Hibernate - Tomcat - SQL Server - Connection closed issue - java

I've a webapp running on TOMCAT 7.0.5 - JDK 1.7 - and connecting to SQL Server 2012.
The hibernate version is 4.3.5. Browser used is IE 11.0.
The issue Is I have a webpage: A normal FORM submit (submit.jsp). It shows a readonly page (submitConfirm.jsp) and has two buttons.
Submit - Saves the application and redirects the page to the home page to start subscription again
Print - opens a new tab via javascript to print a PDF form that likely takes 2 to 5 seconds to render in a "new" tab.
The submit button is disabled by defualt and enabled only when user clicks on the PRINT Button. While the item is still rendering If someone clicks on Continue button - all actions perform well and at the I get both the print and subscriptions saved.
The next subscriptions entered would throw a http 500 error indicating the "Connection is already closed".
I use the Standard HibernateUtil paradigm to begin/end/commit/rollback transactions.
The models are all XML based (not entity decorator based).
For normal workflows where if the user waits till the PDF is rendered all is fine.
But If the user is pressing the button of continue - Seems there is an issue.
Attached is the screen-grab of the error is someone finds it useful provide some hints.
Based on the user feedback (the concerned method):
public String reportSessionId(String userId) throws InfrastructureException {
String sid = null;
try {
sid = (String) HibernateUtil.getSession()
.getNamedQuery("com.ttsme.ims.model.IMSUser.reportSessionId")
.setString("userId", userId).uniqueResult();
}
catch (HibernateException ex) {
throw new InfrastructureException(ex);
}
catch (Exception exp)
{
exp.printStackTrace();
}
return sid;
}

Related

Keycloak is not maintaining session in browser

I am using keycloak(4.3.0) openid-connect flow. For my client app, I am using:
public class AuthenticationTest {
public static void main(String[] args) {
final String KEYCLOAK_JSON = Constants.KC_CONFIG_JSON_PATH;
InputStream config = Thread.currentThread().getContextClassLoader().getResourceAsStream(KEYCLOAK_JSON);
KeycloakInstalled keycloak;
try {
keycloak = new KeycloakInstalled(config);
config.close();
keycloak.loginDesktop();
AccessToken token = keycloak.getToken();
System.out.printf("UserId: %s%n", token.getSubject());
System.out.printf("Username: %s%n", token.getPreferredUsername());
System.out.printf("Email: %s%n", token.getEmail());
System.out.println(keycloak.getTokenString());
System.in.read();
} catch (IOException | VerificationException | OAuthErrorException | URISyntaxException | HttpFailure
| InterruptedException e) {
e.printStackTrace();
}
}
}
I have referred the example mentioned here: https://gist.github.com/thomasdarimont/ca16080145d226e50628d5696ffb9508
First time I launch the application and login, I get
"Login Successful.You may close this browser window and go back to
your console application."
However, if I launch second instance of my application/ relaunch my application even without closing the previous browser window , still the login page appears instead of you are already logged in message.
(The new login page is appearing in a new tab on the same window as the first login page, so it is not an issue of failure to maintain state across different windows. Also I have tried relaunching the app withing 20 seconds so it does not seem t be an issue of timeout either)
Browser: Firefox, chrome.
Any idea what I am doing wrong. Expectation is that browser must maintain a keycloak session for the same user until closed for at least a few minutes.
NOTE: I did not face this issue in Keycloak 3.4.3. But it started coming on 4.1.0 and 4.3.0
I see follwing difference in cookies on 3.4.3 and 4.x:
3.4.3: (same whther first login or subsequent login)
4.x First time login:
4.x Subsequent login: (an addition KC_RESTART cookie is seen)

Java jsoup checking button

I am trying to check whether a page contains next page to sroll. The idea is basic: get the current link, remove the index at the end and then put new index, try to connect to the new link, if it throws IOException that means it does not have next button so that can be scrolled. Here is my code, and the problem it returns false even to the links that Jsoup can connect:
public boolean checkNextButton(String linkToCheck) throws IOException {
boolean containsNextButton = true;
try {
//Here I am trying to connect to a link which is actually available but it still returns false
Document doc = Jsoup.connect(turnToNextPage(linkToCheck)).get();
specific.setPageChangeRate(specific.getPageChangeRate() - 1);
//Set back the counter to the previous one
} catch (IOException e) {
containsNextButton = false;
}
System.out.println("The page contains next button: " + containsNextButton);
return containsNextButton;
}
Solution provided by Pshemo:
It is hard to tell what exactly went wrong without more details.
Are you able to access resource from linkToCheck via browser? Did you need to log-in on that site first (maybe try accessing it via incognito mode to see if it is available for anyone without creating an account).
Other problem could be that some servers allow only specific browsers and they try to recognize them by using user-agent header browsers send, or if server is creating temporary session you may need to pass cookies from previous connection.

Java embedded browser

I'm using the embedded browser.
import org.eclipse.swt.browser.Browser;
.....
final Browser g11_embedded_browser = new Browser(g11_capture_script, SWT.NONE);
g11_embedded_browser.setBounds(0, 0, 1000, 260);
g11_embedded_browser.setVisible(true);
...........
try {
uri = new URI("http://127.0.0.1:" + g11_txt_PATH_portnumber.getText());
} catch (URISyntaxException e1) {
System.out.println("failed setting uri");
e1.printStackTrace();
}
System.out.println("uri=" + uri.toString());
try {
url = uri.toURL();
The full url is: http://127.0.0.1:6500
The C program listening on 6500 sometimes responds first time. At other times it takes 2 attempts.
I believe it returns a 204 when the connection fails.
My questions in the hope someone can point me in the right direction are:
Is there any way I can detect the 204? It displays nothing in the browser as it is deemed a successful reply.
Any clue as to why the 204 as the C program never issues a 204 when the request comes from any browser on any OS, just when from the embedded browser.
Note:
The browser displays an internet page before the localhost request so it isn't an embedded browser start up issue. Tried it with and without that.
Tried interleaving requests to the C program from browsers and the Java browser but 100% success externally and about 50% failures from Java on first attempt. Occasionally needs three or even 4 attempts but always works in the end.
A 204 is "204 - The server successfully processed the request, but is not returning any content. Usually used as a response to a successful delete request." However the localhost call is a request for the display of a simple form.

How to handle (failed) login attempts with Smack XMPP API

I'm developing a chat server based on XMPP and Smack API, which connects to an Openfire server (Hosted by a friend who is also developing this with me).
So, I started programming it just a few days ago (Netbeans on OS X 10.8), and today I went on to the connection and login aspects.
I can login perfectly with the right choice of username+password :P but I don't know how to handle an invalid login attempt and let the app show a message and then allowing the user to retry.
Here's my code, which fires after user has pressed a button in my Swing JForm:
(Note: XMPPConnection object is already created in another class, and the connection has been made to the server. You can see I'm calling the object from that another class)
private void btnIniciarSesionActionPerformed(java.awt.event.ActionEvent evt) {
String Usuario = txtUsuario.getText();
String Password = new String (pwdContrasena.getPassword());
if (Usuario.equals("") || Password.equals("")){
// Missing data
JOptionPane.showMessageDialog(null, "Missing data");
}
else{
//Try to login
try{
Proyecto_chat.conexion.login(Usuario, Password, "x");
}
catch (XMPPException ex){
Logger.getLogger(Ventana_login.class.getName()).log(Level.SEVERE, null, ex);
// Problem
}
if (Proyecto_chat.conexion.isAuthenticated() == true){ //Login has been successful
jLabel1.setVisible(false);
System.out.println("Authenticated as " + Usuario);
JOptionPane.showMessageDialog(null, "Authenticated as " + Usuario);
//Exit login window and carry on
}
else{
JOptionPane.showMessageDialog(null, "login error");
}
}
}
Should I play with that exception I'm getting? ->
SEVERE: null
SASL authentication DIGEST-MD5 failed: not-authorized:
at org.jivesoftware.smack.SASLAuthentication.authenticate(SASLAuthentication.java:337)
at org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:203)
at proyecto_chat.Ventana_login.btnIniciarSesionActionPerformed(Ventana_login.java:159)
at proyecto_chat.Ventana_login.access$100(Ventana_login.java:15)
at proyecto_chat.Ventana_login$2.actionPerformed(Ventana_login.java:73)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
(...) more lines that I think are not critical for this
As passwords are stored in plain text (University project, so it doesn't matter) for simplifying changing them from inside the application, I can connect to the database (PostgreSQL in remote server) from the client computer, and check the passwords and only do 'conexion.login' if user&pass matches, but that would be... you know... wrong
After looking around on the web with no luck, I decided to head over here, ask, go to sleep and wake up next morning with some suggestions ;)
Help shall be appreciated
Not sure if I understand what you are asking but if it's "How can I determine the reason for a failed login attempt with Smack?" then here is my answer:
You have to evaluate the (XMPP)Exception's message string as of Smack 3.2.2 if you want to determine the reason for the failed login. These message strings that distinguish between the various failure reasons are currently hard-coded in the source, which is usually not a good idea.
A while ago I have created SMACK-416 "Improve Exceptions on connect() and login()" to address this issue. The idea is to replace the hard-coded strings/failure reasons with a class hierarchy. But it sure will take a few months until this is implemented (and maybe a few weeks/months/years until it is released).
Actually, the main problem was that when I tried to login using an invalid username/password, some exception was thrown (As well as an information display that I set up), but the application wouldn't let me log in again (As if I corrected my data and clicked the button again).
I finally solved this by placing the .connect() right behind the .login() method, and calling .disconnect() in case a bad login was made, so the server would be reconnected every time the user tried to log in .
This might not be the ideal approach, but I find it easy and do-able. Thanks for helping!

Loop attempt to connect to JDBC

I'm trying to create an application for checking in and out devices. So far I've had success but I'm trying to have the main index.jsp page that is called display a message like "connecting" until a connection with the database can actually be made and then display the actual login form. So something to the effect of.
Connection con = null;
String driver = "com.mysql.jdbc.Driver";
Class.forName(driver).newInstance();
boolean connected = false;
while(!connected) {
try{
String url = "jdbc:mysql://localhost:3306/test";
con = DriverManager.getConnection(url,"username","password");
connected = true;
//Display form allowing user to authenticate login
} catch(Exception e) {
//Display Message "Attempting to connect to database"
}
}
The problem I have is the same message will get repeated over and over on the web page but i just want it to display once and stay there until the connection is found and then be removed and replace with the login form. Any thoughts?
I suggest you use connection pooling.... it is quite easy to manage connections and the overheads will be reduced making your app efficient.
see the following:
Setup Connection pooling in jsp/servlets application based on MVC?
Am I Using JDBC Connection Pooling?
Setup Connection pooling in jsp/servlets application based on MVC?
Change your code in this way
Connection con = null;
String driver = "com.mysql.jdbc.Driver";
Class.forName(driver).newInstance();
boolean connected = false;
int errors = 0;
while(!connected) {
try{
String url = "jdbc:mysql://localhost:3306/test";
con = DriverManager.getConnection(url,"root","ikkakumon");
connected = true;
//Display form allowing user to authenticate login
} catch(Exception e) {
if (errors == 0) {
//Display Message "Attempting to connect to database"
}
++errors;
Thread.sleep(1000); // wait a little before the next attempts
}
}
So you display the error message only the first time.
Then wait between one attempt and another.
However the loop is not the usual way to manage connections. Why do you choose this solution? What kind of exception do you receive?
Any thoughts?
Yes.
You need to get your head around HOW stuff gets displayed to the user. The normal model is that browser sends an HTTP request to the server, the server creates a response consisting of an HTML page, and the browser displays the page. In this model, if you want the user to see the results, the server has to finish and send the response. Until it does, the user sees a blank screen (or the page he / she was on previously).
So to get a page that updates you have two options:
You can create a page that contains a <meta> tag that requests that the browser resends the request after a fixed delay; see http://en.wikipedia.org/wiki/Meta_refresh
You can embed javascript in the page to send an AJAX request to the server asking for an update. On getting a response, the javascript then needs to modify the DOM of the displayed page with the new information.
But in either case, it should be clear to you that you cannot do this in a single call to a single JSP. So you don't want a while loop in the JSP, or in the controller that dispatches to the JSP. The looping has to happen at the browser end.

Categories

Resources