Showing posts with label Spring. Show all posts
Showing posts with label Spring. Show all posts

Tuesday, March 17, 2020

Apache HTTP Server HTTPD + SpringBoot Application


 (Tested working fine with the following)



Enable the following modules:

LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so


First we need to add the following to virtual host definition in httpd.conf  of Apache Server

ProxyPass / http://127.0.0.1:8080/
ProxyPassReverse / http://127.0.0.1:8080/

Example:



<VirtualHost *:8080>
  
    ProxyPass / http://127.0.0.1:8081/example/   # Spring Boot Application URL
    ProxyPassReverse / http://127.0.0.1:8081/example/  # Spring Boot Application URL

</VirtualHost>

Tuesday, March 3, 2020

To configure EhCache to Spring Boot Application

To configure EhCache to Spring Boot Application

First we have to add the following maven dependency to Application (Note versions will be taken care by spring boot starter (which we have added initial setup))
		
                
			org.springframework.boot
			spring-boot-starter-cache
		

		
			javax.cache
			cache-api
		

		
			org.ehcache
			ehcache
		

Add the following class to application as setup
	package com.nagarajuconfig;

import java.util.concurrent.TimeUnit;

import javax.cache.CacheManager;
import javax.cache.Caching;
import javax.cache.configuration.FactoryBuilder;
import javax.cache.configuration.MutableCacheEntryListenerConfiguration;
import javax.cache.configuration.MutableConfiguration;
import javax.cache.expiry.CreatedExpiryPolicy;
import javax.cache.expiry.Duration;
import javax.cache.spi.CachingProvider;

import org.springframework.stereotype.Component;

@Component
public class CacheSetup {

	public CacheManager cacheManager() {
		CachingProvider provider = Caching.getCachingProvider();
		CacheManager cacheManager = provider.getCacheManager();

		cacheManager.createCache("cacheName", getCacheConfiguration());

		return cacheManager;
	}

	private MutableConfiguration getCacheConfiguration() {
		return new MutableConfiguration().setTypes(Object.class, Object.class).setStoreByValue(false)
				.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.MINUTES, 1)))
				.setStatisticsEnabled(true);
	}

}

Add the following to service layer or dao layer ..I have added in the service Layer.
	@Override
	/* @Cacheable(cacheNames = "controllerParamData",key="#controllerId") */
	@CacheResult(cacheName = "controllerParamData")
	public List getParamData(Long controllerId, String type, String sort, Integer count,
			Long startTime, Long endTime, List paramKey)
Now enable the Cache
	package com.nagaraju.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.jcache.JCacheCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 
 */
@Configuration
@EnableCaching
public class CacheConfiguration {

	@Autowired
	private CacheSetup cacheSetup;
	
	@Bean
	JCacheCacheManager jCacheCacheManager() {
		return new JCacheCacheManager(cacheSetup.cacheManager());
	}

}

Run application, then will setup the cache automatically.

Wednesday, February 26, 2020

Invalidate Session on Spring @ControllerAdvice

Problem:

When some exception comes in spring web application, some times we have to redirect the page some exception jsp/html page .
we have to fix this problem in ControllerAdvice Class.

Solution:

        
    @ExceptionHandler(ResourceAccessException.class)
    public ModelAndView handleResourceAccessException(ResourceAccessException ex,HttpServletRequest request) {
      LOG.error(START);
      HttpSession session= request.getSession(false);
        SecurityContextHolder.clearContext();
         if(session != null) {
             session.invalidate();
         }
        ModelAndView model = new ModelAndView();
        LOG.error(MESSAGE,ex.getMessage());
        model.setViewName("generic_page");
        LOG.error(END);
        return model;
    }
  • we get the session Object from HttpServletRequest object and checks the null condition and after that we have invalidated the session.
  • Important point

    is that we have write this statment : SecurityContextHolder.clearContext(); otherwise Spring Security will not identify our session invalidation.

Tuesday, July 31, 2018

SpringRest GET calls showing the HTML Page for Invalid API -- throwExceptionIfNoHandlerFound

In Spring Framework, there are number of ways of handing exceptions (and particularly 404 error). Here is a documentation link.
  • First, you can still use error-page tag in web.xml, and customize error page. Here is an example.
  • Second, you can use one @ExceptionHandler for all controllers, like this:
    @ControllerAdvice
    public class ControllerAdvisor {
    
         @ExceptionHandler(NoHandlerFoundException.class)
         public String handle(Exception ex) {
    
            return "404";//this is view name
        }
    }
    For this to work, set throwExceptionIfNoHandlerFound property to true for DispatcherServletin web.xml:
    <init-param>
        <param-name>throwExceptionIfNoHandlerFound</param-name>
        <param-value>true</param-value>
    </init-param>
    You can also pass some objects to error view, see javadoc for this.

Thursday, January 18, 2018

Problem : No 'Access-Control-Allow-Origin' header is present on the requested resource”

public class CORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        chain.doFilter(req, res);

    }

And adding these details in web.xml file 

Spring MVC 3.1 and JasperReports

Spring MVC – Redirecting model attributes from one controller to other controller

Multiple Mongo Instanaces In Spring Mongo DB

Spring MVC Interceptor HandlerInterceptorAdapter, HandlerInterceptor Example

https://www.journaldev.com/2676/spring-mvc-interceptor-example-handlerinterceptor-handlerinterceptoradapter  

Recent Post

Databricks Delta table merge Example

here's some sample code that demonstrates a merge operation on a Delta table using PySpark:   from pyspark.sql import SparkSession # cre...