Java: How to replace doPost, doGet in deprecated WebSocketServlet class - java

In older Java versions you could extend a class with WebSocketServlet, and because WebSocketServlet itself extended HttpServlet it was possible to add CRUD method, such as doGet(...), doPost(...) etc in the class.
However, now WebSocketServlet is deprecated and and using #ServerEndpoint with #OnOpen, #OnMessage, etc does not provide any "listen to doGet, doPost" messages. How can I migrate something like this?
public class Test extends WebSocketServlet
{
String something = "";
#Override
protected StreamInBound createWebSocketInbound(String string, HttpServletRequest hsr)
{
// DO STUFF
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException
{
this.something = "get";
}
}
Where do put doGet(...) and doPost(...)?
#ServerEndpoint(value = "/test")
public class Test {
#OnOpen
public void onOpen(Session session) {
// DO STUFF
}
#OnMessage
public String onMessage(String message, Session session) {
// DO STUFF
}
#OnClose
public void onClose(Session session, CloseReason closeReason) {
// DO STUFF
}
}
Also notice that I need to change a variable from the doGet(...) method that exist in the Test class.
Thanks!

Related

Injecting Interceptor jar file to my spring boot projects

I am trying to create a jar file to inject into any of my spring boot project for logging the request details.
I am able to do this in one of my project. You can see the code below.
How to create the jar out of it and how to inject into other projects?
#Component
public class Interceptor extends HandlerInterceptorAdapter {
private static Logger log = LoggerFactory.getLogger(Interceptor.class);
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// log.info("Inside prehandle");
return true;
}
#Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// log.info("Inside postHandle");
}
#Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
log.info("Inside afterCompletion");
sendToLoggerApi(request, response);
}
}
#Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {
#Autowired
Interceptor interceptor;
#Override
public void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(interceptor);
}
}

How to identify the owner of Session - Spring-Boot Websockets

I am using websockets without Stomp. What is the correct way to decide to whom USer WebSocketSession belongs to?
In my WsConfig i use:
#Configuration
#EnableWebSocket
public class WebSocketServerConfiguration implements WebSocketConfigurer {
protected final CustomWebSocketHandler webSocketHandler;
#Autowired
public WebSocketServerConfiguration(CustomWebSocketHandler webSocketHandler) {
this.webSocketHandler = webSocketHandler;
}
#SuppressWarnings("NullableProblems")
#Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(webSocketHandler, "/ws")
.addInterceptors();
}
}
my WsHandler is currently empty:
#Service
public class SplitBillWebSocketHandler extends TextWebSocketHandler {
#Override
public void handleTransportError(WebSocketSession session, Throwable throwable) throws Exception {
}
#Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
}
#Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
//determine User for session
User user = determineUser(session);
sessionStorage.add(user.getName(),session);
}
#Override
protected void handleTextMessage(WebSocketSession session, TextMessage jsonTextMessage) throws Exception {
}
}
What is the way to determine the user? Or what is the best practice to do this?
Do I need to pass some parameter to websocket URL from client ( which isn't standard as far as I am aware ), or how to identify the session?
Thanks for help!

Spring boot: How to add interceptors to static resources?

I have several folders in /static/img/** and I need to add interceptors to some of them to check user permissions. I've used interceptors earlier and added them this way:
#SpringBootApplication
#EnableTransactionManagement
public class Application extends WebMvcConfigurerAdapter {
...
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/");
}
#Bean
public AuthHeaderInterceptor authHeaderInterceptor() {
return new AuthHeaderInterceptor();
}
#Bean
public AuthCookieInterceptor authCookieInterceptor() {
return new AuthCookieInterceptor();
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry
.addInterceptor(authHeaderInterceptor())
.addPathPatterns(REST_URL)
.excludePathPatterns(
new String[] {
REST_SECURITY_URL,
REST_SETTINGS_URL,
REST_REPORTS_URL
}
);
registry
.addInterceptor(authCookieInterceptor())
.addPathPatterns(REST_REPORTS_URL);
}
}
All works fine for rest controllers and their URLs, but now I need to secure some static resources and I added this:
#SpringBootApplication
#EnableTransactionManagement
public class Application extends WebMvcConfigurerAdapter {
...
#Bean
public RoleAdminInterceptor roleAdminInterceptor() {
return new RoleAdminInterceptor();
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry
.addInterceptor(authHeaderInterceptor())
.addPathPatterns(REST_URL)
.excludePathPatterns(
new String[] {
REST_SECURITY_URL,
REST_SETTINGS_URL,
REST_REPORTS_URL
}
);
//THIS NOT WORK
registry
.addInterceptor(roleAdminInterceptor())
.addPathPatterns("/static/img/admin/**");
registry
.addInterceptor(authCookieInterceptor())
.addPathPatterns(REST_REPORTS_URL);
}
}
Commented line doesn't work. When I send request to /static/img/admin/test.png RoleAdminInterceptor is never called.
What I'm doing wrong?
I know this is an old question, but since it's unanswered it might help others searching for it.
This is what worked for me:
1- Declare an interceptor class:
class RoleBasedAccessInterceptor implements HandlerInterceptor {
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
AntPathMatcher matcher = new AntPathMatcher();
String pattern = "/static/img/admin/**";
String requestURI = request.getRequestURI();
if (matcher.match(pattern, requestURI)) {
//Do whatever you need
return validateYourLogic();
}
return true;
}
#Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
#Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
2- Configure WebMvcConfigurer
public class WebMvcConfiguration implements WebMvcConfigurer {
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new RoleBasedAccessInterceptor());
}
}
I think in this case you could use Filters with Spring Security instead of Interceptors as you could Validate the access earlier on the process even before hitting the Interceptor, unless there is a specific use case that you need to use the interceptor here.
Some topic about the difference between these two:
filters-vs-interceptor

Getting Null in request.getAttribute(..) in Struts 2

Setting Attribute
public class VoucherApproverListAction extends ActionSupport implements
SessionAware, ServletRequestAware, Preparable {
private HttpServletRequest servletRequest;
public HttpServletRequest getServletRequest() {
return servletRequest;
}
#Override
public void setServletRequest(HttpServletRequest servletRequest) {
this.servletRequest=servletRequest;
}
public void prepare() throws Exception {
servletRequest.setAttribute("id",tCaseVouchrDto.getId());
}
}
Getting Attribute
public class VoucherAction extends ActionSupport implements
SessionAware, ServletRequestAware, Preparable {
private HttpServletRequest servletRequest;
public HttpServletRequest getServletRequest() {
return servletRequest;
}
#Override
public void setServletRequest(HttpServletRequest servletRequest) {
this.servletRequest=servletRequest;
}
public void prepare() throws Exception {
String paramValue = (String)servletRequest.getAttribute("id");
logger.info("#-----Id===-----#" + paramValue);
}
}
From VoucherApproverListAction action class after success ,it is redirected to VoucherAction action class Getting null in paramValue
From VoucherApproverListAction action class after success ,it is
redirected to VoucherAction action class
This is the problem, request attributes are lost if you send redirect. You need to pass a parameter or save it in the session before the next request.

Guice persistence with JDO - weird NPE

I am using Guice with JDO and Datanucleus in my desktop app. I am facing a NPE that I can't fix, so I hope someone can help me :)
I am using properly configured H2 db, with schema created and all my classes are nicely enhanced, so it's not that. Anyway, I am getting NPE here, at JDORepository class:
public abstract class JdoRepository<T> implements Repository<T>
{
private final Class<T> clazz;
private final Provider<PersistenceManager> pmProvider;
protected JdoRepository(Class<T> clazz, Provider<PersistenceManager> pmProvider)
{
this.clazz = clazz;
this.pmProvider = pmProvider;
}
public void persist(T entity)
{
pmProvider.get().makePersistent(entity); <---- NPE!
}
My PersistenceManagerFilter looks like that:
#Singleton
public class PersistenceManagerFilter implements Filter
{
private static final Logger logger = Logger.getLogger(PersistenceManagerFilter.class.getName());
private static final ThreadLocal<PersistenceManager> pm = new ThreadLocal<PersistenceManager>();
private PersistenceManagerFactory pmf;
public void init(FilterConfig filterConfig) throws ServletException
{
logger.info("Creating PersistenceManagerFactory");
pmf = JDOHelper.getPersistenceManagerFactory();
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException
{
try
{
pm.set(pmf.getPersistenceManager());
chain.doFilter(request, response);
}
finally
{
pm.get().close();
}
}
public void destroy()
{
logger.info("Closing PersistenceManagerFactory");
pmf.close();
}
/**
* This module binds the JDO {#link javax.jdo.PersistenceManager} interface to the provider that allows the
* implementation to be injected as Provider<PersistenceManager>.
*/
public static class GuiceModule extends AbstractModule
{
#Override
protected void configure()
{
bind(PersistenceManager.class).toProvider(new Provider<PersistenceManager>()
{
public PersistenceManager get()
{
return PersistenceManagerFilter.pm.get();
}
});
}
}
}
And the responsible module:
public class GuiceModule extends AbstractModule
{
#Override
protected void configure()
{
// Enable per-request-thread PersistenceManager injection.
install(new PersistenceManagerFilter.GuiceModule());
bind(new TypeLiteral<Repository<Project>>() { }).to(JdoProjectRepository.class);
I am initiating it all that way:
Injector injector = Guice.createInjector(new GuiceModule());
Main main = injector.getInstance(Main.class);
main.run();
So repository bindings in main class work fine, as they are redirected to JDORepository. It's something at lower level, PMF not getting bound properly? Any ideas?
What does your main.run()-method do? Does it call PersistenceManagerFilter#doFilter? If it doesn't, the value in yourThreadLocal<PersistenceManager> will be null...
You could override the initialValue() and do something like this:
ThreadLocal<PersistenceManager> pm = new ThreadLocal<PersistenceManager>(){
#Override
protected PersistenceManager initialValue() {
return JDOHelper.getPersistenceManagerFactory().getPersistenceManager();
}
};
You should also remember to call the ThreadLocal#remove() method in your finally-block.
Instead of handling the ThreadLocal yourself, you could bind the PersistenceManager directly in the guice-module:
class GuiceModule extends AbstractModule {
#Provides #RequestScoped
PersistenceManager providePersistenceManager(){
return JDOHelper.getPersistenceManagerFactory().getPersistenceManager();
}
#Override
protected void configure() {}
}

Categories