0

I am currently learning Java EE, and I was asked to develop a backend RESTful Java API that will communicate with a database stored on a cloud solution (IBM Bluemix).

I currently use Eclipse Photon as IDE and I am not an admin user on the computer.

I was asked to test my code with IBM Was Liberty server plugin for eclipse, but I have some trouble setting up the server. I think I may have not understood how the plugin works and can't make it work as I want it to.

The problem is that I can't access the database stored on that server, be it with my api or admin center (can't even log on admin center).

Here is the java code I use (modified) and found on this site

package connection;

//STEP 1. Import required packages
import java.sql.*;

public class FirstExample {
 // JDBC driver name and database URL
 static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";  
 static final String DB_URL = "jdbc:mysql://localhost:3306/ibm/api/validator/dataSource/SAMPLEDB";
 //  Database credentials
 static final String USER = "admin";
 static final String PASS = "admin";

 public static void main(String[] args) {
 Connection conn = null;
 Statement stmt = null;
 try{
    //STEP 2: Register JDBC driver
    Class.forName(JDBC_DRIVER);

    //STEP 3: Open a connection
    System.out.println("Connecting to database...");
    conn = DriverManager.getConnection(DB_URL, USER, PASS);

    //STEP 4: Execute a query
    System.out.println("Creating statement...");
    stmt = conn.createStatement();
    String sql;
    sql = "SELECT * FROM *";
    ResultSet rs = stmt.executeQuery(sql);

    //STEP 5: Extract data from result set
    while(rs.next()){
       //Retrieve by column name

       String data = rs.getString("last");
       //Display values
       System.out.println("Data Retreived " + data);
    }
    //STEP 6: Clean-up environment
    rs.close();
    stmt.close();
    conn.close();
 }catch(SQLException se){
    //Handle errors for JDBC
     System.out.println("\nJDBC ERROR ! \n");
    se.printStackTrace();
 }catch(Exception e){
    //Handle errors for Class.forName
     System.out.println("\nClass.forName ERROR ! \n");
    e.printStackTrace();
 }finally{
    //finally block used to close resources
    try{
       if(stmt!=null)
          stmt.close();
    }catch(SQLException se2){
        System.out.println("\nSQL ERROR ! NOTHING TO DO \n");
    }// nothing we can do
    try{
       if(conn!=null)
          conn.close();
    }catch(SQLException se){
        System.out.println("\nJDBC ERROR ! MAYBE SOMETHING TO DO \n");
       se.printStackTrace();
    }//end finally try
 }//end try
 System.out.println("\nGoodbye!");
}//end main
}//end FirstExample

As for my Server.xml here is the updated code :

<server description="Liberty beta">

    <featureManager>
        <feature>webProfile-8.0</feature>
        <feature>adminCenter-1.0</feature>
        <feature>restConnector-2.0</feature>
        <feature>transportSecurity-1.0</feature>
        <feature>logstashCollector-1.1</feature>
        <feature>validator-1.0</feature>

        <feature>mpConfig-1.3</feature>
        <feature>mpFaultTolerance-1.1</feature>
        <feature>mpHealth-1.0</feature>
        <feature>mpJwt-1.0</feature>
        <feature>mpMetrics-1.1</feature>
        <feature>mpOpenAPI-1.0</feature>
        <feature>mpOpenTracing-1.0</feature>
        <feature>mpRestClient-1.0</feature>

        <feature>localConnector-1.0</feature>
        <feature>jdbc-4.2</feature>
    </featureManager>

    <httpEndpoint   id="defaultHttpEndpoint"
                    host="*"
                    httpPort="9080"
                    httpsPort="9443" />

    <applicationManager autoExpand="true"/>

    <keyStore   id="defaultKeyStore"
                password="Liberty" />

    <basicRegistry id="userReg">
        <user   password="admin"
                name="admin"
                id="admin"></user>
    </basicRegistry>

    <administrator-role>
        <user>admin</user>
    </administrator-role>

    <remoteFileAccess>
        <writeDir>${server.config.dir}</writeDir>
    </remoteFileAccess>

    <dataSource id="DefaultDataSource" jndiName="jdbc/mySQL">
        <jdbcDriver libraryRef="MySQLLib" />
        <properties.microsoft.sqlserver databaseName="SAMPLEDB" serverName="localhost" portNumber="3306" user="admin" password="admin"/>
        <connectionManager></connectionManager>
    </dataSource>
    <library id="MySQLLib">
        <file name="C:/PUBLIC/tools/mysql-connector-java-8.0.12/mysql-connector-java-8.0.12/mysql-connector-java-8.0.12.jar" />
    </library>    

</server>

The problem I got now is that I can't seem to be able to communicate with my server.

here is the console error :

Connecting to database...

JDBC ERROR ! 


Goodbye!
com.mysql.cj.jdbc.exceptions.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 com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:832)
    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456)
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:240)
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:207)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:247)
    at connection.FirstExample.main(FirstExample.java:23)
Caused by: com.mysql.cj.exceptions.CJCommunicationsException: 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(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:105)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:151)
    at com.mysql.cj.exceptions.ExceptionFactory.createCommunicationsException(ExceptionFactory.java:167)
    at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:91)
    at com.mysql.cj.NativeSession.connect(NativeSession.java:152)
    at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:952)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:822)
    ... 6 more
Caused by: java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at com.mysql.cj.protocol.StandardSocketFactory.connect(StandardSocketFactory.java:173)
    at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:65)
    ... 9 more
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Mones Haq
  • 11
  • 3
  • 1
    Spring is not Java EE. First of all, dont use Spring and Hibernate, you dont need it. Just create simple JAX-RS web app. Liberty provides JAX-RS, and JPA runtime built in. Second, you need only enable features that you need, not `javaee-8.0` as it conflicts with spring libraries you included. – Gas Sep 26 '18 at 12:42
  • 1
    You have a lot of missing DB configuration. For starers you'll need to add a JDBC driver and configure it to point to a DB (whether it's a remote DB or just a simple embedded DB). Check out this article for details on configuring a DataSource: https://www.ibm.com/support/knowledgecenter/en/SS7K4U_liberty/com.ibm.websphere.wlp.zseries.doc/ae/twlp_dep_configuring_ds.html – Andy Guibert Sep 26 '18 at 14:22
  • 1
    If you managed to solve your own problem, then please post an **answer** with your solution. Do not add the solution to your question and do not add things like 'solved' to the title of your question. – Mark Rotteveel Sep 28 '18 at 15:23
  • Possible duplicate: https://stackoverflow.com/questions/6865538/solving-a-communications-link-failure-with-jdbc-and-mysql – Mark Rotteveel Sep 28 '18 at 15:27

1 Answers1

0

As a beginner, i tried to follow blindly tutorials found online and didn't thought much about what i actually was doing.

I didn't understand that Was Liberty is not like setting up a VM with the services you wanted, moreover setting up a dataSource in Liberty IS NOT setting up a database. lacking of info, guidance and rigor, i thought that the Liberty server was actually running a mySQL server when i created my dataSource. in fact (correct me if i'm wrong) this portion of code,

<dataSource id="DefaultDataSource" jndiName="jdbc/mySQL">
    <jdbcDriver libraryRef="MySQLLib" />
    <properties.microsoft.sqlserver databaseName="SAMPLEDB"
                                    serverName="localhost"
                                    portNumber="3306"
                                    user="admin"
                                    password="admin"/>
    <connectionManager></connectionManager>
</dataSource>

<library id="MySQLLib">
    <file name="C:/PUBLIC/tools/mysql-connector-java-8.0.12/mysql-connector-java-8.0.12/mysql-connector-java-8.0.12.jar" />
</library>

is meant to set up the service in the server with the adequate driver to connect to your distant database. in this scenario, i've set up a dataSource with a mySQL Driver.

When i did ran a local mySQL server, i was able to communicate and send queries throught my java app.

thanks for the people who took time to read this post and tried to help me.

Mones Haq
  • 11
  • 3