Spring data Redis to Elastic Cache Connection Checklist - java

How to connect to AWS ELasticCache Redis Cluster using Spring-data-redis.
I am using redis as a datastore and would like to achieve
High availability
Low Latency
Assuming :
Auth required
Data encryption at transit required
Cluster mode on

package com.example.config;
import java.time.Duration;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
#Configuration
public class RedisConfiguration {
#Bean
public JedisClientConfiguration getJedisClientConfiguration(#Value("$REDIS_CONNECTION_TIMEOUT}") final Duration timeout) {
JedisClientConfiguration.JedisClientConfigurationBuilder jedisClientConfigurationBuilder = JedisClientConfiguration.builder();
jedisClientConfigurationBuilder.connectTimeout(timeout);
jedisClientConfigurationBuilder.usePooling();
return jedisClientConfigurationBuilder.build();
}
#Bean
public RedisClusterConfiguration getRedisClusterConfiguration(#Value("${REDIS_HOST}") final String host,
#Value("${REDIS_PORT}") final Integer port) {
RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration();
redisClusterConfiguration = redisClusterConfiguration.clusterNode(host, port);
return redisClusterConfiguration;
}
#Bean
public JedisConnectionFactory jedisConnectionFactory(
#Qualifier("getRedisClusterConfiguration") final RedisClusterConfiguration redisClusterConfiguration,
#Qualifier("getJedisClientConfiguration") final JedisClientConfiguration jedisClientConfiguration) {
JedisConnectionFactory connectionFactory = new JedisConnectionFactory(redisClusterConfiguration, jedisClientConfiguration);
return connectionFactory;
}
}
Missing
shrad
auth
Data encryption ..To be done at AWS ElastiCache

Related

Getting an error message when I try to send a message through RabbitMQ

I am getting this message when I try to send a message: Cannot invoke "org.springframework.amqp.core.DirectExchange.getName()" because "this.directExchange" is null although I made the right on configiration for rabbitmq according to their documentation.
package com.todoist.server.config;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
public class ClientConfig {
#Value("thequeue")
private String queueName;
#Value("xchange")
private String directXchangeName;
#Bean
public Queue queue() {
return new Queue(queueName);
}
#Bean
public DirectExchange directExchange() {
return new DirectExchange(directXchangeName);
}
#Bean
public Binding binding(DirectExchange exchange, Queue queue) {
return BindingBuilder.bind(queue).to(exchange).with("routing_key");
}
}
I am using springboot and I am trying to do the RPC pattern.

Spring IntegrationFlow with RestController

I would like to create an application that would perform the following steps:
Receive request thru RestController
Send the received message to a queue (AMQP - MessageChannel) (correlationId?)
Wait for the reply in another queue (AMQP - MessageChannel) (correlationId?)
Return the response on the same thread as the request in step 1.
I thought about using IntegrationFlow for this, but I'm not able to adapt the steps.
Besides, would you know what is the best way to implement this flow?
I tried to implement with the following code:
package poc.integration.http;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.integration.amqp.channel.PollableAmqpChannel;
import org.springframework.integration.amqp.dsl.Amqp;
import org.springframework.integration.amqp.outbound.AmqpOutboundEndpoint;
import org.springframework.integration.amqp.support.DefaultAmqpHeaderMapper;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.config.EnableIntegration;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.dsl.IntegrationFlows;
import org.springframework.integration.http.dsl.Http;
import org.springframework.integration.http.inbound.HttpRequestHandlingMessagingGateway;
import org.springframework.integration.http.inbound.RequestMapping;
import org.springframework.integration.http.outbound.HttpRequestExecutingMessageHandler;
import org.springframework.integration.scheduling.PollerMetadata;
import org.springframework.messaging.MessageChannel;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
#Configuration
#EnableIntegration
public class IntegrationFlowConfig {
final Logger logger = LoggerFactory.getLogger(IntegrationFlowConfig.class);
#Bean
public HttpRequestHandlingMessagingGateway inbound() {
HttpRequestHandlingMessagingGateway gateway = new HttpRequestHandlingMessagingGateway(true);
gateway.setRequestMapping(mapping());
gateway.setRequestPayloadTypeClass(String.class);
gateway.setRequestChannelName("httpRequest");
return gateway;
}
#Bean
public RequestMapping mapping() {
RequestMapping requestMapping = new RequestMapping();
requestMapping.setPathPatterns("/foo");
requestMapping.setMethods(HttpMethod.GET);
return requestMapping;
}
#ServiceActivator(inputChannel = "httpResponse")
#Bean
public HttpRequestExecutingMessageHandler outbound() {
HttpRequestExecutingMessageHandler handler =
new HttpRequestExecutingMessageHandler("http://10.141.201.206:80/foo");
handler.setHttpMethod(HttpMethod.GET);
handler.setExpectedResponseType(String.class);
return handler;
}
#ServiceActivator(inputChannel="httpRequest", outputChannel="httpResponse")
public Object processarMensagem(Object mensagem) {
return mensagem + " - done";
}
#Bean(name = PollerMetadata.DEFAULT_POLLER)
public PollerMetadata pollerAmqp(ThreadPoolTaskScheduler taskScheduler) {
final PollerMetadata poller = new PollerMetadata();
poller.setTaskExecutor(taskScheduler);
poller.setReceiveTimeout(-1);
return poller;
}
#Bean
public MessageChannel httpRequest(AmqpTemplate amqpTemplate) {
PollableAmqpChannel channel = new PollableAmqpChannel("httpRequest", amqpTemplate,
DefaultAmqpHeaderMapper.outboundMapper(), DefaultAmqpHeaderMapper.inboundMapper());
channel.setExtractPayload(true);
return channel;
}
#Bean
public MessageChannel httpResponse(AmqpTemplate amqpTemplate) {
PollableAmqpChannel channel = new PollableAmqpChannel("httpResponse", amqpTemplate,
DefaultAmqpHeaderMapper.outboundMapper(), DefaultAmqpHeaderMapper.inboundMapper());
channel.setExtractPayload(true);
return channel;
}
}
but i'm receiving the message:
No reply received within timeout
You just need an IntegrationFlow with an Http.inboundControllerAdapter() as a starting point. It fully replaces the mentioned RestController, but let you to avoid extra work bridging from the #RestController to the IntegrationFlow and back.
The next step in the flow should be an Amqp.outboundGateway() to send and receive over AMQP. This one takes care about a correlation for you.
See more in docs:
https://docs.spring.io/spring-integration/docs/5.3.0.RELEASE/reference/html/http.html#http-java-config
https://docs.spring.io/spring-integration/docs/5.3.0.RELEASE/reference/html/amqp.html#configuring-with-the-java-dsl-4

Spring Boot OAuth Ressource Server Proxy Configuration

I am currently struggeling using a proxy in combination with Spring-Webflux. In other services I always followed this approach, which worked perfectly (proxy configuration is retrieved from standard environment variables):
#Bean
public RestTemplate restTemplate() {
final RestTemplate restTemplate = new RestTemplate();
final CloseableHttpClient client = HttpClientBuilder.create().useSystemProperties().build();
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(client));
return restTemplate;
}
But now I am trying to setup an OAuth-Ressource-Server using the Spring Oauth-Resource-Server package. This package uses the Spring-Webflux for HTTP(S). The service now tries to fetch the jwk-set from the given uri (proxy needed) and fails because of a connection refused error. Did anyone get a combination of Spring-Webflux/OAuth-Ressource and proxy working?
Found out by myself that providing a NimbusReactiveJwtDecoder bean with a correctly configured webclient solves the problem.
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.security.oauth2.jwt.NimbusReactiveJwtDecoder;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;
import reactor.netty.tcp.ProxyProvider;
#Data
#Component
#Configuration
#ConfigurationProperties(value = "proxy")
public class ProxyConfig {
private String host;
private int port;
private String username;
private String password;
#Value("${spring.security.oauth2.resourceserver.jwt.jwk-set-uri}")
private String jwkSetUri;
#Bean
public WebClient webClient(ReactorClientHttpConnector reactorClientHttpConnector) {
return WebClient.builder().clientConnector(reactorClientHttpConnector).build();
}
#Bean
public HttpClient httpClient() {
return HttpClient.create()
.tcpConfiguration(tcpClient ->
tcpClient.proxy(
proxy -> proxy.type(ProxyProvider.Proxy.HTTP).host(host)
.port(port).username(username)
.password(s -> password)));
}
#Bean
ReactorClientHttpConnector reactorClientHttpConnector(HttpClient httpClient) {
return new ReactorClientHttpConnector(httpClient);
}
#Bean
public NimbusReactiveJwtDecoder nimbusReactiveJwtDecoder(WebClient webClient) {
return NimbusReactiveJwtDecoder
.withJwkSetUri(jwkSetUri)
.webClient(webClient).build();
}
}

Why requests are returned 404 status when using WebFilter corsFilter in webflux?

I want to build a REST api in Spring Webflux using functional endpoints. For CORS I use a WebFilter corsFilter method which sets the required headers. I do see that the method is called (I see the log messages from it) and I see that the headers on the response are indeed the ones I set in my Webflux api. However, as soon as I started to use the corsFilter the requests return 404 status (earlier they would return JSON). I suspect that corsFilter doesn't pass over the request to the router functions. Why would that be?
Specifically I'm wondering if this line is enough to connect the cors config with the routes:
HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler(RouterFunctions.toWebHandler(route))
.applicationContext(ctx).build();
This is my main class:
package com.mypackage;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.server.adapter.WebHttpHandlerBuilder;
import reactor.ipc.netty.http.server.HttpServer;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerResponse;
import static org.springframework.http.HttpStatus.UNAUTHORIZED;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RequestPredicates.POST;
import static org.springframework.web.reactive.function.server.RequestPredicates.accept;
import static org.springframework.web.reactive.function.server.RequestPredicates.contentType;
import static org.springframework.web.reactive.function.server.RequestPredicates.method;
import static org.springframework.web.reactive.function.server.RequestPredicates.path;
import static org.springframework.web.reactive.function.server.RouterFunctions.nest;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler;
#SpringBootApplication
public class Server {
private static final Logger log = LogManager.getLogger(Server.class);
public static final String HOST = "localhost";
public static final int PORT = 8080;
public static void main(String[] args) throws Exception {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(CorsConfiguration.class);
Server server = new Server();
server.startReactorServer(ctx);
System.out.println("Press ENTER to exit.");
System.in.read();
}
public RouterFunction<ServerResponse> routingFunction() {
PersonRepository repository = new DummyPersonRepository();
PersonHandler handler = new PersonHandler(repository);
return nest(path("/person"),
nest(accept(APPLICATION_JSON),
route(GET("/{id}"), handler::getPerson)
.andRoute(method(HttpMethod.GET), handler::listPeople)
).andRoute(POST("/").and(contentType(APPLICATION_JSON)), handler::createPerson));
}
public void startReactorServer(AnnotationConfigApplicationContext ctx) {
RouterFunction<ServerResponse> route = this.routingFunction().filter((request, next) -> {
log.warn(request.path());
if (request.path().contains("person")) {
log.warn("calling next()");
return next.handle(request);
} else {
return ServerResponse.status(UNAUTHORIZED).build();
}
});
HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler(RouterFunctions.toWebHandler(route))
.applicationContext(ctx).build();
ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler);
HttpServer server = HttpServer.create(HOST, PORT);
server.newHandler(adapter).block();
}
}
and this is my CORS config class:
package com.mypackage;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.cors.reactive.CorsUtils;
import org.springframework.web.reactive.config.EnableWebFlux;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
#Configuration
#EnableWebFlux
public class CorsConfiguration {
private static final Logger log = LogManager.getLogger(CorsConfiguration.class);
private static final String ALLOWED_HEADERS = "x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN, mode";
private static final String ALLOWED_METHODS = "GET, PUT, POST, DELETE, OPTIONS";
private static final String ALLOWED_ORIGIN = "*";
private static final String MAX_AGE = "3600";
#Bean
public WebFilter corsFilter() {
log.warn("from CorsConfiguration!!!");
return (ServerWebExchange ctx, WebFilterChain chain) -> {
ServerHttpRequest request = ctx.getRequest();
log.warn("after ServerHttpRequest");
if (CorsUtils.isCorsRequest(request)) {
log.warn("inside isCorsRequest");
ServerHttpResponse response = ctx.getResponse();
HttpHeaders headers = response.getHeaders();
headers.add("Access-Control-Allow-Origin", ALLOWED_ORIGIN);
headers.add("Access-Control-Allow-Methods", ALLOWED_METHODS);
headers.add("Access-Control-Max-Age", MAX_AGE);
headers.add("Access-Control-Allow-Headers", ALLOWED_HEADERS);
if (request.getMethod() == HttpMethod.OPTIONS) {
response.setStatusCode(HttpStatus.OK);
return Mono.empty();
}
}
return chain.filter(ctx);
};
}
}
To use the functional approach when defining your endpoints Spring Boot's official documentation has a very simple example.
FooBarApplication.class this is our main class.
#SpringBootApplication
public class FooBarApplication {
public static void main(String[] args) {
SpringApplication.run(FooBarApplication.class, args);
}
}
RoutingConfiguration.class (or whatever you wanna call it)
#Configuration
public class RoutingConfiguration {
#Bean
public RouterFunction<ServerResponse> monoRouterFunction(UserHandler userHandler) {
return route(GET("/{user}").and(accept(APPLICATION_JSON)), userHandler::getUser)
.andRoute(GET("/{user}/customers").and(accept(APPLICATION_JSON)), userHandler::getUserCustomers)
.andRoute(DELETE("/{user}").and(accept(APPLICATION_JSON)), userHandler::deleteUser);
}
}
#Component
public class UserHandler {
public Mono<ServerResponse> getUser(ServerRequest request) {
// ...
}
public Mono<ServerResponse> getUserCustomers(ServerRequest request) {
// ...
}
public Mono<ServerResponse> deleteUser(ServerRequest request) {
// ...
}
}
any class annotated with #Configuration will be run at startup and run all #Bean annotated methods. So this will run the monoRouterFunction and set up all our routes for us.
Example taken from the official spring boot documentation Spring boot webflux scroll down a little bit.
EDIT:
and as a side note the #EnableWebFlux annotation means that you will disable the auto-configuration of webflux and set upp configuration manually. I do not recommend this if you are just starting out (i know the name is very misleading) you can read about the webflux auto-configuration here Spring WebFlux Auto-configuration
EDIT2:
WebFlux has a built in CorsFilter that you can use all you need is to configure it.
#Bean
CorsWebFilter corsWebFilter() {
CorsConfiguration corsConfig = new CorsConfiguration();
corsConfig.setAllowedOrigins(Arrays.asList("http://allowed-origin.com"));
corsConfig.setMaxAge(8000L);
corsConfig.addAllowedMethod("PUT");
corsConfig.addAllowedHeader("Baeldung-Allowed");
UrlBasedCorsConfigurationSource source =
new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfig);
return new CorsWebFilter(source);
}
Example taken from Enabling CORS with a WebFilter

How to fix OPTIONS 401 unauthorised error in spring rest and ajax?

I am trying to make a get request for an api which is in sprint mvc rest, I get the below error in the console:
OPTIONS http://localhost:8080/api/users/travel-plan/1 401 (Unauthorized)
Access to XMLHttpRequest at 'http://localhost:8080/api/users/travel-plan/1' from origin 'http://localhost:8585' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Below is the code for the ajax request:
axios.get('http://localhost:8080/api/users/travel-plan/1',{
headers: {
'Access-Control-Allow-Origin': '*',
Authorization: 'Basic' + btoa('xlz#wwe.com' + ":" + 'thepass')
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Please refer the code below for the controller:
package com.travelplanner.rest.controller;
//COPY
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.travelplanner.rest.entity.UserDetails;
import com.travelplanner.rest.entity.TravelPlans;
import com.travelplanner.rest.service.UserService;
#RestController
#RequestMapping("/api")
public class UserRestController {
#Autowired
private UserService userService;
#Autowired
private UserDetailsManager userDetailsManager;
private PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
private boolean doesUserExist(String username) {
boolean exists = userDetailsManager.userExists(username);
return exists;
}
// API to add user
#PostMapping("/user/register")
public UserDetails addUser(#RequestBody UserDetails userDetails) {
if(!doesUserExist(userDetails.getEmail())) {
String encodedPassword = passwordEncoder.encode(userDetails.getPassword());
encodedPassword="{bcrypt}"+encodedPassword;
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
User user = new User(userDetails.getEmail(), encodedPassword, authorities);
userDetailsManager.createUser(user);
userDetails.setId(0);
userService.saveUser(userDetails);
return userDetails;
}else {
return null;
}
}
// API to get user/login
#PostMapping("/users/{email}")
public UserDetails authUser(#PathVariable String email) {
return userService.getUser(email);
}
// API to add travel plan
#PostMapping("/users/travel-plan/{userId}")
public TravelPlans addTravelPlan(#RequestBody TravelPlans travelPlan, #PathVariable int userId) {
userService.saveTravelPlan(travelPlan, userId);
return travelPlan;
}
// API to update travel plan
#PutMapping("/users/travel-plan/{userId}")
public TravelPlans updateTravelPlan(#RequestBody TravelPlans travelPlan, #PathVariable int userId) {
userService.updateTravelPlan(travelPlan, userId);
return travelPlan;
}
// API to get travel plans
#GetMapping("/users/travel-plan/{userId}")
public List<TravelPlans> getTravelPlans(#PathVariable int userId) {
return userService.getTravelPlans(userId);
}
// API to delete travel plan
#DeleteMapping("/users/travel-plan/{planId}")
public String deleteTravelPlan(#PathVariable int planId) {
userService.deleteTravelPlan(planId);
return "Deleted the travel plan with id: " + planId;
}
}
I have tried adding the #CrossOrigin(origins="http://localhost8585") and also tried putting .cors().disable at the beginning and end of the http trail in the config.java but nothing seemed to work. I still get the above message in the console.
Please refer the ode below for the congfig.java:
package com.travelplanner.rest.config;
import java.beans.PropertyVetoException;
import java.util.Properties;
import java.util.logging.Logger;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import com.mchange.v2.c3p0.ComboPooledDataSource;
#Configuration
#EnableWebMvc
#EnableTransactionManagement
#ComponentScan("com.travelplanner.rest")
#PropertySource({ "classpath:persistence-mysql.properties" })
public class DemoAppConfig implements WebMvcConfigurer {
#Autowired
private Environment env;
private Logger logger = Logger.getLogger(getClass().getName());
#Bean
public DataSource myDataSource() {
// create connection pool
ComboPooledDataSource myDataSource = new ComboPooledDataSource();
// set the jdbc driver
try {
myDataSource.setDriverClass("com.mysql.jdbc.Driver");
}
catch (PropertyVetoException exc) {
throw new RuntimeException(exc);
}
// for sanity's sake, let's log url and user ... just to make sure we are reading the data
logger.info("jdbc.url=" + env.getProperty("jdbc.url"));
logger.info("jdbc.user=" + env.getProperty("jdbc.user"));
// set database connection props
myDataSource.setJdbcUrl(env.getProperty("jdbc.url"));
myDataSource.setUser(env.getProperty("jdbc.user"));
myDataSource.setPassword(env.getProperty("jdbc.password"));
// set connection pool props
myDataSource.setInitialPoolSize(getIntProperty("connection.pool.initialPoolSize"));
myDataSource.setMinPoolSize(getIntProperty("connection.pool.minPoolSize"));
myDataSource.setMaxPoolSize(getIntProperty("connection.pool.maxPoolSize"));
myDataSource.setMaxIdleTime(getIntProperty("connection.pool.maxIdleTime"));
return myDataSource;
}
private Properties getHibernateProperties() {
// set hibernate properties
Properties props = new Properties();
props.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
props.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
return props;
}
// need a helper method
// read environment property and convert to int
private int getIntProperty(String propName) {
String propVal = env.getProperty(propName);
// now convert to int
int intPropVal = Integer.parseInt(propVal);
return intPropVal;
}
#Bean
public LocalSessionFactoryBean sessionFactory(){
// create session factorys
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
// set the properties
sessionFactory.setDataSource(myDataSource());
sessionFactory.setPackagesToScan(env.getProperty("hibernate.packagesToScan"));
sessionFactory.setHibernateProperties(getHibernateProperties());
return sessionFactory;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
// setup transaction manager based on session factory
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactory);
return txManager;
}
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*");;
}
}
Please help!
Thanks in advance.
Its work for me with:
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}

Categories

Resources