SessionHandler becomes null in Jetty v9.4.5 - java

So I am using embedded jetty server for my project application. Whenever a request comes in to specific method it has all the attributes populated in org.eclipse.jetty.server.Request object including SessionHandler, but since my code is taking significant amount of time to excecute , after some time Session and SessionHandler attribute becomes null in Request object. Due to this , obviously I am getting exception whenever I try o access session as below :
Exception in thread "Thread-19" java.lang.IllegalStateException: No SessionManager
at org.eclipse.jetty.server.Request.getSession(Request.java:1548)
Initially I thought , since my code is taking longer to complete execution , it might be that I am losing session due to timeout, so I increased the session-timeout value. But it didn't help.
Has anyone come across similar issue , please suggest me solution. Any help is appreciated.

I had a similar issue. You are probably missing a Jetty session manager in your handler list.
Instead of:
server.setHandler( context );
do this:
HandlerCollection contexts = new HandlerCollection( new org.eclipse.jetty.server.session.SessionHandler(), context );
server.setHandler( contexts );

Related

How to fix "org.apache.shiro.UnavailableSecurityManagerException" error with "SecurityUtils.getSubject()"

I try to read data from web-server, which situated at some URL.
In our company I use e-Commerce API, which works with the data from web-server.
To retrieve the data at first I need to make pool of the data from web-server.
To make the pool of data I need to configure connection.
One part from step "I need to configure connection" is function getSession(), which uses the Shiro api(org.apache.shiro.SecurityUtils)
so every time when I try to make connection with web-server and use the data from the web-server I become an Exception "Exception in thread "main" org.apache.shiro.UnavailableSecurityManagerException: No SecurityManager accessible to the calling code, either bound to the org.apache.shiro.util.ThreadContext or as a vm static singleton. This is an invalid application configuration."
Before writing this question I tried to look at logs and read about classes and problem, which describe there.
This all runs on Windows 10, Java 8, Payara Server(Glassfish), with EJBAPI and some e-Commerce API.
Import that I use
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
at
ContentConfiguration conf = new ContentConfiguration(
getSessionId(),
Constant.ENTITYMODELL,
Constant.EMPTY,
context);
protected static Session getSession()
{
Subject subject = SecurityUtils.getSubject();
if(subject.isAuthenticated())
return subject.getSession();
else
return null;
}
Error Message
Exception in thread "main" org.apache.shiro.UnavailableSecurityManagerException: No SecurityManager accessible to the calling code, either bound to the org.apache.shiro.util.ThreadContext or as a vm static singleton. This is an invalid application configuration.
at org.apache.shiro.SecurityUtils.getSecurityManager(SecurityUtils.java:123)
at org.apache.shiro.subject.Subject$Builder.<init>(Subject.java:627)
at org.apache.shiro.SecurityUtils.getSubject(SecurityUtils.java:56)
at de.kolb.demo.data.ServiceLocator.getSessionId(ServiceLocator.java:15)
at de.kolb.demo.logic.CommonTest.getCommonData(CommonTest.java:32)
at de.kolb.demo.presentation.ContentDirector.main(ContentDirector.java:34)
I want to get answer which represent situation in my company, but a lot of principes, which i will to describe connect with common proplem in Shiro hub.
1.My problem connect with getSessionId() enter image description here
2.getSessionId() it's a function from company API. In this function i call org.apache.shiro.SecurityUtils.getSubject() enter
link description here
At this moment I thought about exception Message No SecurityManager accessible to the calling code.... Than I look at Shiro documentation here enter link description here. There i found, that every time when i use Aplication, which use authentication and autorisation i need to configure "SecurityManager" with "Realm" object.
4.It is a small instruction and detailed instruction present at shiro site enter link description here

MDB new threads are calling onMessage while previous thread not finished

In JBOSS EAP6 I've got a long running MDB thread listening to a JMS Queue. It received a Text Message with a DB key of work it should process (loop).
During its execution I noticed that new threads spawn new MDB instances, leading to inconsistencies. I do want to prevent that in a programmatic manner or in a configuration manner whithout changing performace. So, for instance check in the onMessage that work is ongoing. I can't change the DB Model.
Since I'm running in a single VM I'm on the verge (last resort) of using a static Set that stores the DB key. (I'm a bit under time pressure to fix this).
The problem was caused by the fact I forgot the specify the transaction time-out. Hence the default time-out seems to kick in.
The problem was solved by adding the transaction time out:
#ActivationConfigProperty( propertyName = "transactionTimeout", propertyValue = "10800" )

How to change Jetty settings through SparkJava? / Form too Large Exception / org.eclipse.jetty.server.Request.maxFormContentSize

I'm using SparkJava 2.2 which is using Jetty 9.0.2.
I'm getting "Form too large" exception which is thrown by Jetty. I already know how to solve this problem if I was using Jetty directly:
Form too Large Exception
http://www.eclipse.org/jetty/documentation/current/setting-form-size.html
PROBLEM :
Now I need to find a way to change org.eclipse.jetty.server.Request.maxFormContentSize setting through SparkJava. Is there a way to do this?
I must note that other methods (JVM_OPTS, System.setProperty) do not work for me for some reason. I'm still getting the same exception.
Stacktrace:
[qtp1858644635-27] ERROR spark.webserver.MatcherFilter -
java.lang.IllegalStateException: Form too large 308913>200000
at org.eclipse.jetty.server.Request.extractParameters(Request.java:334)
at org.eclipse.jetty.server.Request.getParameterMap(Request.java:765)
at javax.servlet.ServletRequestWrapper.getParameterMap(ServletRequestWrapper.java:193)
at spark.QueryParamsMap.<init>(QueryParamsMap.java:59)
at spark.Request.initQueryMap(Request.java:364)
at spark.Request.queryMap(Request.java:349)
at spark.webserver.RequestWrapper.queryMap(RequestWrapper.java:213)
at com.xyz.analytics.webservice.RequestTools.getRequestQueryMap(RequestTools.java:27)
at com.xyz.analytics.webservice.RequestTools.getMandrillQueryParams(RequestTools.java:22)
at com.xyz.analytics.webservice.Endpoints.lambda$initiateEndpointsAndExceptionHandlers$2(Endpoints.java:61)
at com.xyz.analytics.webservice.Endpoints$$Lambda$3/1485697819.handle(Unknown Source)
at spark.SparkBase$1.handle(SparkBase.java:311)
at spark.webserver.MatcherFilter.doFilter(MatcherFilter.java:159)
at spark.webserver.JettyHandler.doHandle(JettyHandler.java:60)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:179)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:136)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
at org.eclipse.jetty.server.Server.handle(Server.java:451)
at org.eclipse.jetty.server.HttpChannel.run(HttpChannel.java:252)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:266)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.run(AbstractConnection.java:240)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:596)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:527)
at java.lang.Thread.run(Thread.java:745)
Edit:
I must note that other methods (JVM_OPTS, System.setProperty) do not work for me.
Well, debugger doesn't even stop at any breakpoint set within org.eclipse.jetty.server.handlerContextHandler... Plus when it stops at org.eclipse.jetty.server.Request breakpoints, _context property is null. Seems that SparkJava is handling it differently. Dead end.
Request does one more thing before setting maxFormContentSize = 200000;. It checks _channel.getServer().getAttribute("org.eclipse.jetty.server.Request.maxFormContentSize").
Except Server's attribute collection is empty... And I don't see any way to add any attribute. Jetty Server is created by SparkBase.init() which calls SparkServer.ignite().
But it doesn't help us much. It's not easy to "break in" to make our own adjustments. It seems pretty hopeless.
Not possible with Spark 2.2
The creation of the ServerConnector is hardcoded in the SparkServer, you cannot change those values after the fact, they have to be passed into the ServerConnector before server start.
Would recommend filing a bug with Spark to make that configurable.
https://github.com/perwendel/spark/issues
Good news everyone :)
In Spark 2.6 (released April 2017) embedded Jetty is fully configurable!
Release notes: http://sparkjava.com/news#spark-26-released
See the original future request for more details here: https://github.com/perwendel/spark/issues/314
and related pull request here:
https://github.com/perwendel/spark/pull/813
NOTE that it is also possible to run Spark on another web server instead of the embedded Jetty server:
http://sparkjava.com/documentation#other-web-server
Well, having access to the server object, you can always do something like:
server.setAttribute("org.eclipse.jetty.server.Request.maxFormContentSize", 1024 * 1024);
Hope this helps!

Is it possible to invalidate spring mvc sessions if browser is closed or power got off?

In Spring MVC I am able to get all the session by the following code.
int active= sessionRegistry.getAllPrincipals().size();
List<String> activeSessionsId = new ArrayList<String>();
for(int i=0;i<active;i++){
List<SessionInformation> si=
sessionRegistry.getAllSessions(sessionRegistry.getAllPrincipals().get(i), false);
for(SessionInformation s:si){
System.out.println("SessionId="+s.getSessionId());
activeSessionsId.add(s.getSessionId());
}
}
Here sessionRegistory is my spring given bean I configured it like this:
<beans:bean id="sessionRegistry" class="org.springframework.security.core.session.SessionRegistryImpl" />
And autowired in my controller like this:
#Resource(name="sessionRegistry")
private SessionRegistryImpl sessionRegistry;
I thought activeSessionsId list would be contain only active session but it contain all the users session that I logged in and passed by spring security. For some users I closed the browser without logout and I was expecting this session won't be add in my activeSessionsId
list but it is not like that .
I observed all sessionId got added in activeSessionsId.
Actually Concept wise I know the session creation is happening by server side .But Please any one let me know whatever I am trying is it possible or not in a case of spring MVC.
From the point of view of server, you must admit that you cannot know if browser if closed. Ok, you can try to use javascript to send something when closing window, but anything can happen :
the network can go down at any point (system, modem, proxies), voluntarily or not
power can go off, voluntarily or not
javascript can be disabled
user can use a headless browser (Selenium, Python or Java or ... code) that could choose to ignore all or part of javascript
So use javascript if you want and it will work in the great majority of use cases, but always keep a session timeout for the unwanted silent disconnection that can still occur whatever you do.
In general, when I close the browser, the server i'm talking to will have no way of knowing I closed the browser - unless, you tell it somehow. Typically you do this with a bit of javascript and listen for the browser close event and call the server to tell them they closed the browser.
On this call, you can invalidate that user's session and that should remove it from your active sessions list
Alternatively, you you add session timeout on the server which will remove the sessions upon expiry of certain amount of time.

Verification failure while using openid4java for 'login with google'

I am using openid4java library for implementing the 'login with google' functionality in a spring-mvc application.
It works fine on my local tomcat server but on the remote server it has suddenly stopped working. It was working fine before there too.
After doing some logging in catalina.out I found that the verification of the response fails after google redirects to the return url
VerificationResult verification = openIdService.getConsumerManager().verify(
receivingURL.toString(),
response, discovered);
Identifier verified = verification.getVerifiedId(); //Null
The value of verified is null on the remote server. On local server its an uri
I am aware that while handling the response, ConsumerManager needs to be the same
instance used to place the authentication request.
The rest of the code is implemented as follows
There is an OpenIdController in which OpenIdService is Autowired.
The OpenIdServiceImpl implements OpenIdService and has the getConsumerManager method which returns the consumerManager instance.
In the construct of the OpenIdServiceImpl, an instance of ConsumerManager is created.
The actions that create the form for submission and handle the response are written in the
OpenIdController and access the consumerManager instance using the getConsumerManager method.
Edit:
I tried logging the Discovery information before the form submission and in the call back here it the output
Debugging OpenId: Discovered (before) OpenID2
OP-endpoint:https://www.google.com/accounts/o8/ud
ClaimedID:null
Delegate:null
Debugging OpenId: Discovered (after) OpenID2
OP-endpoint:https://www.google.com/accounts/o8/ud
ClaimedID:null
Delegate:nul
Am I doing anything wrong here ? But it works on local server!
Or something to do with tomcat configuration on the remote server ?
Any help is appreciated. I can post code if required.
Thanks.
I could resolve this problem by adding the following lines after creating an instance of ConsumerManager.
consumerManager.setAssociations(new InMemoryConsumerAssociationStore());
consumerManager.setNonceVerifier(new InMemoryNonceVerifier(5000));
consumerManager.setMinAssocSessEnc(AssociationSessionType.DH_SHA256);
I found it mentioned it in one of the comments to the SampleConsumer example here - http://code.google.com/p/openid4java/wiki/SampleConsumer
see response #3 from the bottom.
Haven't yet tried to figure out what it does, but hope its the right way to solve it :)

Categories