Infinispan cache put is not working in loop - spring-boot

I am using embedded cachemanager and i am trying to put entries in cache in for loop but when the next request is fired i am seeing cache empty. Below is my implementation -
EmbeddedCacheManager manager=null;
{
try {
manager = new DefaultCacheManager("src/main/resources/infinispan.xml");
} catch (IOException e) {
e.printStackTrace();
}
}
Cache cache=manager.getCache();
for (JsonElement jsonElement : jsonArray)
{
id=jsonElement.getAsJsonObject().get("_id").getAsString();
id1= id.replace("-","");
JsonObject source = jsonElement.getAsJsonObject().getAsJsonObject("_src");
String jsonString = source.toString();
Dummy dummy = new Gson().fromJson(jsonString, Dummy.class);
if(cache.get(id1)!=null){
retVal.add((Dummy) cache.get(id1));
System.out.println("This is cached !");
}else {
cache.put(id1,dummy);
retVal.add(dummy);
System.out.println("This is not cached");
}
}

Add infinispan-bom to your pom.xml file before the starter dependencies, as follows:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.infinispan</groupId>
<artifactId>infinispan-bom</artifactId>
<version>${version.infinispan}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>${version.spring.boot}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.infinispan</groupId>
<artifactId>infinispan-spring-boot-starter</artifactId>
<version>${version.infinispan.starter}</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependency>
<groupId>org.infinispan</groupId>
<artifactId>infinispan-spring-boot-starter-embedded</artifactId>
<version>${version.infinispan.starter}</version>
</dependency>
your bean should have
private final EmbeddedCacheManager cacheManager;
#Autowired
public YourBean(EmbeddedCacheManager cacheManager) {
this.cacheManager = cacheManager;
}
if you need to customize EmbeddedCacheManager do
#Bean
public InfinispanCacheConfigurer cacheConfigurer() {
return manager -> {
final Configuration ispnConfig = new ConfigurationBuilder()
.clustering()
.cacheMode(CacheMode.LOCAL)
.build();
manager.defineConfiguration("local-sync-config", ispnConfig);
};
}
You will find good examples at https://infinispan.org/infinispan-spring-boot/master/spring_boot_starter.html

Related

Non spring boot app, Spring data jpa save is not working

I have faced with a problem and couldn't find out what's the reason. My Test class which contains save to the database method actually not saving anything to DB with #Transactional annotation. But when I remove #Transactional, it starting to work. I am almost sure that the problem is related to transaction manager, but what is wrong here?
THIS IS NOT WORKING
TestSaveTransactional.java
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(
classes = { HibernateConfiguration.class},
loader = AnnotationConfigContextLoader.class)
public class TestSaveTransactional {
#Autowired
private UserRepository userRepository;
#Test
#Transactional
public void testSaveUsersTransactional(){
System.out.println("**********testSaveUserTransactional**********");
StopWatch watch = new StopWatch();
watch.start();
final List<User> users = new LinkedList<User>();
users.add(new User("He he", true));
users.add(new User("She she", false));
this.userRepository.save(users);
watch.stop();
System.out.println(watch.getTotalTimeMillis() + " mls");
System.out.println("**********testSaveUserTransactional**********");
}
}
pom.xml
http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
<groupId>com.egs</groupId>
<artifactId>test-hibernate</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<springframework.version>4.3.9.RELEASE</springframework.version>
<hibernate.version>4.3.6.Final</hibernate.version>
<pgsql.connector.version>42.2.5</pgsql.connector.version>
<joda-time.version>2.3</joda-time.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.10.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>${pgsql.connector.version}</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${springframework.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
HibernateConfiguration.java
#Configuration
#EnableTransactionManagement
#PropertySource(value = { "classpath:application.properties" })
#ComponentScan(basePackageClasses = { HibernateConfiguration.class })
#EnableJpaRepositories(basePackages = {"com.egs.repository"})
public class HibernateConfiguration {
#Value("${jdbc.driverClassName}") private String driverClassName;
#Value("${jdbc.url}") private String jdbcUrl;
#Value("${jdbc.username}") private String username;
#Value("${jdbc.password}") private String password;
#Value("${hibernate.dialect}") private String hibernateDialect;
#Value("${hibernate.show_sql}") private String showSql;
#Value("${hibernate.format_sql}") private String formatSql;
#Bean
public HibernateJpaVendorAdapter jpaVendorAdapter(){
return new HibernateJpaVendorAdapter();
}
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(jdbcUrl);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean sessionFactory = new LocalContainerEntityManagerFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setJpaVendorAdapter(jpaVendorAdapter());
sessionFactory.setPackagesToScan(
new String[] { "com.egs.entity" });
sessionFactory.setJpaProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public JpaTransactionManager transactionManager() {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory().getObject());
return txManager;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", hibernateDialect);
properties.put("hibernate.show_sql", showSql);
properties.put("hibernate.format_sql", formatSql);
return properties;
}
}
THIS ONE WORKS
TestFindAllHibernate.java
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(
classes = { HibernateConfiguration.class},
loader = AnnotationConfigContextLoader.class)
public class TestFindAllHibernate {
#Autowired private UserRepository userRepository;
#Autowired private PostRepository postRepository;
#Test
#Transactional(readOnly = true)
public void testFindAllUsers(){
System.out.println("**********testFindAllUsers**********");
StopWatch watch = new StopWatch();
watch.start();
System.out.println(this.userRepository.findAll());
watch.stop();
System.out.println(watch.getTotalTimeMillis() + " mls");
System.out.println("**********testFindAllUsers**********");
}
#Test
#Transactional(readOnly = true)
public void testFindAllMaleUsers(){
System.out.println("**********testFindAllMaleUsers**********");
StopWatch watch = new StopWatch();
watch.start();
System.out.println(this.userRepository.findByMaleIsTrue());
watch.stop();
System.out.println(watch.getTotalTimeMillis() + " mls");
System.out.println("**********testFindAllMaleUsers**********");
}
#Test
#Transactional(readOnly = true)
public void testFindAllPosts(){
System.out.println("**********testFindAllPosts**********");
StopWatch watch = new StopWatch();
watch.start();
System.out.println(this.postRepository.findAll());
watch.stop();
System.out.println(watch.getTotalTimeMillis() + " mls");
System.out.println("**********testFindAllPosts**********");
}
}

How to configure Spring Data Rest to return A Json-LD or Siren media type instead of HAL

I have been struggling to find any examples of how one could override the default Spring Boot Data Rest JpaRepository behavior to return something other than a HAL response. I have found that both Siren and Json-LD can meet the requirements but not any examples of how to get it to work with spring. I am using Spring 5, Spring Data Rest 2.0.4.RELEASE.
Please note, I am not looking to do this for a custom rest controller, but for the default repository provided by extending JpaRepository. This is my first time posting so I apologize for any rules I might have inadvertently broken.
Update: I was able to find a library hydra-spring that has a SirenMessageConverter, following the example on the repo I was able to do the following:
#Configuration
#EnablePluginRegistries(RelProvider.class)
public class Config implements WebMvcConfigurer {
private static final boolean EVO_PRESENT =
ClassUtils.isPresent("org.atteo.evo.inflector.English", null);
#Autowired
private PluginRegistry<RelProvider, Class<?>> relProviderRegistry;
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(sirenMessageConverter());
converters.add(hydraMessageConverter());
converters.add(halConverter());
converters.add(uberConverter());
converters.add(xhtmlMessageConverter());
converters.add(jsonConverter());
}
#Bean
public RepositoryRestConfigurerAdapter repositoryRestConfigurer() {
return new RepositoryRestConfigurerAdapter() {
#Override
public void configureHttpMessageConverters(
List<HttpMessageConverter<?>> messageConverters) {
messageConverters.add(0, sirenMessageConverter());
}
};
}
#Bean
public HttpMessageConverter<?> uberConverter() {
UberJackson2HttpMessageConverter converter = new UberJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(Collections.singletonList(HypermediaTypes.UBER_JSON));
return converter;
}
private HttpMessageConverter<?> xhtmlMessageConverter() {
XhtmlResourceMessageConverter xhtmlResourceMessageConverter = new XhtmlResourceMessageConverter();
xhtmlResourceMessageConverter.setStylesheets(
Arrays.asList(
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"
));
xhtmlResourceMessageConverter.setDocumentationProvider(new JsonLdDocumentationProvider());
return xhtmlResourceMessageConverter;
}
#Override
public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
final ExceptionHandlerExceptionResolver resolver = new ExceptionHandlerExceptionResolver();
resolver.setWarnLogCategory(resolver.getClass()
.getName());
exceptionResolvers.add(resolver);
}
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.defaultContentType(HypermediaTypes.SIREN_JSON);
}
#Bean
public HydraMessageConverter hydraMessageConverter() {
return new HydraMessageConverter();
}
#Bean
public SirenMessageConverter sirenMessageConverter() {
SirenMessageConverter sirenMessageConverter = new SirenMessageConverter();
sirenMessageConverter.setRelProvider(new DelegatingRelProvider(relProviderRegistry));
sirenMessageConverter.setDocumentationProvider(new JsonLdDocumentationProvider());
sirenMessageConverter.setSupportedMediaTypes(Collections.singletonList(HypermediaTypes.SIREN_JSON));
return sirenMessageConverter;
}
#Bean
public ObjectMapper jacksonObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
return objectMapper;
}
#Bean
public MappingJackson2HttpMessageConverter jsonConverter() {
MappingJackson2HttpMessageConverter jacksonConverter = new
MappingJackson2HttpMessageConverter();
jacksonConverter.setSupportedMediaTypes(Arrays.asList(MediaType.valueOf("application/json")));
jacksonConverter.setObjectMapper(jacksonObjectMapper());
return jacksonConverter;
}
#Bean
public CurieProvider curieProvider() {
return new DefaultCurieProvider("ex", new UriTemplate("http://localhost:8080/webapp/hypermedia-api/rels/{rels}"));
}
#Bean
public MappingJackson2HttpMessageConverter halConverter() {
CurieProvider curieProvider = curieProvider();
RelProvider relProvider = new DelegatingRelProvider(relProviderRegistry);
ObjectMapper halObjectMapper = new ObjectMapper();
halObjectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
halObjectMapper.registerModule(new Jackson2HalModule());
halObjectMapper.setHandlerInstantiator(new
Jackson2HalModule.HalHandlerInstantiator(relProvider, curieProvider, null));
MappingJackson2HttpMessageConverter halConverter = new
MappingJackson2HttpMessageConverter();
halConverter.setSupportedMediaTypes(Arrays.asList(MediaTypes.HAL_JSON));
halConverter.setObjectMapper(halObjectMapper);
return halConverter;
}
#Bean
RelProvider defaultRelProvider() {
return EVO_PRESENT ? new EvoInflectorRelProvider() : new DefaultRelProvider();
}
#Bean
RelProvider annotationRelProvider() {
return new AnnotationRelProvider();
}
}
This is my current 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.knowledgebase.DataRest</groupId>
<artifactId>DataRest</artifactId>
<version>2.1.0.M2</version>
<packaging>jar</packaging>
<name>DataRest</name>
<description>Demo project for Spring Boot DataRest</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.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>
</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-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-mockmvc</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-hal-browser</artifactId>
</dependency>
<dependency>
<groupId>de.escalon.hypermedia</groupId>
<artifactId>hydra-spring</artifactId>
<version>0.4.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<pluginRepositories>
<pluginRepository>
<id>spring-milestones</id>
<url>http://repo.spring.io/milestone</url>
</pluginRepository>
</pluginRepositories>
</project>
However this still fails to deliver the results I am looking for. I know that some of the changes I introduced in the config class are making a difference since the output now looks like this:
{
"_embedded": {
"ex:contacts": []
},
"_links": {
"self": {
"href": "http://localhost:8080/contacts{?page,size,sort}",
"templated": true
},
"profile": {
"href": "http://localhost:8080/profile/contacts"
},
"search": {
"href": "http://localhost:8080/contacts/search"
},
"curies": [
{
"href": "http://localhost:8080/webapp/hypermedia-api/rels/{rels}",
"name": "ex",
"templated": true
}
]
},
"page": {
"size": 20,
"totalElements": 0,
"totalPages": 0,
"number": 0
}
}
As you can see the Curries provider is the only thing that actually works. For some reason spring boot data rest JpaRepository does not change the default application type to SIREN_JSON despite the:
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.defaultContentType(HypermediaTypes.SIREN_JSON);
}

Error while connecting to AWS SQS from spring boot

I am trying to integrate AWS SQS into my springboot app using spring cloud AWS, but keep getting this error(posted below), can someone help?
Here are my files.
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'simpleMessageListenerContainer' defined in
class path resource
[org/springframework/cloud/aws/messaging/config/annotation/SqsConfiguration.class]:
Invocation of init method failed; nested exception is
java.lang.NoSuchMethodError:
com.amazonaws.http.ExecutionContext.setCredentials(Lcom/amazonaws/auth/AWSCredentials;)V
#Configuration
public class AWSConfig {
#Value("${amazon.dynamodb.endpoint}")
private String amazonDynamoDBEndpoint;
#Value("${amazon.aws.accesskey}")
private String amazonAWSAccessKey;
#Value("${amazon.aws.secretkey}")
private String amazonAWSSecretKey;
#Value("${amazon.sqs.endpoint}")
private String amazonSqsEndpoint;
#Bean
#Primary
public AmazonSQSAsyncClient amazonSQSAsyncClient() {
AmazonSQSAsyncClient amazonSQSAsyncClient = new AmazonSQSAsyncClient(amazonAWSCredentials());
if (!StringUtils.isEmpty(amazonSqsEndpoint)) {
amazonSQSAsyncClient.setEndpoint(amazonSqsEndpoint);
}
return amazonSQSAsyncClient;
}
#Bean
public AWSCredentials amazonAWSCredentials() {
return new BasicAWSCredentials(amazonAWSAccessKey, amazonAWSSecretKey);
}
}
I am able to work with dynamodb with this but not able to connect to SQS.
I have given the correct access key, secret access key and end point in application.properties file.
#Component
#EnableSqs
public class SQSDao {
private static final Logger logger = LoggerFactory.getLogger(SQSDao.class);
private QueueMessagingTemplate queueMessagingTemplate;
#Autowired
public SQSDao(AmazonSQSAsync amazonSqs) {
this.queueMessagingTemplate = new QueueMessagingTemplate(amazonSqs);
}
public void send(String message) {
System.out.println(queueMessagingTemplate.getDefaultDestination());
queueMessagingTemplate.convertAndSend("test-queue", MessageBuilder.withPayload(message).build());
}
#SqsListener(value = "test-queue", deletionPolicy = SqsMessageDeletionPolicy.NEVER)
public void receive(String message)
{
System.out.println("message: " + message);
}
}
I was facing the same issue as described. My solution requeried implement some extra methods for the Config class:
imports [...]
#Configuration
#RefreshScope
public class SpringCloudSQSConfig {
#Value("${cloud.aws.credentials.accessKeyId:default}")
private String accessKeyId;
#Value("${cloud.aws.credentials.secretKey:default}")
private String secretKey;
#Value("${cloud.aws.region.static:default}")
private String region;
private Logger logger = LoggerFactory.getLogger(this.getClass());
#Bean
public QueueMessagingTemplate queueMessagingTemplate() {
return new QueueMessagingTemplate(amazonSQSAsync());
}
public AmazonSQSAsync amazonSQSAsync() {
return AmazonSQSAsyncClientBuilder.standard().withRegion(Regions.US_EAST_2)
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKeyId, secretKey)))
.build();
}
#Bean
public SimpleMessageListenerContainerFactory simpleMessageListenerContainerFactory() {
SimpleMessageListenerContainerFactory msgListenerContainerFactory = new SimpleMessageListenerContainerFactory();
msgListenerContainerFactory.setAmazonSqs(amazonSQSAsync());
return msgListenerContainerFactory;
}
#Bean
public QueueMessageHandler queueMessageHandler() {
QueueMessageHandlerFactory queueMsgHandlerFactory = new QueueMessageHandlerFactory();
queueMsgHandlerFactory.setAmazonSqs(amazonSQSAsync());
QueueMessageHandler queueMessageHandler = queueMsgHandlerFactory.createQueueMessageHandler();
List<HandlerMethodArgumentResolver> list = new ArrayList<>();
HandlerMethodArgumentResolver resolver = new PayloadArgumentResolver(new MappingJackson2MessageConverter());
list.add(resolver);
queueMessageHandler.setArgumentResolvers(list);
return queueMessageHandler;
}
}
And for the dependencies implemented:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-aws</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-aws-messaging</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
and adding the next property in the properties file:
spring.main.allow-bean-definition-overriding=true
I was able to fix this problem by adding the last line shown to my application.yml during local testing
spring:
autoconfigure:
exclude:
- org.springframework.cloud.aws.autoconfigure.context.ContextStackAutoConfiguration
- org.springframework.cloud.aws.autoconfigure.context.ContextRegionProviderAutoConfiguration
I resolved it by removing duplicate dependencies :
aws-xray-recorder-sdk-aws-sdk
aws-xray-recorder-sdk-aws-sdk-v2
aws-xray-recorder-sdk-aws-sdk-instrumentor
aws-xray-recorder-sdk-aws-sdk-v2-instrumentor
Before :
<!-- AWS X-Ray -->
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-xray-recorder-sdk-core</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-xray-recorder-sdk-apache-http</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-xray-recorder-sdk-aws-sdk</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-xray-recorder-sdk-aws-sdk-v2</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-xray-recorder-sdk-aws-sdk-instrumentor</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-xray-recorder-sdk-aws-sdk-v2-instrumentor</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-xray-recorder-sdk-sql-postgres</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-xray-recorder-sdk-spring</artifactId>
</dependency>
After:
<!-- AWS X-Ray -->
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-xray-recorder-sdk-core</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-xray-recorder-sdk-apache-http</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-xray-recorder-sdk-aws-sdk-v2</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-xray-recorder-sdk-aws-sdk-v2-instrumentor</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-xray-recorder-sdk-sql-postgres</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-xray-recorder-sdk-spring</artifactId>
</dependency>
Fixed it, apparently issue was related to dependency mix up as mentioned here

Spring boot Turbine.stream with ssl Not working

We are trying to enable https in turbine stream. And we are facing below problem:
ERROR 10644 --- [o-eventloop-3-1] r.n.p.h.s.ServerRequestResponseConverter : Invalid HTTP request recieved. Decoder error.
java.lang.IllegalArgumentException: invalid version format: ■\ᅦ:4'|"￀+￀/￀,￀0ᅩ로또ᅩ￀ ￀￀
at io.netty.handler.codec.http.HttpVersion.<init>(HttpVersion.java:130) ~[netty-codec-http-4.0.27.Final.jar!/:4.0.27.Final]
at io.netty.handler.codec.http.HttpVersion.valueOf(HttpVersion.java:84) ~[netty-codec-http-4.0.27.Final.jar!/:4.0.27.Final]
Please provide any suggestion
Thank you.
UPDATE
Do we need to enable ssl to message broker which is handling the stream
Code
#SpringBootApplication
#RestController
#EnableDiscoveryClient
#EnableTurbineStream
public class DemoHystrixApplication {
public static void main(String[] args) {
SpringApplication.run(DemoHystrixApplication.class, args);
}
#RequestMapping(value ="/test")
public String helloHystrix() {
ObjectMapper mapper = new ObjectMapper();
String output = null;
try {
output = mapper.writeValueAsString("{ \"message\" : \"test : Welcome to test Notification Detail Page.\"}");
} catch (JsonProcessingException e) {
e.getMessage();
}
return output;
}
#RequestMapping(value ="/test2")
public String testhello() {
ObjectMapper mapper = new ObjectMapper();
String output = null;
try {
output = mapper.writeValueAsString("{ \"message\" : \"test : Welcome to test1 Page.\"}");
} catch (JsonProcessingException e) {
e.getMessage();
}
return output;
}
}
POM Dependency
<dependencies>
<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.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-turbine-stream</artifactId>
<version>1.1.5.BUILD-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-kafka</artifactId>
</dependency>
</dependencies>
application.properties
server.port=8083
spring.cloud.consul.host=localhost
spring.cloud.consul.port=8500
spring.application.name=testApp
security.basic.enabled=false
eureka.client.enabled=false
server.ssl.key-store=consul.pfx
server.ssl.key-password=changeit
server.ssl.key-store-type=PKCS12
server.ssl.trust-store=root.pfx
server.ssl.trust-store-password=changeit
server.ssl.trust-store-type=PKCS12
spring.cloud.consul.discovery.scheme=https

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