Mountain View


Spring practice

Posted On : 11-Oct-2018 [231]


----Spring boot-------------



package com.rs.aegon.combisite.config;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan(basePackages="com.rs.aegon")
public class CombiservicesApplication /*extends SpringBootServletInitializer*/ {

	public static void main(String[] args) {
		SpringApplication.run(CombiservicesApplication.class, args);
	}
	
	/*@Override
	protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
		return application.sources(CombiservicesApplication.class);
	}*/
}

==========Spring boot ==========


Key components in Spring boot


Spring Boot Starters
Spring Boot AutoConfigurator
Spring Boot CLI
Spring Boot Actuator

Spring Boot Initilizr 
Spring Boot IDEs


Spring Boot Starters :

The main responsibility of Spring Boot Starter is to combine
a group of common or related dependencies into single dependencies


Spring Boot AutoConfigurator = @ComponentScan + @Configuration + @EnableAutoConfiguration

Spring Boot CLI = Command line interface to run Spring boot application

Spring Boot Actuator =  Provides spring boot applications metrics


Spring Boot Initilizr 

Spring Boot Initilizr With Web Interface
Spring Boot Initilizr With IDEs/IDE Plugins
Spring Boot Initilizr With Spring Boot CLI
Spring Boot Initilizr With Third Party Tools

----rest clent-------------


@SuppressWarnings("deprecation")
	public String getCombiServiceResponse(Object obj, String url, String jsonUrl) {
		logger.info("MuleServiceUtil::getCombiServiceResponse::start");
		String responseString = "";
		try {
			HttpClient httpClient = HttpClientBuilder.create().build();

			logger.info("MuleServiceUtil::getCombiServiceResponse::url = {}" , url);
			HttpPost postRequest = new HttpPost(url);
			ObjectMapper mapper = new ObjectMapper();
			String jsonInString = mapper.writeValueAsString(obj);
			logger.info("String:::: {}" , jsonInString);
			StringEntity input = new StringEntity(jsonInString);
			input.setContentType(MuleMasterConstants.APPLICATION_JSON);
			postRequest.setEntity(input);
			postRequest.setHeader(MuleMasterConstants.USER_NAME, MuleMasterConstants.VAM_USER);
			postRequest.setHeader(MuleMasterConstants.PASSWORD, MuleMasterConstants.PASSW0RD);
			HttpResponse response = httpClient.execute(postRequest);
			HttpEntity entity = response.getEntity();
			responseString = EntityUtils.toString(entity, MuleMasterConstants.UTF_8);
			logger.info("MuleServiceUtil::getCombiServiceResponse::responseString = {}" , responseString);
			if (response.getStatusLine().getStatusCode() != 200) {
				throw new MuleException(MuleMasterConstants.HTTP_ERROR_CODE + response.getStatusLine().getStatusCode());
			}
			httpClient.getConnectionManager().closeExpiredConnections();
		} catch (MalformedURLException e) {
			logger.error("MalformedURLException in getCombiServiceResponse method ", e);
		} catch (IOException e) {
			logger.error("IOException in getCombiServiceResponse method ", e);
		}
		logger.info("MuleServiceUtil::getCombiServiceResponse::end");
		return responseString;
	}

=======================================

@SuppressWarnings("deprecation")
	public String getMuleResponseAegon(Object obj,String url,String jsonUrl, String token, String key){
		logger.info("MuleServiceUtil::getMuleResponse::start");
		String responseString = "";
		try{
			HttpClient httpClient = HttpClientBuilder.create().build();
			
			logger.info("MuleServiceUtil::getMuleResponse::url = "+url);
		HttpPost postRequest = new HttpPost(url);
		ObjectMapper mapper = new ObjectMapper();
					//Object to JSON in file
		mapper.writeValue(new File(jsonUrl), obj);
		//Object to JSON in String
		String jsonInString = mapper.writeValueAsString(obj);
		logger.info("String::::"+jsonInString);
		StringEntity input = new StringEntity(jaxbObjectToXml(obj));
		logger.info(obj.getClass().toString());
		logger.info(jaxbObjectToXml(obj));
		input.setContentType(MuleMasterConstants.APPLICATION_JSON);
		postRequest.setEntity(input);
		postRequest.setHeader(MuleMasterConstants.USER_NAME, MuleMasterConstants.VAM_USER);
		postRequest.setHeader(MuleMasterConstants.PASSWORD, MuleMasterConstants.PASSW0RD);
		postRequest.setHeader(AegonServiceConstants.AUTHORIZATION, token);
		postRequest.setHeader(AegonServiceConstants.XAPIKEY, key);
		HttpResponse response = httpClient.execute(postRequest);
		HttpEntity entity = response.getEntity();
		responseString = EntityUtils.toString(entity, MuleMasterConstants.UTF_8);
		if (response.getStatusLine().getStatusCode() != 200) {
			throw new MuleException(MuleMasterConstants.HTTP_ERROR_CODE+response.getStatusLine().getStatusCode());
		}
		httpClient.getConnectionManager().closeExpiredConnections();
	  } catch (MalformedURLException e) {
		  logger.error("MalformedURLException in getMuleResponse method ", e);
	  } catch (IOException e) {
		  logger.error("IOException in getMuleResponse method ", e);
	  }
		logger.info("MuleServiceUtil::getMuleResponse::end");
		return responseString;
	}

----rest endpoint-------------


@RestController
public class ServicesController {

	private static final Logger logger = LoggerFactory.getLogger(ServicesController.class);

	@Autowired
	private ProposerDetailsService proposerDetailsService;
	
	@PostMapping(value = "/ProposerDetails", consumes = MediaType.APPLICATION_JSON_VALUE,
			produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Object> proposerDetails(@RequestBody ProposerDetailsDTO proposerDetailsDTO) {
		logger.info("ServicesController::proposerDetails::start");
		logger.info("ServicesController::proposerDetails::proposerDetailsDTO = {}", proposerDetailsDTO);
		ResponseEntity<Object> responseEntity = null;
		try {
			Object response = proposerDetailsService.processAction(proposerDetailsDTO);
			responseEntity = new ResponseEntity<>(response, HttpStatus.OK);
		} catch (Exception e) {
			logger.error("Exception in proposerDetails method {}", e);
			responseEntity = new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
		}
		logger.info("ServicesController::proposerDetails::end");
		return responseEntity;
	}
}


----service-------------


@Service
public class ProposerDetailsServiceImpl implements ProposerDetailsService {

	private static final Logger logger = LoggerFactory.getLogger(ProposerDetailsServiceImpl.class);

	@Autowired
	ProposerDetailsDao proposerDetailsDao;

	@Override
	public Object processAction(ProposerDetailsDTO proposerDetailsDto) {
		logger.info("ProposerDetailsServiceImpl::processAction::start");
		Object object = null;
		ProposerDetails proposerDetails = convertToEntity(proposerDetailsDto);
		if (ServiceConstrains.CREATE.equalsIgnoreCase(proposerDetailsDto.getTransactionType())) {
			object = save(proposerDetailsDto, proposerDetails);
		} else if (ServiceConstrains.UPDATE.equalsIgnoreCase(proposerDetailsDto.getTransactionType())) {
			object = update(proposerDetailsDto, proposerDetails);
		} else if (ServiceConstrains.RETRIEVE.equalsIgnoreCase(proposerDetailsDto.getTransactionType())) {
			proposerDetails = findByProposerId(Long.parseLong(String.valueOf(proposerDetailsDto.getProposerDetailsId())));
			proposerDetailsDto = convertToDTO(proposerDetails);
		}
		List<Object> objects = new ArrayList<>();
		if(ServiceConstrains.RETRIEVE.equalsIgnoreCase(proposerDetailsDto.getTransactionType())) {
			objects.add(proposerDetailsDto);
		}else {
			objects.add(object);
		}
		logger.info("ProposerDetailsServiceImpl::processAction::objects = {}", objects);
		logger.info("ProposerDetailsServiceImpl::processAction::end");
		return objects;
	}
}


Hibernate transaction manager


package com.rs.aegon.combisite.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@EnableCaching
@Configuration
@EnableTransactionManagement
public class DBConfiguration  {


	@Bean
	public DataSource dataSource() {
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName(driver);
		dataSource.setUrl(url);
		dataSource.setUsername(userName);
		dataSource.setPassword(password);
		return dataSource;
	}

	
	@Bean
	public LocalSessionFactoryBean sessionFactory() {
		LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
		sessionFactory.setDataSource(dataSource());
		sessionFactory.setPackagesToScan(packagesToScan);
		Properties hibernateProperties = new Properties();
		hibernateProperties.put("hibernate.dialect", dialect);
		hibernateProperties.put("hibernate.show_sql", showSql);
		hibernateProperties.put("hibernate.hbm2ddl.auto", hbm2ddlAuto);
		
		sessionFactory.setHibernateProperties(hibernateProperties);
		return sessionFactory;
	}

	@Bean
	public HibernateTransactionManager transactionManager() {
		HibernateTransactionManager transactionManager = new HibernateTransactionManager();
		transactionManager.setSessionFactory(sessionFactory().getObject());
		return transactionManager;
	}

}


Scheduler in spring


@Configuration
@EnableScheduling
public class SchedulerConfiguration {
	@Bean
	public PolicySetupScheduler policySetupUrl(){
		return new PolicySetupScheduler();
	}
}


@Component
@PropertySource("file:D:\\\\MOPIS\\\\combisite\\\\combisite.properties")
public class PolicySetupScheduler {
	private static final Logger logger = LoggerFactory.getLogger(PolicySetupScheduler.class);
	@Autowired
	private Environment env;
	@Autowired
	private ProposerDetailsService proposerDetailsService;

	//@Scheduled(cron="0 0/5 * * * ?")
	@Scheduled(cron="0 0 18 * * ?")
	public void genrateNewToken(){
		try {
			System.out.println("Inside payment scheduler");
			if("true".equalsIgnoreCase(env.getProperty("ppmc.flag"))){
			new SchedulerUtil().getPolicySetupFailedCaseNew( proposerDetailsService);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}	
	}
	public Environment getEnvironment(){
		return env;
	}
}


Swagger in spring


@Configuration
@EnableSwagger2
public class SwaggerConfig {
	@Bean
	public Docket productApi() {
		return new Docket(DocumentationType.SWAGGER_2).select()
				.apis(RequestHandlerSelectors.basePackage(ServiceConstrains.SWAGER_SCAN_PACKAGE))
				.paths(PathSelectors.any()).build().apiInfo(metaData());
	}
	private ApiInfo metaData() {
		return new ApiInfo(ServiceConstrains.SWAGER_API_TITLE,
				ServiceConstrains.SWAGER_API_DESC, ServiceConstrains.SWAGER_API_VERSION,
				ServiceConstrains.SWAGER_TERMS_OF_SERVICE,
				new Contact(ServiceConstrains.SWAGER_CONTACT_NAME,
						ServiceConstrains.SWAGER_CONTACT_URL, ServiceConstrains.SWAGER_EMPTY_STRING),
				ServiceConstrains.SWAGER_EMPTY_STRING, ServiceConstrains.SWAGER_EMPTY_STRING);
	}
}

Factory level cache


@Service
public class MastersServicesImpl implements MastersServices {

@Autowired
private MastersServicesDao masterServicesDao;
@Override
@Cacheable(value = "appCache", key="#cityName")
public List<CityStateDTO> fetchCity(String cityName) {
return masterServicesDao.fetchCity(cityName);
}
@Override
@Cacheable(value = "appCache", key="#cityDTO")
public List<CityStateDTO> fetchCityStateDTOById(CityDTO cityDTO) {
return masterServicesDao.fetchCityStateDTOById(cityDTO);
}
}

Dao class


@Repository
public class MastersServicesDaoImpl implements MastersServicesDao {

private static final Logger logger = LoggerFactory.getLogger(MastersServicesDaoImpl.class);
@Autowired
private SessionFactory sessionFactory;

@Autowired
private CommonServiceUtil commonServiceUtil;
@SuppressWarnings("unchecked")
@Transactional(readOnly=true)
public List<CityStateDTO> fetchCity(String cityName) {
logger.info("MastersServicesDaoImpl::fetchCity::start");
List<CityStateDTO> cityStates = new ArrayList<>();
Session session = sessionFactory.getCurrentSession();
Query query = session.getNamedQuery("@MASTER_CITY_STATE");
query.setString("cityName", "%"+cityName.toUpperCase()+"%");
List<Object[]> lookupCityStates = query.list();
if(null != lookupCityStates && !lookupCityStates.isEmpty()) {
for(Object [] objs : lookupCityStates) {
CityStateDTO cityStateDTO = new CityStateDTO();
cityStateDTO.setCityId(Integer.parseInt(String.valueOf(objs[0])));
cityStateDTO.setCityName(String.valueOf(objs[1]));
cityStateDTO.setStateId(Integer.parseInt(String.valueOf(objs[3])));
cityStateDTO.setStateName(String.valueOf(objs[2]));
cityStates.add(cityStateDTO);
}
}
logger.info("MastersServicesDaoImpl::fetchCity::end");
return cityStates;
}
@SuppressWarnings("unchecked")
@Override
@Transactional(readOnly=true)
public List<MasterPojo> fetchMasterIncomeProof(String masterIncomeProof) {
logger.info("MastersServicesDaoImpl::fetchMasterIncomeProof::start");
List<MasterPojo> masterPojoList = new ArrayList<>();
Session session = sessionFactory.getCurrentSession();
Criteria criteria = session.createCriteria(LookupIncomeProof.class);
List<LookupIncomeProof> lookupIncomeProofList = criteria.list();
if(null != lookupIncomeProofList && !lookupIncomeProofList.isEmpty()) {
for (LookupIncomeProof lookupIncomeProof : lookupIncomeProofList) {
MasterPojo masterPojo = new MasterPojo();
if(null != lookupIncomeProof && null != lookupIncomeProof.getId()) {
masterPojo.setCode(commonServiceUtil.convertToInt(lookupIncomeProof.getId().getCode()));
masterPojo.setDisplayValue(lookupIncomeProof.getId().getDisplayValue());
masterPojo.setDocumentUploadValue(lookupIncomeProof.getId().getDocumentUploadValue());
masterPojoList.add(masterPojo);
}
}
}
logger.info("MastersServicesDaoImpl::fetchMasterIncomeProof::end");
return masterPojoList;
}
}



Dao class



@Entity
@Table(name = "LOOKUP_CITY_STATE")
@Cacheable(true)
@NamedNativeQueries({
@NamedNativeQuery(name="@MASTER_CITY_STATE", query="SELECT C.ID AS cityId, C.CITY_NAME AS cityName, S.STATE_NAME as stateName, S.ID AS stateId FROM LOOKUP_CITY_STATE C,LOOKUP_MASTER_STATE S WHERE "
+ " UPPER(C.STATE_CODE) = UPPER(S.STATE_CODE) and UPPER(C.CITY_NAME) like UPPER(:cityName) ORDER BY C.CITY_NAME ASC"),
@NamedNativeQuery(name="@MASTER_BANK_CODE", query="select item_id as itemId, code AS bankId, name as bankName from LOOKUP_BANK where UPPER(name) like UPPER(:bankName)")
})
public class LookupCityState implements java.io.Serializable {
private static final long serialVersionUID = -3321713896317434062L;
private LookupCityStateId id;
public LookupCityState() {
}
public LookupCityState(LookupCityStateId id) {
this.id = id;
}
@EmbeddedId
@AttributeOverrides({
@AttributeOverride(name = "id", column = @Column(name = "ID", nullable = false, precision = 10, scale = 0)),
@AttributeOverride(name = "cityName", column = @Column(name = "CITY_NAME", nullable = false, length = 50)),
@AttributeOverride(name = "stateName", column = @Column(name = "STATE_NAME", nullable = false, length = 50)),
@AttributeOverride(name = "bankName", column = @Column(name = "name",  length = 50)),
@AttributeOverride(name = "stateCode", column = @Column(name = "STATE_CODE", nullable = false, length = 50)) })
public LookupCityStateId getId() {
return this.id;
}
public void setId(LookupCityStateId id) {
this.id = id;
}
}

City Dto


package com.rs.aegon.combisite.dtos;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "City")
public class CityDTO implements Serializable{
private static final long serialVersionUID = -1791430406721415673L;
private int cityId;
private String city;
private String transactionType;
public int getCityId() {
return cityId;
}
public void setCityId(int cityId) {
this.cityId = cityId;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getTransactionType() {
return transactionType;
}
public void setTransactionType(String transactionType) {
this.transactionType = transactionType;
}
@Override
public String toString() {
return "CityDTO [cityId=" + cityId + ", city=" + city + ", transactionType=" + transactionType + "]";
}
}


========Spring Annotations ===========


@Configuration
@Bean(name = "comp", initMethod = "turnOn", destroyMethod = "turnOff")
@Component
@ComponentScan
@PropertySource
@PropertySources
@Service
@Repository
@Autowired
@PreDestroy
@PostConstruct
@Qualifier("cdDrive") will be used with @Autowired 

@Controller
@RequestMapping
@PathVariable
@RequestParam
@ModelAttribute
@RequestBody 
@ResponseBody
@RequestHeader 
@ResponseHeader


@EnableWebSecurity
@Transactional 

@SpringBootApplication
@EnableAutoConfiguration

======== JAXB to XML ===========


public String jaxbObjectToXml(Object obj) {
		logger.info("MuleServiceUtil::jaxbObjectToXml::start");
		String xmlString = "";
		try {
			JAXBContext context = JAXBContext.newInstance(obj.getClass());
			Marshaller m = context.createMarshaller();
			m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // To format XML
			StringWriter sw = new StringWriter();
			m.marshal(obj, sw);
			xmlString = sw.toString();
		} catch (JAXBException e) {
			logger.error("Exception in jaxbObjectToXml method", e);
		}
		logger.info("MuleServiceUtil::jaxbObjectToXml::end");
		return xmlString;
	}

==================================================================================

class XmlToObject
{
public static void main(String args[]){
    XmlToObject xmlObject = new XmlToObject();
	xmlObject.jaxbObjectToXml(customer ,new File("C:\\file.xml") )
	}
public Object jaxbObjectToXml(Object obj  , File file) {
		JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
	}
}





@XmlRootElement
class Customer{
	int name ;
	int id;
	public int getName() {
		return name;
	}
	public void setName(int name) {
		this.name = name;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
}


<customer>
<name>javabro</name>
<id>javabro.com</id>
</customer>

Json to object / object json


@Override
public IdDTO submitProposerDetails(ProposerDetailsDTO proposerDetailsDTO) {
logger.info("MuleServiceImpl::submitProposerDetails::start");
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ").create();
IdDTO idDTO = null;
String muleUrl = env.getProperty(MuleMasterConstants.COMBISITE_SERVICE_URL).concat(
env.getProperty(MuleMasterConstants.MULE_PROPOSER_DETAILS).concat("/"));
if(proposerDetailsDTO.getProposerDetailsId()!=0){
proposerDetailsDTO.setTransactionType(muleUpdate);
}else{
proposerDetailsDTO.setTransactionType(muleCreate);
}
String responseString = muleServiceUtil.getCombiServiceResponse(proposerDetailsDTO, muleUrl, jsonUrl);
logger.info("MuleServiceImpl::submitProposerDetails::responseString = {}", responseString);
if(!RSAAEGConstants.SUCCESS.equalsIgnoreCase(responseString)){
List<IdDTO>
idDTOList = gson.fromJson(responseString, new TypeToken<List<IdDTO>>(){}.getType());
if(null != idDTOList && !idDTOList.isEmpty()) {
idDTO = idDTOList.get(0);
}
}
logger.info("MuleServiceImpl::submitProposerDetails::end");
return idDTO;
}


======== Spring interceptor ===========


package com.vam.rsaeg.common.interceptor;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.vam.rsaaeg.constants.RSAAEGConstants;
import com.vam.rsaaeg.mule.dtos.LoginDTO;
import com.vam.rsaaeg.mule.dtos.Visitor;
import com.vam.rsaaeg.security.AccessPoint;

public class RequestHandlerInterceptor extends HandlerInterceptorAdapter {
	
	private static final Logger logger = LoggerFactory.getLogger(RequestHandlerInterceptor.class);
	private static final long MAX_INACTIVE_SESSION_TIME = 60 * 10000;
	@Autowired
	private HttpSession session;
	
	@Autowired
	private AccessPoint accessPoint;
	
	private List<String> excludedList = new ArrayList<String>(Arrays.asList("/lifeAndHealthCombi/","/lifeAndHealthCombi/showProposeDetails",
			"/lifeAndHealthCombi/checkExistingUser", "/lifeAndHealthCombi/showUserDropPage", "/lifeAndHealthCombi/autoSuggestCity", "/lifeAndHealthCombi/showPaymentSuccessDetails"));
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		logger.info("RequestHandler::preHandle::start");
		logger.info("RequestHandler::preHandle::request.getRequestURI()="+request.getRequestURI());
		long startTime = System.currentTimeMillis();
		session = request.getSession();
	    if (System.currentTimeMillis() - session.getLastAccessedTime()
	      > MAX_INACTIVE_SESSION_TIME) {
	        response.sendRedirect(request.getContextPath()+"/sessionExpired");
			return false;
	    }
	    
		if(!excludedList.contains(request.getRequestURI())){
			Visitor visitor = (Visitor)request.getSession().getAttribute("visitor");
		}
		
		String uri = request.getRequestURI().replace(request.getContextPath(), "");
			
		if(!roleCheck(uri)){
			session.invalidate();
			response.sendRedirect(request.getContextPath()+"/");
			return false;
		}
        
		logger.info("RequestHandler::preHandle::end");
		return super.preHandle(request, response, handler);
	}
	
	public boolean roleCheck(String uri){
		boolean roleCheck =true;
		if(uri.startsWith("/OPS") && !accessPoint.getExcludeList().contains(uri)){
			LoginDTO loginDTO = (LoginDTO)session.getAttribute(RSAAEGConstants.LOGINDTO);
			    if( loginDTO==null || !RSAAEGConstants.OPS.equalsIgnoreCase(loginDTO.getRole())){
			    	roleCheck = false;
	            }
		}
		return roleCheck;
	}
}


============application.propoerties =============


#jdbc.driverClassName = oracle.jdbc.pool.OracleDataSource

# UAT DB
#jdbc.url = 
#jdbc.username = 
#jdbc.password = 

server.port=9099
server.context-path=/tinyurl
spring.datasource.driver-class-name=oracle.jdbc.pool.OracleDataSource
spring.datasource.url=
spring.datasource.username=
spring.datasource.password=
spring.datasource.tomcat.max-wait=20000
spring.datasource.tomcat.max-active=50
spring.datasource.tomcat.max-idle=20
spring.datasource.tomcat.min-idle=15

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.Oracle10gDialect
spring.jpa.properties.hibernate.id.new_generator_mappings = false
spring.jpa.properties.hibernate.format_sql = true
spring.data.jpa.repositories.enabled = true
spring.jpa.properties.javax.persistence.sharedCache.mode=ALL
spring.cache.ehcache.provider=net.sf.ehcache.CacheManager
spring.cache.ehcache.config=classpath:ehcache.xml

hibernate.show_sql = true
hibernate.hbm2ddl.auto = none
entitymanager.packagesToScan = com.rs.tiny

# Redis Config
#spring.cache.type=redis
#spring.redis.host=localhost
#spring.redis.port=6379

logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql=trace


logging.level.org.springframework.web=INFO
logging.level.com.rs.aegon=INFO

# Logging pattern for the console
logging.pattern.console= "%d{yyyy-MM-dd HH:mm:ss} - %msg%n"

# Logging pattern for file
logging.pattern.file= "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"

logging.file=D:/MOPIS/combisite/logs/combiservices.log




======================CSRF Token===============


1. Add follwoing in pom.xml



<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>0</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>0</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>0</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>0</version>
</dependency>


2. In Web.xml add following


   <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/appServlet/spring-security.xml
</param-value>
</context-param>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>



3. Add spring-security.xml in path provided



<beans:beans
xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.0.xsd">

<http auto-config="true">
<!-- enable csrf protection -->
<csrf />
</http>

<authentication-manager>
<authentication-provider>
<user-service>
<user name="permitAll" password="permitAll" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>



4. In all jsps add



<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
inside form add
<sec:csrfInput/>
added proposerdetails.jsp for referance




=========================== Interceptor in Spring Boot ==================




package com.rs.tiny.interceptor;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.rs.tiny.dao.TinyUrlDao;
import com.rs.tiny.dto.TinyUrlDto;


public class TinyUrlRedirectInterceptor extends HandlerInterceptorAdapter {
private static final Logger logger = LoggerFactory.getLogger(TinyUrlRedirectInterceptor.class);
private static final long MAX_INACTIVE_SESSION_TIME = 60 * 10000;
@Autowired
private HttpSession session;
@Autowired
TinyUrlDao tinyUrlDao;
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
super.postHandle(request, response, handler, modelAndView);
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
logger.info("RequestHandler::preHandle::start");
       String url = request.getRequestURL().toString();
       String urlParts[] = url.split("/");
       String id = urlParts[urlParts.length-1];
       
       TinyUrlDto dto = new TinyUrlDto();
       dto.setUrlId(id);
       dto = tinyUrlDao.loadTinyUrl(dto);
       String actUrl = dto.getUrl();
       if(actUrl!=null &&actUrl.trim().length()>0) {
       
response.sendRedirect(actUrl);
       }        
logger.info("RequestHandler::preHandle::end");
return super.preHandle(request, response, handler);
}
}



************** Add interceptor to registry in spring boot ***************



package com.rs.tiny.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

@Component
public class TinyInterceptorRegistry extends WebMvcConfigurerAdapter {
  @Autowired
  TinyUrlRedirectInterceptor tinyinterceptor;

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
     registry.addInterceptor(tinyinterceptor);
  }
}

============================Spring MVC in Spring Boot ==============================


**************1) create Spring boot class as follows*********************



package com.rs.tiny.config;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@SpringBootApplication
@ComponentScan(basePackages="com.rs.tiny")
public class CombiservicesApplication extends SpringBootServletInitializer {

public static void main(String[] args) {
SpringApplication.run(CombiservicesApplication.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(CombiservicesApplication.class);
}
}


*****************2)  Enable spring MVC and add View Resolver  in Spring Boot************



package com.rs.tiny.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
public class TinyUrlWebMvc extends WebMvcConfigurerAdapter{
@Bean
   public ViewResolver getViewResolver() {
       InternalResourceViewResolver resolver = new InternalResourceViewResolver();
       resolver.setPrefix("/WEB-INF/views/");
       resolver.setSuffix(".jsp");
       return resolver;
   }
 
 @Override
   public void configureDefaultServletHandling(
           DefaultServletHandlerConfigurer configurer) {
       configurer.enable();
   }    

}


------or you can add below propeorties in application.propeorties--------


spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp



****************3) Add beolw dependency in pom.xml*****************

        <dependency>
		   <groupId>org.apache.tomcat.embed</groupId>
		   <artifactId>tomcat-embed-jasper</artifactId>
		   <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency> 
		



*********************************************************

@Configuration 
represents cinfuguration classe

@componentScan("package") 
If package not specified then that class package 
and sub packages will be considered

@Component 
one of stereo type annotation
can be applied to classes only

@Autowired 
Wiil be used with beans to be automatically wired

@Bean(name="beanName")
To declare bean we use it. uses with method

in XML
<bean id ="beanId" class="com.sree.Sample">
<constructor-arg ref="otherbeanId"/>
<constructor-arg value="otherbeanId"/>
<constructor-arg>
<list>
<value>hi</value>
<value>hi2</value>
</list>
</constructor-arg>
<constructor-arg>
<set>
<value>hi</value>
<value>hi2</value>
</set>
</constructor-arg>
<property name="cd" ref="CompactDisc"  />
<property name="cd" value="Hi"  />
<property name ="cdList">
<list>
<value>hi</value>
<value>hi2</value>
</list>
</property>
<property name="cdSet">
<set>
<value>hi</value>
<value>hi2</value>
</set>
</property>
</bean>


public class DemoBean implements InitializingBean, DisposableBean
{     
    @Override
    public void afterPropertiesSet() throws Exception
    {    }
    @Override
    public void destroy() throws Exception
    {    }
}

public class DemoBean
{
    @PostConstruct
    public void customInit()
    {    }
    @PreDestroy
    public void customDestroy()
    {    }
}

@Profile("prod")
To set the envoronment based configuration

@Bean 
@Conditional(MagicExistsCondition.class) 
public MagicBean magicBean() 
{ 
  return new MagicBean();
}

public class MagicExistsCondition implements Condition {
public boolean matches( ConditionContext context, AnnotatedTypeMetadata metadata) { 
Environment env = context.getEnvironment(); 
return env.containsProperty("magic"); 
}
} 

public interface ConditionContext { 
 BeanDefinitionRegistry getRegistry();
 ConfigurableListableBeanFactory getBeanFactory(); 
 Environment getEnvironment(); 
 ResourceLoader getResourceLoader(); 
 ClassLoader getClassLoader(); 
 }

 @Primary
 @Qualifier("qualifier name")
 
 Singleton
 Prototype
 Session
 Request
 @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) (or)
 @Scope("prototype")
 
 @Component 
 @Scope( value=WebApplicationContext.SCOPE_SESSION, proxyMode=ScopedProxyMode.INTERFACES) 
 public ShoppingCart cart() { ... }
 
 check examples for SPEL
 
 
 ******************Spring MVC *******************
 
Spring MVC flow
1)Dispatcher Servlet
2)HandlerMapping
3)Controller
4)Model and logical view name
5)View resolver
6)View
7)Reponse

Configure Dispatcher servlet according to servlet 3.0 Specifications

package spittr.config; 
import org.springframework.web.servlet.support. AbstractAnnotationConfigDispatcherServletInitializer;
public class SpittrWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override 
protected String[] getServletMappings() { return new String[] { "/" }; }
@Override
protected Class<?>[] getRootConfigClasses() { return new Class<?>[] { RootConfig.class }; }
@Override
protected Class<?>[] getServletConfigClasses() { return new Class<?>[] { WebConfig.class }; }
}



@Configuration 
@EnableWebMvc 
@ComponentScan("spitter.web") 
public class WebConfig extends WebMvcConfigurerAdapter {
@Bean 
public ViewResolver viewResolver() {
 InternalResourceViewResolver resolver = new InternalResourceViewResolver(); 
 resolver.setPrefix("/WEB-INF/views/");
 resolver.setSuffix(".jsp");
 resolver.setExposeContextBeansAsAttributes(true); 
 return resolver; 
 }
@Override 
public void configureDefaultServletHandling( DefaultServletHandlerConfigurer configurer)
 { configurer.enable(); 
 }
 }
 
 @Configuration
 @ComponentScan(basePackages={"spitter"}, excludeFilters={ @Filter(type=FilterType.ANNOTATION, value=EnableWebMvc.class) })
 public class RootConfig { }

 
 
 
 @Controller 
 public class HomeController {
@RequestMapping(value="/", method=GET)
 public String home()
 { return "home"; }
}


model.addAttribute("spittllist",spittleList)

Query parameters 

/spittles?max=238900&count=50


@RequestMapping(method=RequestMethod.GET)
 public List<Spittle> spittles( @RequestParam("max") long max, @RequestParam("count") int count) 
 { return spittleRepository.findSpittles(max, count); } 
 
 
 Path variable
 
 @RequestMapping(value="/{spittleId}", method=RequestMethod.GET) 
 public String spittle( @PathVariable("spittleId") long spittleId, Model model) 
 {
 model.addAttribute(spittleRepository.findOne(spittleId));
 return "spittle"; 
 }
 
 
================Validating forms=====================
 
public class Spitter {
private Long id;
@NotNull @Size(min=5, max=16) private String username;
@NotNull @Size(min=5, max=25) private String password;
}


@RequestMapping(value="/register", method=POST) 
public String processRegistration( @Valid Spitter spitter, Errors errors) {
if (errors.hasErrors()) 
{ return "registerForm"; }
spitterRepository.save(spitter); 
return "redirect:/spitter/" + spitter.getUsername();
}


=================Setting JSTL view==================


@Bean 
public ViewResolver viewResolver() { 

 InternalResourceViewResolver resolver = new InternalResourceViewResolver();
 resolver.setPrefix("/WEB-INF/views/"); 
 resolver.setSuffix(".jsp");
 resolver.setViewClass( org.springframework.web.servlet.view.JstlView.class);
 return resolver;

} 

=========================================


Adding additional servlets

public class MyServletInitializer implements WebApplicationInitializer {
@Override 
public void onStartup(ServletContext servletContext) throws ServletException {

//SevletRegistration
Dynamic myServlet = servletContext.addServlet("myServlet", MyServlet.class);
myServlet.addMapping("/custom/**");

//filter registation
javax.servlet.FilterRegistration.Dynamic filter = servletContext.addFilter("myFilter", MyFilter.class);
filter.addMappingForUrlPatterns(null, false, "/custom/*");

}
} 


add below code in AbstractAnnotationConfigDispatcherServletInitializer  for filter registration


@Override protected Filter[] getServletFilters()
 { return new Filter[] { new MyFilter() }; }
 
 ============================================
 
 adding Mulitpart in AbstractAnnotationConfigDispatcherServletInitializer 
 
 @Override protected void customizeRegistration(Dynamic registration) 
 { registration.setMultipartConfig( new MultipartConfigElement("/tmp/spittr/uploads", 2097152, 4194304, 0)); } 
 
 
for rcmmons multipart configuration add belo code webconfig class

@Bean 
public MultipartResolver multipartResolver() 
{ return new CommonsMultipartResolver(); } 


===================Exception handling in Spring===============

@ResponseStatus(value=HttpStatus.NOT_FOUND, reason="Spittle Not Found")
 public class SpittleNotFoundException extends RuntimeException { }


@ControllerAdvice 
public class AppWideExceptionHandler {
@ExceptionHandler(DuplicateSpittleException.class)
 public String duplicateSpittleHandler() { return "error/duplicate"; }
}

=================Working with Flash attribute================


@RequestMapping(value="/register", method=POST) 
public String processRegistration( Spitter spitter, RedirectAttributes model) 
{ spitterRepository.save(spitter); 
model.addAttribute("username", spitter.getUsername()); 
model.addFlashAttribute("spitter", spitter); 
return "redirect:/spitter/{username}"; } 


@RequestMapping(value="/{username}", method=GET) 
public String showSpitterProfile( @PathVariable String username, Model model) {
 if (!model.containsAttribute("spitter")) 
 { model.addAttribute( spitterRepository.findByUsername(username)); } 
 return "profile"; 
 } 
 

 
************************* Spting Security *********************


 
 Enable DelegatingFilterProxy using xml
 
 <filter> <filter-name>springSecurityFilterChain</filter-name>
 <filter-class> org.springframework.web.filter.DelegatingFilterProxy </filter-class>
 </filter>
 
  Enable DelegatingFilterProxy in java way
  
  package spitter.config; 
  import org.springframework.security.web.context. AbstractSecurityWebApplicationInitializer;
  public class SecurityWebInitializer extends AbstractSecurityWebApplicationInitializer {} 
  
  Enable Web security
  
  @Configuration
  @EnableWebSecurity
  public class SecurityConfig extends WebSecurityConfigurerAdapter { 
  }
  
  WebSecurityConfigurerAdapter has three methods have to override
  
  configure(WebSecurity)
  configure(HttpSecurity)
  configure(AuthenticationManagerBuilder)
 
 
 protected void configure(HttpSecurity http) throws Exception {
 http .authorizeRequests() .
 anyRequest().authenticated() .
 and() .formLogin().and() .httpBasic();
 }
 
================ in memory authentication ===============
 
 @Override 
 protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
 auth .inMemoryAuthentication() .
 withUser("user").password("password").roles("USER").and() 
 .withUser("admin").password("password").roles("USER", "ADMIN"); 
 }
 
 ==============Selecting users with usedefined queries and pwd encode=========
 
 @Override 
 protected void configure(AuthenticationManagerBuilder auth) throws Exception 
 {
 auth .jdbcAuthentication() .dataSource(dataSource) .
 usersByUsernameQuery( "select username, password, true " + "from Spitter where username=?") .
 authoritiesByUsernameQuery( "select username, 'ROLE_USER' from Spitter where username=?") 
 .passwordEncoder(new StandardPasswordEncoder("53cr3t"));
 } 

 * if you set hasAuthority role name should be prefixed
 
 @Override 
 protected void configure(HttpSecurity http) throws Exception {
 http .authorizeRequests() .antMatchers("/spitters/me").hasAuthority("ROLE_SPITTER") 
 .antMatchers(HttpMethod.POST, "/spittles") .hasAuthority("ROLE_SPITTER")
 .anyRequest().permitAll(); 
 } 
 
 ===============Securing with SPEL ================
 
 .antMatchers("/spitter/me") .
 access("hasRole('ROLE_SPITTER') and hasIpAddress('192.168.1.2')") 
 
 
 ============securing https============
 
 
 @Override 
 protected void configure(HttpSecurity http) throws Exception {
 http .authorizeRequests() .antMatchers("/spitter/me").hasRole("SPITTER") 
 .antMatchers(HttpMethod.POST, "/spittles").hasRole("SPITTER") 
 .anyRequest().permitAll(); .and() .requiresChannel() .antMatchers("/spitter/form").
 requiresSecure();
 }
 
 ==============if failed login page and logout finctionalty==============
 
 @Override 
 protected void configure(HttpSecurity http) throws Exception 
 { http .formLogin() .loginPage("/login") .and() 
 .logout() .logoutSuccessUrl("/").logoutUrl("/signout"} 
 
 
 <security:authorize access="isAuthenticated() and principal.username=='habuma'"> 
 <a href="/admin">Administration</a>
 </security:authorize>




Related Articles
Recent Articles
Most Viewed Articles