Skip to content

Instantly share code, notes, and snippets.

@tyb
Last active July 25, 2019 12:19
Show Gist options
  • Save tyb/03d405a9310512675405825eab2ca9fd to your computer and use it in GitHub Desktop.
Save tyb/03d405a9310512675405825eab2ca9fd to your computer and use it in GitHub Desktop.
moving/transferring common request parameters between rest calls
package com.xxx.common.config;
import com.xxx.common.util.CommonReqParams;
import com.xxx.common.util.RestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class MyConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry){
//registry.addInterceptor(new RestInterceptor()).addPathPatterns("/**");
registry.addInterceptor(restInterceptor()).addPathPatterns("/**");
//registry.addInterceptor(
// new HeaderRequestInterceptor("Accept", MediaType.APPLICATION_JSON_VALUE));
}
@Bean(name="commonReqParams")
@Scope(value="request", proxyMode= ScopedProxyMode.TARGET_CLASS)
public CommonReqParams commonReqParams() {
return new CommonReqParams();
}
@Bean
public RestInterceptor restInterceptor() {
return new RestInterceptor(commonReqParams());
}
}
package com.xxx.common.util;
import org.springframework.http.HttpEntity;
public class CommonReqParams {
private String userName;
private HttpEntity<Object> entity;
public CommonReqParams() {}
public CommonReqParams(String userName) {
this.userName = userName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public HttpEntity<Object> getEntity() {
return entity;
}
public void setEntity(HttpEntity<Object> entity) {
this.entity = entity;
}
}
---
package com.xxx.common.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
public class RestInterceptor implements HandlerInterceptor, ApplicationContextAware {
private static ApplicationContext applicationContext;
private final Logger log = LoggerFactory.getLogger(this.getClass());
private CommonReqParams commonReqParams;
//unimplemented methods comes here. Define the following method so that it
//will handle the request before it is passed to the controller.
public RestInterceptor(CommonReqParams commonReqParams) {
this.commonReqParams = commonReqParams;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
try {
log.info("[taha: preHandle][" + request + "]" + "[" + request.getMethod()
+ "]" + request.getRequestURI());
//create a new session??
//HttpSession session = request.getSession(true);
//session.setAttribute("PARAM_TO_FORWARD", request.getParameterMap());
printAllParameters(request.getParameterMap(), request);
commonReqParams.setUserName(request.getHeader("userName"));
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.set("userName", commonReqParams.getUserName());
/**TODO: buradaki parameters kısmı değiştirilecek. Bu parametre request'in body kısmını gösterir.
* Use the HttpEntity to wrap the request object.
* Here, we wrap the "parameters" object(ordinary string) to send it to the request body.
* */
//TODO: taha: generic olması için Object'e dönüştürdüm.
//HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
HttpEntity<Object> entity = new HttpEntity<>("parameters", headers);
commonReqParams.setEntity(entity);
/*
HttpSession session = request.getSession(false);
String path = request.getRequestURI().substring(request.getContextPath().length());
if(path.equals("/Login")){
return true;
}
else if(session == null || session.getAttribute("details") == null) {
request.setAttribute("emassage", "login failed");
throw new Exception("login failed.");
}else{
return true;
}
*/
System.out.println("..........user:" + request.getHeader("userName"));
//Security kısımlarını ByPass etmek için bir deneme...
SecurityContextHolder.getContext().setAuthentication(
new AuthenticationRequest(request.getHeader("userName")));
/*
DefaultSavedRequest savedRequest = (DefaultSavedRequest)
request.getSession().getAttribute(
"SPRING_SECURITY_SAVED_REQUEST");
return "redirect:"+savedRequest.getRequestURL();
*/
//Principal userPrincipal = request.getUserPrincipal();
//Authentication auth = (Authentication)userPrincipal;
//SecurityContextHolder.getContext().setAuthentication(auth);
//The Authentication has two major uses:
//1. to access the user's details (e.g. id/name/email)
// UserDetails ud = (UserDetails)auth.getPrincipal();
//2. to know the roles that user has
/// Collection<? extends GrantedAuthority> grantedRoles = auth.getAuthorities();
} catch (Exception e) {
System.out.println("asd");
}
/*
JBossSecurityContext securityContext = new JBossSecurityContext("myAppp");
SecurityContextAssociation.setSecurityContext(securityContext);
SecurityContextAssociation.setPrincipal(new SimplePrincipal(userName));
SecurityContextAssociation.setCredential(userName);
*/
/*
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
String username = ((UserDetails)principal).getUsername();
} else {
String username = principal.toString();
}*/
/*
try {
InitialContext context = new InitialContext();
SecurityContext securityContext = new SecurityContext("myApp");
SecurityContextAssociation.setSecurityContext(securityContext);
SecurityContextAssociation.setPrincipal(new SimplePrincipal(userName));
SecurityContextAssociation.setCredential(userName);
try {
UserType userType = USER_CACHE.computeIfAbsent(userName, u -> getUserType(context));
if (UserType.USER.equals(userType)) {
return context;
}
} catch (Exception e) {
log.error(e);
}
return null;
} catch (Exception e) {
log.error("", e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity("System error.").type(MediaType.TEXT_PLAIN_TYPE).build();
}*/
return true;
}
@Override
public void postHandle( HttpServletRequest request, HttpServletResponse response,
Object handler, ModelAndView modelAndView) throws Exception {
//System.out.println("---method executed---");
request.getSession().setAttribute("PARAM_TO_FORWARD", request.getParameterMap());
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
Map<String,String[]> params = (Map<String,String[]>)attr.getRequest()
.getSession()
.getAttribute("PARAM_TO_FORWARD");
printAllParameters(params, request);
log.info("[taha: postHandle]: " + params.get("userName"));
log.info("[taha: postHandle]: " + commonReqParams.getUserName());
/*
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.set("userName", commonReqParams.getUserName());
HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
commonReqParams.setEntity(entity);
*/
log.info("[taha: postHandle]: " + commonReqParams.getEntity().getHeaders());
/*
HandlerMethod handlerMethod = (HandlerMethod)handler;
Method method = handlerMethod.getMethod();
MaintAwareAnnotation maintAware = method.getAnnotation(MaintAwareAnnotation.class);
if (maintAware != null) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.set("userName", commonReqParams.getUserName());
}
*/
//HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) throws Exception {
//System.out.println("---Request Completed---");
request.getSession().setAttribute("PARAM_TO_FORWARD", request.getParameterMap());
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
Map<String,String[]> params = (Map<String,String[]>)attr.getRequest()
.getSession()
.getAttribute("PARAM_TO_FORWARD");
printAllParameters(params, request);
log.info("[taha: afterCompletion]: " + params.get("userName"));
//TODO: print security info - taha
/*
SecurityContext securityContext = SecurityContextHolder.getContext();
Authentication authentication = securityContext.getAuthentication();
if (authentication != null) {
Object principal = authentication.getPrincipal();
return principal instanceof UserDetails ? (UserDetails) principal : null;
}
*/
}
public void setApplicationContext(ApplicationContext context) throws BeansException {
applicationContext = context;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
private void printAllParameters(Map<String, String[]> params, HttpServletRequest request) {
Enumeration<String> headerNames = request.getHeaderNames();
request.getSession().setAttribute("HEADER_PARAMS", headerNames);
while (headerNames.hasMoreElements()) {
String header = headerNames.nextElement();
System.out.println("Header " + header);
System.out.println("Value " + request.getHeader(header));
}
Iterator<String> i = params.keySet().iterator();
while ( i.hasNext() ){
String key = (String) i.next();
String value = ((String[]) params.get( key ))[ 0 ];
System.out.println("Requst Params Key: ["+key+"] - Val: ["+value+"]");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment