tags:

views:

51

answers:

2

I just talked to my host that I have my web page at and they say they allow JDBC connections.

Anyway, the page you can view this at is http://mystikrpg.com/mysqltest/mysqltry.html

Here is my error:

**** Looking for database...
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
    at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1118)
    at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:343)
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2308)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2122)
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:774)
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:49)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:375)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:289)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at test.init(test.java:38)
    at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.net.SocketException: java.security.AccessControlException: access denied (java.net.SocketPermission [0:0:0:0:0:0:0:1]:4464 connect,resolve)
    at com.mysql.jdbc.StandardSocketFactory.unwrapExceptionToProperClassAndThrowIt(StandardSocketFactory.java:407)
    at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:268)
    at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:292)
    ... 16 more
java.lang.NullPointerException
    at test.init(test.java:69)
    at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Exception: java.lang.NullPointerException

and here is the code:

What am I doing wrong?

//package mysqltest;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.Applet;
import java.awt.TextArea.*;
import java.sql.*;
import java.util.*;
import javax.swing.plaf.*;
import javax.swing.plaf.basic.*;
import java.net.*;
import java.applet.*;

public class test extends JApplet
{
    public JTextArea c;
    public void init()
    {
        c = new JTextArea();
        add(c);
        c.append("**** Looking for database...");
        Connection conn = null;
        Properties props = new Properties();
        String url = "jdbc:mysql://localhost:3306/";
        String dbName = "mystik";
        String driver = "com.mysql.jdbc.Driver";
        String userName = "root";
        String password = "";
        String loggedusername = getParameter("name");
        boolean online = false;
        try
        {
            Class.forName(driver).newInstance();
            online = true;
            if (online)
            {
                // if user loads applet online
                conn = DriverManager.getConnection("jdbc:mysql://localhost:4464/jsfdan_mystikdan", "jsfdan_muser", "test");
            }
            else
            {
                // for localhost - testing purposes props.put("user", "root");
                conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mystik", props);
            }
            c.append("\nConnected to the database");
            c.append("\nGetting stats for: " + loggedusername);
            PreparedStatement statement = conn.prepareStatement( "select * from `user` where `username` = '"+loggedusername+"'");
            ResultSet result = statement.executeQuery();
            // just a dumb mysql statement! while(result.next())
            {
                c.append("\nUsername: "+result.getString(2)+ "\nLevel: "+result.getString(6)+"\nEXP: "+result.getString(8)+"\n");
            }
            PreparedStatement updateEXP = conn.prepareStatement( "update`user` set `exp` = '666' where `username` = '"+loggedusername+"'");
            updateEXP.executeUpdate();
            ResultSet xresult = statement.executeQuery();
            while(xresult.next())
            {
                c.append("\nUsername: "+xresult.getString(2)+ "\nLevel: "+xresult.getString(6)+"\nEXP: "+xresult.getString(8)+"\n");
            }

            c.append("\nDisconnected from database");
        }
        catch (Exception e)
        {
            System.out.println(c.getText());
            e.printStackTrace();
        }finally {
            try {
            conn.close();
        }catch(SQLException dan) {dan.printStackTrace(); }
        }
    }
}
+2  A: 

Quoting your code:

  // if user loads applet online
  conn = DriverManager.getConnection("jdbc:mysql://localhost:4464/jsfdan_mystikdan", "jsfdan_muser", "test");

An applet is a program running on the user's machine, where the browser is. Thus, localhost refers to the user's machine at this stage. Chances are that most users aren't running MySQL on their own machine, that even if they were, it wouldn't be the one your applet is after and that it would get out of the applet's sandboxed environment anyway.

EDIT (after discussion in comments):

From the discussions and the comments in the previous related questions, it looks like you're trying to connect directly to your MySQL server from an application (applet) distributed to clients that could be anywhere, which is usually the wrong approach.

  • You were concerned about posting your username/password in your examples. That's only a minor problem compared with what could happen if you distributed your applet widely: anyone then could easily look at the traffic sent by your application to your MySQL server and get the username/password.
  • Most MySQL servers are blocked from external access, mostly because they don't provide suitable access control on their own compared with the access requirements of the overall application. This is not always the case, but the access control on INSERT/SELECT/UPDATE operations on their own are often too crude to represent the functional purpose of the overall application.

With most services that use a database, the user-management and access control is done at the application level, not at the database level. This is particularly the case when you're using a shared provider that creates a database and a user account for your entire application to use, even if you want multiple users.

The typical workaround for this is do develop another service (typically a web-service) that your client will call, providing suitable authentication and usage context for the various operations you'd want the client to perform on the data.

I'm not sure if your hosting service lets you run Java services, but cheaper hosting providers tend to let you run PHP, Perl and/or Python services, so you could write a service in one of those languages and have your applet be a client that talk to them.

Explaining how to write web services is probably out of scope of this question/answer. In general, you'll probably come across 3 categories: REST-style web-services (it's an architectural style, guided by the notion of resources and representations), XML-RPC (often called "REST" by mistake, where you send fragments of XML to some web-page that will call a function/method and give you some results in return; you might be able to do the same with JSON) and SOAP (where you'll probably get more tools but might also be more bloated depending on what you're comfortable with). There have been on-going debates as to which is better, but it's up to you to investigate and choose what you think is better for your application. It will probably depend on what can be deployed on your host.

Bruno
+1: Got there a minute ahead of me!
Don Roby
In his [previous question](http://stackoverflow.com/questions/3613395/java-jdbc-connection) he was however using the right URL. I have no idea why it is changed to localhost. @Dan: by the way, the `AccessControlException` is exactly the kind of exception which indicates that the applet is probably not properly signed (referring to the comments in your previous question)
BalusC
I wonder if in this previous question, `jdbc:mysql://epic.0sites.net:208/***` isn't a typo for `jdbc:mysql://epic.0sites.net:2083/***` (blanked when removing the details by hand) and that port is responding to the HTTPS protocol, not the MySQL protocol (208 would be quite unusual to run MySQL).
Bruno
@Bruno: He mentioned as well that he "starred out" sensitive info.
BalusC
@BalusC indeed, I was just suggesting that he may have tried to connect to an HTTPS server instead of a MySQL server, as the other port number values in the examples seem to indicate (I'm not sure). That would certainly trigger an exception along the lines of "Cannot read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost."
Bruno
So is this right? conn = DriverManager.getConnection("jdbc:mysql://epic.0sites.net:4464/jsfdan_mystikdan", "jsfdan_muser", "test");
Dan
Decided that I'm not going to star out info for the sake of getting it right. I'll just change the information later.
Dan
Or is THIS right? conn = DriverManager.getConnection("jdbc:mysql://epic.0sites.net:3306/jsfdan_mystikdan?user=jsfdan_muser
Dan
Neither 3306 or 4464 seem to be open to the outside world. It's quite common not to allow connection further than the local network for MySQL server.
Bruno
So what connection should I use?
Dan
I've just edited my answer, too long for comments.
Bruno
OOOOOk. SO I just read it... and I think I'll just drop it at this point. You lost me, sorry.
Dan
I get what you are saying but it's become way too much for one SIMPLE thing.
Dan
It's probably not as simple as you think it is, unfortunately. I've only given a few possible reasons, but whether the reasons are good or not, most hosting services won't let you connect to their MySQL servers from outside their local networks (where their web servers usually sit).
Bruno
So that's why whenever I see a game that requires that... the owner usuallys respond with "I host myself."?
Dan
Possibly, but that also implies that it's probably not a good design, for the reasons I listed above. Typically, if you don't enable TLS/SSL on MySQL, anyone could be able to intercept the username/password you're using to connect, which is likely to be common to all users it seems in your case (otherwise you'd have to do the MySQL admin when registering users). Most people decompiling the class file could get that too, even when SSL/TLS is used.
Bruno
So I think I got it.. I should use a java getConnection PHP $_GET script to do my MySQL work? :D
Dan
Generally, GET if it's a read operation and POST if it makes modification. You can indeed process POST operations from PHP on the server side (and make PHP become a client to MySQL then) and you can use an HTTP client library (or URLHTTPConnection) on the Java client side. This way you can also use HTTP user authentication. I'd suggest reading on HTTP and various forms of web service design. It's likely that for a simple service, emulating a simple HTML form submission (even without the HTML) will be enough.
Bruno
Oh, I have done this. But it's just that it took too long. I mean you on Command Prompt.. everytime it flashs the little bar where you type? Well it took 5 blinks from that bar until the process of doing the URL post method was finished. I just thought the way I was looking in this topic was faster.
Dan
A: 

The NPE is because Connection conn is never initialized - that's what blows up.

I'd recommend you use a database connectivity tool (like the MySQL Workbench) to establish the correct URL from your system to mystikrpg.com; once you have the correct URL, you can put it in your applet.

As @Bruno indicated, the applet runs locally.

mlschechter
Indeed, but that NPE is only in the finally block, which should contain `if (conn!=null) { conn.close(); }`, that's a side-effect of the original problem.
Bruno