Loop attempt to connect to JDBC - java

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.

Related

Hibernate - Tomcat - SQL Server - Connection closed issue

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;
}

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 get user logout time when user closes the web browser without logging out from application [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have created web application that handle user login with it and update logout time when user logout from application, but when user close web browser directly or system gone shutdown with some problem, i am not able to update user logout time.
Please give any possible way to update user logout time on such circumstances.
Assuming javascript on client side as it is a webapp.
In such cases you should send a request in browser close event
window.onbeforeunload = function(event) {
//send request to server .
}
Prefer to read :want to detect browser close event?
May the following steps help you to update logout time.
1.Keep updating a timestamp variable in session for each request.
2.During session time out get the variable value (which holds when user accessed at last) and update in logout record.
This could help without depending the browser to send logout request.
try this code to implement
window.onbeforeunload = function(event) {
var isOK = confirm("Are you sure to Leave this Page?");
if(isOK)
{
// try ajax for update your table
}
}
You can create a class which implements HttpSessionListener and annotated #WebListener() like this:
#WebListener()
public class MyListener implements HttpSessionListener {
#Override
public void sessionCreated(HttpSessionEvent se) {
}
#Override
public void sessionDestroyed(HttpSessionEvent se) {
Date lougOutDate=new java.util.Date();
}
}
in sessionDestroyed method you retrieve the date of disconnection
Why don't you use a TimeOut ?
There is several solutions :
Timeout
Implement HTTP COOKIE. Check the link below
http://en.wikipedia.org/wiki/HTTP_cookie
In your specific case it should be Session Cookie
Session cookie
A user's session cookie[14] (also known as an in-memory cookie or transient cookie) for a website exists in temporary memory only while the user is reading and navigating the website. When an expiry date or validity interval is not set at cookie creation time, a session cookie is created. Web browsers normally delete session cookies when the user closes the browser.[15][16]
Do the stuff with Javascript as suggested
Hope it's help :)
You could try to write some Javascript that sends an "User logging out" message to the server. This code should be triggered using $.unload() (if you're using jQuery) or binding to the native unloadevent of the browser.
There is no way of precisely getting the logout time in such circumstances, as this might be for example caused by internet connection loss.
Some possibilities:
Send an ajax request on document unload to notify your server (as suggested by #Baadshah and #mthmulders)
Add a session timeout listener on the server to set the logout time when the session times out - this way even if the ajax doesn't get to the server you will know that the user logged out during the last few minutes (depending on the session duration)
Use the event beforeunload with jquery on your page.
The beforeunload event fires whenever the user leaves your page for any reason.
For example, it will be fired if the user submits a form, clicks a link, closes the window (or tab), or goes to a new page using the address bar, search box, or a bookmark.
You could exclude form submissions and hyperlinks (except from other frames) with the following code:
var inFormOrLink = false;
$(document).on('click','a', function() { inFormOrLink = true; });
$(document).bind('submit','form', function() { inFormOrLink = true; });
$(window).on('beforeunload',document, function(eventObject) {
var returnValue = undefined;
if (inFormOrLink == false) {
//do your action
}
});
EDIT: Answer found here: How to capture the browser window close event?

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!

Categories

Resources