Get responseBody from HttpServletResponse Java - java

I want to check response body, read the response then perform some other operation manipulate the body and then return the response.
How exactly can i log the response in logger?
If i want to manipulate the content of response how can i do that?
Custom Filter.java
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
#Component
#Order(1)
#WebFilter(urlPatterns = {"/*"}, description = "My delay filter ")
public class CustomFilter implements Filter{
private static final Logger logger = Logger.getLogger(CustomFilter.class);
#Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
try {
if (httpRequest.getRequestURL().toString().contains("download")) {
logger.debug(httpResponse); //want to log response body
}
} catch (Exception e) {
logger.error("Exception in CustomFilter.doFilter(): ", e);
}
chain.doFilter(request, response);
}
#Override
public void destroy() {
// TODO Auto-generated method stub
}
}

package com.biclinical.rmm.controller;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;
import org.springframework.web.util.WebUtils;
import com.biclinical.rmm.utility.ServiceUtils;
#Component
#Order(1)
#WebFilter(urlPatterns = { "/*" })
public class DownloadFileFilter implements Filter {
private static final Logger logger = Logger.getLogger(DownloadFileFilter.class);
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest requestToCache = new ContentCachingRequestWrapper((HttpServletRequest) request);
HttpServletResponse responseToCache = new ContentCachingResponseWrapper((HttpServletResponse) response);
try {
if (requestToCache.getRequestURL().toString().contains("/download")) {
chain.doFilter(request, responseToCache);
getResponseData(responseToCache);
} else {
chain.doFilter(request, response);
}
} catch (Exception e) {
logger.error("Exception in CustomFilter.doFilter(): ", e);
}
}
private static void getResponseData(HttpServletResponse response) throws Exception {
ContentCachingResponseWrapper wrapper = WebUtils.getNativeResponse(response,
ContentCachingResponseWrapper.class);
if (wrapper != null) {
byte[] buf = wrapper.getContentAsByteArray();
if (buf.length > 0) {
String payload = new String(buf, 0, buf.length, wrapper.getCharacterEncoding());
logger.debug("Response Richa :" + payload);
wrapper.copyBodyToResponse();
}
}
}
#Override
public void destroy() {
}
}

Related

how to get response body from cxf outInterceptor

I am writing some code to collect some controller's request param and response body.
Since the project framework is apache CXF, which version is 3.1.18,
I write an interceptor extends AbstractPhaseInterceptor to collect param in phase Phase.RECEIVE, which is working.
But when a write an outInterceptor extends AbstractPhaseInterceptor to collect the response of the controller, I find there no way for me to do this, there just one method handleMessage(Message message) in the interceptor, I can not fetch anything I want from the message
Can anybody help me? I am new to CXF. Thanks!
I found the answer from the other blob
package XXX.web.webservice.interceptor;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.io.IOUtils;
import org.apache.cxf.io.CachedOutputStream;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.log4j.Logger;
public class ArtifactOutInterceptor extends AbstractPhaseInterceptor<Message>{
private static final Logger log = Logger.getLogger(ArtifactOutInterceptor.class);
public ArtifactOutInterceptor() {
//这儿使用pre_stream,意思为在流关闭之前
super(Phase.PRE_STREAM);
}
public void handleMessage(Message message) {
try {
OutputStream os = message.getContent(OutputStream.class);
CachedStream cs = new CachedStream();
message.setContent(OutputStream.class, cs);
message.getInterceptorChain().doIntercept(message);
CachedOutputStream csnew = (CachedOutputStream) message.getContent(OutputStream.class);
InputStream in = csnew.getInputStream();
String xml = IOUtils.toString(in);
//这里对xml做处理,处理完后同理,写回流中
IOUtils.copy(new ByteArrayInputStream(xml.getBytes()), os);
cs.close();
os.flush();
message.setContent(OutputStream.class, os);
} catch (Exception e) {
log.error("Error when split original inputStream. CausedBy : " + "\n" + e);
}
}
private class CachedStream extends CachedOutputStream {
public CachedStream() {
super();
}
protected void doFlush() throws IOException {
currentStream.flush();
}
protected void doClose() throws IOException {
}
protected void onWrite() throws IOException {
}
}
}

Spring Security Authentication UserDetailsService Implementation class not being invoked

I'm trying to migrate from Spring XML based configuration to Pure Java Configuration, I have configured all the configuration files, but when I try to enter the username and password in login page, it redirects me back to the login page again. I believe the userServiceImpl method is not being invoked because the control is not going there.
Here, I have autowired userServiceImpl method which is implementing UserDetailsService of spring security core credentials.
package com.lw.sms.config;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.lw.sms.CustomAuthenticationSuccessHandler;
import com.lw.sms.UserServiceImpl;
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
#EnableTransactionManagement
#Order(1000)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private static final Logger logger = LoggerFactory.getLogger(SecurityConfig.class);
#Value("${jdbc.dialect}")
String jdbcDialect;
#Value("${jdbc.driverClassName}")
String jdbcDriverClassName;
#Value("${jdbc.databaseurl}")
String jdbcDatabaseurl;
#Value("${jdbc.username}")
String jdbcusername;
#Value("${jdbc.password}")
String jdbcPassword;
#Autowired
private CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;
#Autowired
private UserServiceImpl userServiceImpl;
#Override
public void configure(final AuthenticationManagerBuilder auth) throws Exception {
logger.info("configure auth");
auth.userDetailsService(userServiceImpl);
}
#Bean
public PasswordEncoder passwordEncoder() {
PasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
#Override
public void configure(HttpSecurity http) throws Exception {
logger.info("configure http");
http.httpBasic().disable();
http.authorizeRequests().and().formLogin().loginPage("/login").usernameParameter("employeeId")
.passwordParameter("password").successHandler(customAuthenticationSuccessHandler)
.failureUrl("/login?error").defaultSuccessUrl("/dashboard", true)
.loginProcessingUrl("j_spring_security_check")
.and().logout().logoutUrl("/j_spring_security_logout").logoutSuccessUrl("/logout")
.invalidateHttpSession(true).deleteCookies("JSESSIONID")
.and().sessionManagement().invalidSessionUrl("/logout").maximumSessions(1)
.maxSessionsPreventsLogin(true).expiredUrl("/logout");
http.csrf().disable();
http.authorizeRequests().anyRequest().authenticated();
}
#Bean
public SessionRegistry sessionRegistry() {
logger.info("sessionRegistry");
return new SessionRegistryImpl();
}
#Bean
public SessionFactory sessionFactory() {
LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource());
builder.scanPackages("com.lw.sms").addProperties(hibernateProperties());
return builder.buildSessionFactory();
}
#Bean
public LocalSessionFactoryBean hibernateSessionFactory() {
logger.info("sessionFactory");
org.hibernate.cfg.Configuration configuration = new org.hibernate.cfg.Configuration();
configuration.configure("hibernate.cfg.xml");
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan("com.lw.sms");
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public DataSource dataSource() {
logger.info("dataSource");
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(jdbcDriverClassName);
dataSource.setUrl(jdbcDatabaseurl);
dataSource.setUsername(jdbcusername);
dataSource.setPassword(jdbcPassword);
return dataSource;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
logger.info("transactionManager");
HibernateTransactionManager htm = new HibernateTransactionManager();
htm.setSessionFactory(sessionFactory);
return htm;
}
#Bean
public Properties hibernateProperties() {
logger.info("hibernateProperties");
Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.show_sql", "true");
hibernateProperties.setProperty("hibernate.dialect", jdbcDialect);
hibernateProperties.setProperty("hibernate.default_schema", "sms");
return hibernateProperties;
}
}
CustomAuthenticationSuccessHandler Code is attached below
package com.lw.sms;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;
import com.lw.sms.constants.Constants;
import com.lw.sms.user.entities.EmployeeEntity;
import com.lw.sms.user.entities.EmployeePermissionsEntity;
import com.lw.sms.user.service.UserManagementService;
import com.lw.sms.util.QueryBuilder;
#Component("customAuthenticationSuccessHandler")
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
private static final Logger logger = LoggerFactory.getLogger(CustomAuthenticationSuccessHandler.class);
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
#Autowired
#Qualifier("sessionInfo")
private SessionInfo sessionInfo;
#Autowired
#Qualifier("userManagementServiceImpl")
private UserManagementService userManagementService;
#Autowired
private HttpServletRequest httpServletRequest;
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException {
response.setStatus(HttpServletResponse.SC_OK);
clearAuthenticationAttributes(request);
handle(request, response);
}
protected void handle(HttpServletRequest request, HttpServletResponse response)
throws IOException {
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
EmployeeEntity employeeEntity = (EmployeeEntity) principal;
setSessionInformationForEmployee(employeeEntity);
}
if (response.isCommitted()) {
return;
}
startServices();
redirectStrategy.sendRedirect(request, response, "/dashboard");
}
/**
* #param employeeEntity
*
*/
private void setSessionInformationForEmployee(EmployeeEntity employeeEntity) {
try {
WebAuthenticationDetails details = (WebAuthenticationDetails) SecurityContextHolder.getContext()
.getAuthentication().getDetails();
userManagementService.updateLoginInfo(employeeEntity.getUsername(), details.getRemoteAddress());
// setting session information
} catch (Exception e) {
logger.info("Exception while set Session Information For Employee :" + ExceptionUtils.getFullStackTrace(e));
}
}
private void startServices() {
logger.info("Starting Services..");
try {
String domainName = httpServletRequest.getScheme() + "://" + httpServletRequest.getServerName();
if (httpServletRequest.getServerPort() != 0) {
domainName += ":" + httpServletRequest.getServerPort();
}
domainName += httpServletRequest.getContextPath();
Constants.domainName = domainName + "/resources";
} catch (Exception e) {
logger.error("Error in start services :"+ ExceptionUtils.getFullStackTrace(e));
}
}
protected void clearAuthenticationAttributes(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
return;
}
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
protected RedirectStrategy getRedirectStrategy() {
return redirectStrategy;
}
}
UserServiceImpl Code is attached below
package com.lw.sms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.lw.sms.user.dao.UserManagementDAO;
import com.lw.sms.user.entities.EmployeeEntity;
#Service("userServiceImpl")
public class UserServiceImpl implements UserDetailsService {
#Autowired
#Qualifier("userManagementDAOImpl")
private UserManagementDAO userManagementDAO;
#Override
#Transactional
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
EmployeeEntity employeeEntity = userManagementDAO.loadUserByUsername(username);
if (employeeEntity == null) {
ContractorEntity contractorEntity = userManagementDAO.loadUserByUsernameContractor(username);
if(contractorEntity == null)
throw new AuthenticationCredentialsNotFoundException("Invalid Username or Password");
}
if(!employeeEntity.isEnabled())
throw new AuthenticationCredentialsNotFoundException("Employee Disabled");
return employeeEntity;
}
}
Global Exception Handler Code:
package com.lw.sms;
import java.io.IOException;
import java.nio.charset.Charset;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.stereotype.Controller;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.HttpSessionRequiredException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;
#SuppressWarnings("deprecation")
#Controller
#ControllerAdvice
public class CustomExceptionHandler extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 3699167829164697594L;
private static final Logger logger = LoggerFactory
.getLogger(CustomExceptionHandler.class);
#ExceptionHandler(AuthenticationCredentialsNotFoundException.class)
#ResponseStatus(HttpStatus.UNAUTHORIZED)
public ModelAndView handleLoginExceptions(HttpServletRequest request,
HttpServletResponse response,Exception exception) {
logger.info("Handling exception time error"+ exception.getMessage());
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("login");
return modelAndView;
}
#ExceptionHandler(HttpSessionRequiredException.class)
public String handleSessionExpired() {
logger.info("session-expired");
return "logout";
}
#SuppressWarnings("unchecked")
#ExceptionHandler(value = { MissingServletRequestParameterException.class,
ServletRequestBindingException.class, TypeMismatchException.class,
HttpMessageNotReadableException.class,
MethodArgumentNotValidException.class,
MissingServletRequestPartException.class })
#ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "Bad Request")
#ResponseBody
public JSONObject handle400Exception(Exception ex,HttpServletResponse response) {
logger.error("400 Exception" + ex.getMessage());
JSONObject jsonObject=new JSONObject();
jsonObject.put("status", HttpStatus.BAD_REQUEST);
jsonObject.put("success", false);
jsonObject.put("message", ex.getMessage());
try {
response.getOutputStream().write(jsonObject.toString().getBytes(Charset.defaultCharset()));
} catch (IOException e) {
logger.error(ExceptionUtils.getFullStackTrace(e));
}
response.setContentType("application/json; charset=UTF-8");
return jsonObject;
}
#ExceptionHandler(value = { NoSuchRequestHandlingMethodException.class, })
#ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Not Found")
#ResponseBody
public Boolean handle404Exception(Exception ex) {
logger.error("404 Exception" + ExceptionUtils.getFullStackTrace(ex));
return false;
}
#ExceptionHandler(value = { HttpRequestMethodNotSupportedException.class,
HttpMediaTypeNotSupportedException.class })
#ResponseStatus(value = HttpStatus.NOT_ACCEPTABLE, reason = "Not Supported")
#ResponseBody
public Boolean handle405Exception(Exception ex) {
logger.error("405 Exception" + ExceptionUtils.getFullStackTrace(ex));
return false;
}
#ExceptionHandler(value = { HttpMessageNotWritableException.class,
ConversionNotSupportedException.class })
#ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "Internal Server Error")
#ResponseBody
public Boolean handle500Exception(Exception ex) {
logger.error("500 Exception" + ExceptionUtils.getFullStackTrace(ex));
return false;
}
#ExceptionHandler({ Exception.class })
public ModelAndView handleException(Exception ex, HttpServletRequest request,
HttpServletResponse response) {
logger.info("*****************************************************");
logger.error("Exception: " + ExceptionUtils.getFullStackTrace(ex));
ex.printStackTrace();
logger.info("*****************************************************");
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("logout");
return modelAndView;
}
}
This is my HomeController.
package com.lw.sms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
import com.lw.sms.master.service.MasterDataService;
import com.lw.sms.user.entities.EmployeeEntity;
/**
* Handles requests for the application home page.
*/
#Controller("homeController")
public class HomeController {
#Autowired
#Qualifier("masterDataServiceImpl")
private MasterDataService masterDataService;
#Autowired
#Qualifier("sessionInfo")
private SessionInfo sessionInfo;
#GetMapping(value = { "/home", "/", "login" })
public ModelAndView home() {
return new ModelAndView("login");
}
#GetMapping(value = "dashboard")
public ModelAndView dashboard() {
EmployeeEntity user = sessionInfo.getEmployeeEntity();
return new ModelAndView("dashboard", "userDetails", user);
}
// Logout page
#ResponseStatus(code = HttpStatus.UNAUTHORIZED)
#GetMapping(value = "logout")
public String logout() {
return "logout";
}
}
Could you please try adding the successForwardUrl also as below.
http.authorizeRequests().antMatchers("/login").permitAll()
.antMatchers("/dashboard").access("IS_AUTHENTICATED_FULLY")
.antMatchers("/j_spring_security_check").access("IS_AUTHENTICATED_ANONYMOUSLY")
.and().formLogin().loginPage("/login").usernameParameter("employeeId").passwordParameter("password")
.successForwardUrl("/dashboard").defaultSuccessUrl("/dashboard", true).failureForwardUrl("/loginfailed")
.loginProcessingUrl("/j_spring_security_check")
.and().logout().logoutSuccessUrl("/logout").invalidateHttpSession(true)
.and().sessionManagement().sessionFixation().none()
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.invalidSessionUrl("/login")
.and().exceptionHandling().accessDeniedPage("/Access_Denied").and().csrf().disable();
I was able to replicate the error.
I had to configure a new bean in SecurityConfig file.
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
#Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userServiceImpl);
authenticationProvider.setPasswordEncoder(passwordEncoder());
return authenticationProvider;
}

How to sort table on click jsp?

I have a table on JSP page. I want to sort it, when click button. How I should do it? Result table will on other jsp page or I can change current table?
That is my servlet, but I cant understand, how return result after sorting. It
Thank you!
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/home")
public class HomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
String[] name = {"x1","x2","x3","x4","x5","x6","x7","x8","x9","x10"};
int[] price = {7600,8500,11700,15000,6000,10200,6400,5800,8700,10400};
int[] memory = {4,4,12,16,2,10,3,1,6,8};
int[] camera = {10,8,10,15,6,9,5,4,8,12};
public HomeServlet() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int temp = 0;
List<Product> products = new ArrayList<Product>();
while(temp!=price.length-1){
Product pr = new Product(name[temp], camera[temp], memory[temp], price[temp]);
temp++;
products.add(pr);
}
request.setAttribute("productList", products);
RequestDispatcher rd = request.getServletContext().getRequestDispatcher("/WEB-INF/views/home.jsp");
rd.forward(request, response);
if (request.getParameter("button1") != null) {
Sorts.function1(price);// in this function I sort table by a certain field
} else if (request.getParameter("button2") != null) {
Sorts.function1(memory);
}
}
//???? WHAT I SHOULD DO HERE?
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}

Jersey: Checking for Not null request payload

How can I make sure that a null request payload will not be sent to any of the POST or PUT requests?
You could try implementing a ContainerRequestFilter and abort the request if the payload is null.
requestContext.abortWith(Response.status(Response.Status.BAD_REQUEST)
.entity("Payload is null")
.build());
https://jersey.java.net/documentation/latest/filters-and-interceptors.html
/*Name Binding meta annotation*/
package com.avinash.api;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.ws.rs.NameBinding;
#Target({ ElementType.TYPE, ElementType.METHOD })
#Retention(value = RetentionPolicy.RUNTIME)
#NameBinding
public #interface NullPayloadDetection {}
/* Decorate your filter with name-binding (NullPayloadDetection) annotation*/
package com.avinash.api;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
#Provider
#NullPayloadDetection
public class NullPayloadDetectionFilter implements ContainerRequestFilter {
#Override
public void filter(ContainerRequestContext requestContext) throws IOException {
String entityStream = read(requestContext.getEntityStream());
if( (!requestContext.hasEntity() && requestContext.getLength() == 0)
|| isEmpty(entityStream)) {
String path = requestContext.getUriInfo().getRequestUri().getPath();
System.out.println("Null payload detected for "+path);
requestContext.abortWith(Response.status(Response.Status.BAD_REQUEST).entity("Null payload").build());
} else {
System.out.println("Nothing wrong with the request");
InputStream targetStream = new ByteArrayInputStream(entityStream.getBytes());
requestContext.setEntityStream(targetStream);
}
}
private String read(InputStream inputStream) throws IOException {
ByteArrayOutputStream into = new ByteArrayOutputStream();
byte[] buf = new byte[4096];
for (int n; 0 < (n = inputStream.read(buf));) {
into.write(buf, 0, n);
}
into.close();
String str = new String(into.toByteArray(), "UTF-8");
System.out.println(str);
return str;
}
private boolean isEmpty(String str) {
boolean bool = "".equals(str);
System.out.println("isEmpty: "+bool);
return bool;
}
}
/*
name-binding annotation is applied to the resource method to which the name-bound JAX-RS provider(s) should be bound to
*/
package com.avinash.api;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
#Path("status")
public class Status {
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
#NullPayloadDetection
public Response status(MyRequestModel request) {
// your business logic
}
}

Apache Felix Filter Issue

I'm developing an Apache Sling WCMS application. I need to filter all requests sent to the server and set some headers in response object. I implemented filter and bundle activator class according to Felix Http Filter Sample and installed as bundle to sling.
Fileter class:
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class HeaderFilter implements Filter {
private final String name;
public HeaderFilter(String name) {
this.name = name;
}
public void init(FilterConfig config) throws ServletException {
doLog("Init with config [" + config + "]");
}
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
try {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
doLog("Filter request [" + request + "]");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Expires", "-1");
chain.doFilter(req, response);
} catch (Exception e) {
e.printStackTrace();
}
}
public void destroy() {
doLog("Destroyed filter");
}
private void doLog(String message) {
System.out.println("## [" + this.name + "] " + message);
}
}
Bundle Activator class:
import org.apache.felix.http.api.ExtHttpService;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTracker;
import java.util.Dictionary;
import java.util.Hashtable;
public class Activator implements BundleActivator {
private ServiceTracker tracker;
private HeaderFilter filter1 = new HeaderFilter("filter1");
Dictionary hashTable = new Hashtable<Object, Object>();
public void start(BundleContext context) throws Exception {
try {
this.tracker = new ServiceTracker(context, ExtHttpService.class.getName(), null) {
#Override
public Object addingService(ServiceReference ref) {
Object service = super.addingService(ref);
serviceAdded((ExtHttpService) service);
return service;
}
#Override
public void removedService(ServiceReference ref, Object service) {
serviceRemoved((ExtHttpService) service);
super.removedService(ref, service);
}
};
this.tracker.open();
} catch (Exception e) {
e.printStackTrace();
}
}
public void stop(BundleContext context)
throws Exception {
this.tracker.close();
}
private void serviceAdded(ExtHttpService service) {
try {
hashTable.put("filter.scope", new String[]{"request", "forward", "include"});
service.registerFilter(this.filter1, ".*", hashTable, 0, null);
} catch (Exception e) {
e.printStackTrace();
}
}
private void serviceRemoved(ExtHttpService service) {
service.unregisterFilter(this.filter1);
}
}
The is a problem with the code above. It's not working and no request will be filtered.
Any help is appreciated in advance.
Note that you can implement this in a much simpler way using Sling Filters implemented as OSGi Declarative Services (DS).
You'll then just need a few annotations in your Filter, no Activator and the correct pom.xml setup for the Maven plugins that handle the DS annotations.
The documentation is at https://sling.apache.org/documentation/the-sling-engine/filters.html and it points to the NoPropertyFilter example from the Sling integration tests.
I found that my filter is not tracked by the service tracker, so by passing parameter 'true' to tracker.open() the filter was tracked:
this.tracker.open(true);

Categories

Resources