Get HTTPRequest in HttpSessionListener - java

Due to project requirement I have created a HttpSessionListener in my spring based application.
public class SessionListener implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent se) {
//some business logic
}
}
I need to set some parameters in request in this class but I am not able to find any way to get http request object in this class. Is there any way to get the http request object here? If no what is the other way too implement it?

Related

Injection variable to websocket annotation #ServerEndpoint("/myVar")

I have chat which mapping to static URL. I need get the opportunity creating rooms for user.
How to inject variable in annotation #ServerEndpoint("/myVariable") when app already running?
class SomeClass{
public void createRoom(User user) {
String name = user.getName();
//...Somehow inject name to annotation #ServerEndpoint("/name")...
}
}
#ServerEndpoint("/chat") //May be replace to #ServerEndpoint(someGetteUserName())
public class ChatEndpoint {
#OnMessage
public void message(String message, Session client)
throws IOException, EncodeException {
for (Session peer : client.getOpenSessions()) {
peer.getBasicRemote().sendText(message);
}
}
}
I don't use Spring this is clear websocket and Glassfish.
Help me create implementation variable injection to annotation. Thank You.
I think that you don't need any injection if you only want to create and handle chat rooms. You just need to handle this by java code independently from your endpoint.
I recommend you to:
Create one websocket server endpoint: #ServerEndpoint("/chat"/{client_id}). This client id pathParam is may serve as a session id.
In ChatEndpoint class, initialize a list of rooms (this list should be static <=> common between all threads).
Create your business methods to handle clients and rooms(create/delete user, create/delete room, subscribe to a room...etc).
Finally, in your chat message try to specify the room destination. This can be very simple if you use JSON format.
message = { ... ,"room": "room1", ... }

How to use Jersey's internal routing mechanism to extract a class/method reference?

I have a Jersey 1.8 application running. Jersey is running as a Servlet.
I need to write a servlet filter that given a plain request/response, is able to figure out which REST resource/method will respond to the request and extract values from annotations.
For example, imagine I have the following resource:
#Path("/foo")
#MyAnnotation("hello")
public class FooResource {
#GET
#Path("/bar")
#MyOtherAnnotation("world")
public Response bar(){
...
}
}
When a request GET /foo/bar comes in, I need my servlet filter to be able to extract the values "hello" and "world" from MyAnnotation and MyOtherAnnotation before Jersey's own servlet processes the request.
This filter logic should be able to work for all requests and all resources registered.
Is there a way to access Jersey's internal routing mechanism to obtain a class/method reference where Jersey will dispatch the request?
I'm open to other suggestions as well, but ideally nothing like trying to hack my own routing mechanism by reading the #Path annotations myself.
#Provider
#Priority(Priorities.AUTHORIZATION)
public class MyFilter implements ContainerRequestFilter
#Context // request scoped proxy
private ResourceInfo resourceInfo;
#Override
public void filter(ContainerRequestContext requestContext) throws IOException {
if (resourceInfo.getResourceClass().isAnnotationPresent(MyAnnotationion.class) ||
resourceInfo.getResourceMethod().isAnnotationPresent(MyOtherAnnotation.class)) {
to register the filter use
bind(AuthFilter.class).to(ContainerRequestFilter.class).in(Singleton.class);

Why we use PrincipalAware in Struts 2

We are using PrincipalAware interface in our application to get some user related stuff.
I searched on the net to get the info about it with poor results, this is what I got on Google:
public interface PrincipalAware
Actions that want access to the Principal information from HttpServletRequest object should implement this interface.
This interface is only relevant if the Action is used in a servlet environment. By using this interface you will not become tied to servlet environment.
Please, help me to understand it.
The PrincipalAware interface allows the Struts to inject a PrincipalProxy object into the action instance. This proxy can be used to get access to the servlet security mechanism. Like this
public class MyAction extends ActionSupport implements PrincipalAware {
protected PrincipalProxy principal;
public void setPrincipalProxy(PrincipalProxy principalProxy) {
this.principal = principalProxy;
}
public PrincipalProxy getPrincipal() {
return principal;
}
}
Now, you can use PrincipalProxy in action method or on the view layer,
<s:if test="principal.isUserInRole('role1')">
Note, if you want to restrict an execution of some actions based on a role, then you could use roles interceptor.

tomcat 8 javax.websockets doesn't work

I have tomcat 8-RC1 installed in order to use javax.websockets to write websocket based applications.
there are examples at http://svn.apache.org/viewvc/tomcat/trunk/webapps/examples/WEB-INF/classes/websocket/ that show exactly the structure of a websocket class so I implemented the following interface:
public interface XpoWebSocket {
#OnOpen
public void onOpen(Session session);
#OnClose
public void onClose();
#OnMessage
public void onTextMessage(String message);
public Session getSession();
}
in the line above the class deceleration I also included the following:
#ServerEndpoint(value = "/ServConnect")
public class ServConnect implements XpoWebSocket {
...
so the ServerEndPoint is to point how to access to websocket, the question is what do i need to set in web.xml ? for now the web socket is still not accessible.
I try to define ServConnect as a regular Servlet in web.xml but that doesn't work. it just time out when I try to access the ServConnect location.
what configuration am I missing to let this ServConnect websocket class work ?
The WebSocket spec says that you have to annotate the concrete class. ServConnect will be treated as a WebSocket endpoint but will not receive any events as the annotations on the interface are ignored.
I'd suggest getting your own version of the Echo example working and then expanding from there.

How to get the IP address when a session is created?

In my grails application, I have implemented the interface HttpSessionListener to listen for session creation as given below:
class MyHttpSessionListener implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent event) {
log.info "***************** Session created: id= ${event.getSession()?.id}"
}
}
Now, I would like to log the IP address that is responsible for the session creation.
How can I do that?
you can access the RequestContextHolder and get the value
String ipAddr = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes())
.getRequest().getRemoteAddr();
As far as I know you can't using the HttpSessionListener interface.
You can get and log the IP Address from "ServletRequest.getRemoteAddr()" but you don't have access to the servlet request from HttpSessionListener or from HttpSessionEvent.
Best idea would to have a javax.servlet.Filter which gets the IP address and sets it as a session attribute if not already present. (You could also do the logging if not already present).
You can also use this interface in your HttpSessionListener : ServletRequestListener
You can implement : requestInitialized() like this.
#Override
public void requestInitialized(ServletRequestEvent servletRequestEvent) {
this.request = (HttpServletRequest) servletRequestEvent.getServletRequest();
}
it s working fine, the request object can bring you the remote adress, there is a méthod to do that

Categories