Amazon RDS Connection Error - java

I have trying to connect to Amazon RDS and were able to connect it once though I am unable to connect it again. I have checked my username, password, database name, server, etc. and they are all correct. I have all the required files included before the compilation.
I have attached my code below:
import java.io.File;
import java.net.URL;
import java.sql.*;
import java.util.*;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.InputSource;
import java.net.URL;
import java.sql.*;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.InputSource;
public class test_url {
#SuppressWarnings("null")
public static void main(String[] args){
String url = "jdbc:mysql://newtes.ctt52jgw7nwb6.eu-west-1.rds.amazonaws.com:3306/";
String userName = "amankijawani";
String password = "vegasishere";
String dbName = "newtesDB";
String driver = "com.mysql.jdbc.Driver";
System.out.println("Connecting database...");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url + dbName, userName, password);
System.out.println("Database connected!");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ERROR
Connecting 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:404)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:988)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:341)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2251)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2284)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2083)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:806)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
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:404)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:410)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:328)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at test_url.main(test_url.java:44)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:211)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:300)
... 15 more

Related

Cannot connect to MySQL due to incorrect time zone

I have made a single java app and I want to try to connect to an sql database when window opened. I have add the my-sql-java-8.0.14.jar connector but when I run the app I get an error message.
I have tried multiple times to re-connect, re-build the database and connect with new one but i still get the below error message.
Thanks in advance for your help
"Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Cannot connect to the dbat testDBPack.MainWindow$1.windowOpened(MainWindow.java:47)
at java.awt.Window.processWindowEvent(Unknown Source)
at javax.swing.JFrame.processWindowEvent(Unknown Source)
at java.awt.Window.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Caused by: java.sql.SQLException: The server time zone value '????????? ??? GTB' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:73)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:76)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:835)
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:455)
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:240)
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:199)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at testDBPack.MainWindow$1.windowOpened(MainWindow.java:45)
... 25 more
Caused by: com.mysql.cj.exceptions.InvalidConnectionAttributeException: The server time zone value '????????? ??? GTB' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
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.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61)
at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:85)
at com.mysql.cj.util.TimeUtil.getCanonicalTimezone(TimeUtil.java:132)
at com.mysql.cj.protocol.a.NativeProtocol.configureTimezone(NativeProtocol.java:2241)
at com.mysql.cj.protocol.a.NativeProtocol.initServerSession(NativeProtocol.java:2265)
at com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:1319)
at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:966)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:825)
... 31 more
"
I have checked my credentials, i have sql running but i cannot fix the issue.
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Connection;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JSeparator;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
#SuppressWarnings("serial")
public class MainWindow extends JFrame {
JPanel contentPane;
static Connection conn;
public MainWindow() {
setResizable(false);
setTitle("Coding Factory");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 433, 293);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
addWindowListener(new WindowAdapter() {
#Override
public void windowOpened(WindowEvent e) {
String url = "jdbc:mysql://localhost:3306/teachers";
String username = "panos123";
String password = "panagiotis";
try {
conn = DriverManager.getConnection(url,username,password);
}catch (SQLException ex) {
throw new IllegalStateException("Cannot connect to the db",ex);
}
}
});
JLabel lblNewLabel_1 = new JLabel("Quality Assistance");
lblNewLabel_1.setFont(new Font("Tahoma", Font.PLAIN, 30));
lblNewLabel_1.setBounds(71, 32, 295, 37);
contentPane.add(lblNewLabel_1);
JButton TeachersButton = new JButton(" ");
TeachersButton.setBounds(10, 144, 46, 34);
contentPane.add(TeachersButton);
Also i have another class for the main:
package testDBPack;
import java.awt.EventQueue;
public class TeachersApp {
static MainWindow mainFrame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mainFrame = new MainWindow();
mainFrame.setVisible(true);
mainFrame.setLocationRelativeTo(null);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
Time zone is not configured. Try using the following url:
jdbc:mysql://localhost/teachers?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC

chat app SSLSocket SSLHandshakeException

Hey i'm building a chat application, I was previously using regular sockets for communications but want to add encryption so I've switched over to SSL sockets. However since switching to SSL sockets as soon as I go to send a message I receive a SSLHandshakeException, can anyone give me any clues as to why this is happening?
Below is the ServerConnection class:
import javax.net.ssl.SSLServerSocket
import javax.net.ssl.SSLServerSocketFactory
import java.net.Socket
import java.net.ServerSocket
import java.io._
import scala.io._
class ServerConnection(port: Int) {
def connect(): Socket = {
val factory = SSLServerSocketFactory.getDefault()
val serverSocket = factory.createServerSocket(port)
serverSocket.accept()
}
def getMsg(client: Socket): String = new BufferedSource(client.getInputStream()).getLines().next()
def sendMsg(client: Socket, msg: String): Unit = {
val out = new PrintStream(client.getOutputStream())
out.println(msg)
out.flush()
}
def close(client: Socket): Unit = client.close()
Below is the ClientConnection class:
import javax.net.ssl.SSLSocket
import javax.net.ssl.SSLSocketFactory
import javax.net.SocketFactory
import java.net.Socket
import java.net.InetAddress
import java.net.InetSocketAddress
import java.io._
import scala.io._
import java.util.Calendar
class ClientConnection(host: InetAddress, port: Int) {
def connect(): Socket = {
val sslfactory = SSLSocketFactory.getDefault()
val sslsocket = sslfactory.createSocket(host, port)
sslsocket
}
def getMsg(server: Socket): String = new BufferedSource(server.getInputStream()).getLines().next()
def sendMsg(server: Socket, user: User, msg: String): Unit = {
val out = new PrintStream(server.getOutputStream())
out.println(this.getCurrDate() + " " + user.getUsername() + ": " + msg)
out.flush()
}
def getCurrDate(): String = "(" + Calendar.getInstance().getTime().toString().substring(11, 19) + ")"
def close(server: Socket): Unit = server.close()
}
EDIT: Below is the full stack trace
javax.net.ssl.SSLException: Connection has been shutdown: javax.net.ssl.SSLHands
hakeException: Received fatal alert: handshake_failure
at sun.security.ssl.SSLSocketImpl.checkEOF(Unknown Source)
at sun.security.ssl.AppInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at scala.io.BufferedSource$BufferedLineIterator.next(BufferedSource.scal
a:78)
at scala.io.BufferedSource$BufferedLineIterator.next(BufferedSource.scal
a:66)
at ClientConnection.getMsg(ClientConnection.scala:20)
at Client$.main(Client.scala:20)
at Client.main(Client.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at scala.reflect.internal.util.ScalaClassLoader$$anonfun$run$1.apply(Sca
laClassLoader.scala:70)
at scala.reflect.internal.util.ScalaClassLoader$class.asContext(ScalaCla
ssLoader.scala:31)
at scala.reflect.internal.util.ScalaClassLoader$URLClassLoader.asContext
(ScalaClassLoader.scala:101)
at scala.reflect.internal.util.ScalaClassLoader$class.run(ScalaClassLoad
er.scala:70)
at scala.reflect.internal.util.ScalaClassLoader$URLClassLoader.run(Scala
ClassLoader.scala:101)
at scala.tools.nsc.CommonRunner$class.run(ObjectRunner.scala:22)
at scala.tools.nsc.ObjectRunner$.run(ObjectRunner.scala:39)
at scala.tools.nsc.CommonRunner$class.runAndCatch(ObjectRunner.scala:29)
at scala.tools.nsc.ObjectRunner$.runAndCatch(ObjectRunner.scala:39)
at scala.tools.nsc.MainGenericRunner.runTarget$1(MainGenericRunner.scala
:65)
at scala.tools.nsc.MainGenericRunner.run$1(MainGenericRunner.scala:87)
at scala.tools.nsc.MainGenericRunner.process(MainGenericRunner.scala:98)
at scala.tools.nsc.MainGenericRunner$.main(MainGenericRunner.scala:103)
at scala.tools.nsc.MainGenericRunner.main(MainGenericRunner.scala)
Caused by: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_
failure
at sun.security.ssl.Alerts.getSSLException(Unknown Source)
at sun.security.ssl.Alerts.getSSLException(Unknown Source)
at sun.security.ssl.SSLSocketImpl.recvAlert(Unknown Source)
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source
)
at sun.security.ssl.SSLSocketImpl.writeRecord(Unknown Source)
at sun.security.ssl.AppOutputStream.write(Unknown Source)
at java.io.PrintStream.write(Unknown Source)
at sun.nio.cs.StreamEncoder.writeBytes(Unknown Source)
at sun.nio.cs.StreamEncoder.implFlushBuffer(Unknown Source)
at sun.nio.cs.StreamEncoder.flushBuffer(Unknown Source)
at java.io.OutputStreamWriter.flushBuffer(Unknown Source)
at java.io.PrintStream.write(Unknown Source)
at java.io.PrintStream.print(Unknown Source)
at java.io.PrintStream.println(Unknown Source)
at ClientConnection.sendMsg(ClientConnection.scala:24)
at Client$.main(Client.scala:19)
... 19 more

How to resolve exception in thread “main” javax.naming.NameNotFoundException: not bound?

I'm trying to create a jms publisher/subscriber chat application in eclipse.
import java.util.Properties;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicSession;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class TopicConsumer implements MessageListener {
public static void main(String[] args) throws JMSException, NamingException {
System.out.println(".....Entering JMS example TopicConsumer....");
Context context = TopicConsumer.getInitialContext();
TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) context.lookup("ConnectionFactory");
Topic topic = (Topic) context.lookup("topic/zaneacademy_jms_tutorial_01");
TopicConnection topicConnection = topicConnectionFactory.createTopicConnection();
TopicSession topicSession = topicConnection.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);
topicSession.createSubscriber(topic).setMessageListener(new TopicConsumer());
topicConnection.start();
System.out.println("......Exiting JMS Example TopicConsumer.....");
}
public void onMessage(Message message) {
try {
System.out.println("Incoming Messages: " + ((TextMessage)message).getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
public static Context getInitialContext() throws JMSException, NamingException {
Properties props = new Properties();
props.setProperty("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
props.setProperty("java.naming.factory.url.pkgs", "org.jboss.naming");
props.setProperty("java.naming.provider.url", "localhost:1099");
Context context = new InitialContext(props);
return context;
}
}
trying to run the program I'm getting the following errors in console
.....Entering JMS example TopicConsumer....
Exception in thread "main" javax.naming.NameNotFoundException: zaneacademy_jms_tutorial_01 not bound
at org.jnp.server.NamingServer.getBinding(NamingServer.java:564)
at org.jnp.server.NamingServer.getBinding(NamingServer.java:572)
at org.jnp.server.NamingServer.getObject(NamingServer.java:578)
at org.jnp.server.NamingServer.lookup(NamingServer.java:317)
at org.jnp.server.NamingServer.lookup(NamingServer.java:291)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.rmi.server.UnicastServerRef.dispatch(Unknown Source)
at sun.rmi.transport.Transport$1.run(Unknown Source)
at sun.rmi.transport.Transport$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Unknown Source)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(Unknown Source)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(Unknown Source)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(Unknown Source)
at sun.rmi.transport.StreamRemoteCall.executeCall(Unknown Source)
at sun.rmi.server.UnicastRef.invoke(Unknown Source)
at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(Unknown Source)
at java.rmi.server.RemoteObjectInvocationHandler.invoke(Unknown Source)
at com.sun.proxy.$Proxy0.lookup(Unknown Source)
at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:669)
at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:629)
at javax.naming.InitialContext.lookup(Unknown Source)
at TopicConsumer.main(TopicConsumer.java:19)
As it says in the exception the zaneacademy_jms_tutorial_01 is not defined.
You need to configure it and assigne it to the topic/zaneacademy_jms_tutorial_01.
I would say, that the problem is your getInitialContext() which you configure mannaully, instead of returing the probably already configured context by new InitialContext();

Is it possible to run an application from the Command Line and reference a .jar file too?

I have a simple java application that i've got running in Netbeans, show below. i've added the sqlite-jdbc.jar in Netbeans to access the database but i'd like to know if i can use the .jar from the Command Prompt and if so how? Thanks.
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;
import java.sql.*;
import javax.swing.*;
/**
*
* #author James
*/
public class TestProj{
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
ConnectDb();
}
public static Connection ConnectDb(){
try
{
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:
C:\\Users\\James\\Documents
\\NetBeansProjects\\TestProj\\TestProj.sqlite");
System.out.println("Connection opened successfully!");
Statement stat = conn.createStatement();
String sql = "SELECT kE100 FROM customers" +
" WHERE phoneNo = 873333333";
ResultSet rs = stat.executeQuery(sql);
System.out.println("name = " + rs.getString("kE100"));
conn.close();
return conn;
}catch(Exception e){
System.out.println("No Connection!");
return null;
}
}
}
C:\Users\James\Documents\NetBeansProjects\TestKamarad\src\testkamarad>javac -cp
"C:/Users/James/Desktop/Installers Etc/sqlite-jdbc-3.7.2.jar;" TestKamarad.java
C:\Users\James\Documents\NetBeansProjects\TestKamarad\src\testkamarad>java -cp "
C:/Users/James/Desktop/Installers Etc/sqlite-jdbc-3.7.2.jar;" TestKamarad
Exception in thread "main" java.lang.NoClassDefFoundError: TestKamarad (wrong na
me: testkamarad/TestKamarad)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
How to run a .jar from commandline ? It's pretty simple, just type in:
java -jar foo\bar.jar

Mongodb connection fails when selecting or inserting with java

I'm using mongo-java-driver-2.11.3.jar and also tried with mongo-2.10.1.jar both are giving the following error.The database is
connected but the collection insert and selection are not working.
import java.net.UnknownHostException;
import java.util.Set;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
public class mongo_test {
public MongoClient mongo = null;
public DB mongodb = null;
private void mongo_startconnection() {
try {
mongo = new MongoClient("10.0.2.15", 27017);
mongodb = mongo.getDB("foobar");
System.out.println("Mongodb is connected");
BasicDBObject doc = new BasicDBObject();
DBCollection collection = mongodb.getCollection("url_ta");
Set<String> colls = mongodb.getCollectionNames();
for (String s : colls) {
System.out.println(s);
}
System.out.println("done");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e1) {
e1.printStackTrace();
}
}
public static void main(String args[]) {
mongo_test MT = new mongo_test();
MT.mongo_startconnection();
}
}
I'm getting this error:
Mongodb is connected
Nov 26, 2013 11:34:39 AM com.mongodb.DBTCPConnector initDirectConnection
WARNING: Exception executing isMaster command on /10.0.2.15:27017
java.net.SocketTimeoutException: connect timed out
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at com.mongodb.DBPort._open(DBPort.java:223)
at com.mongodb.DBPort.go(DBPort.java:125)
at com.mongodb.DBPort.go(DBPort.java:106)
at com.mongodb.DBPort.findOne(DBPort.java:162)
at com.mongodb.DBPort.runCommand(DBPort.java:170)
at com.mongodb.DBTCPConnector.initDirectConnection(DBTCPConnector.java:547)
at com.mongodb.DBTCPConnector.checkMaster(DBTCPConnector.java:526)
at com.mongodb.DBTCPConnector.innerCall(DBTCPConnector.java:236)
at com.mongodb.DBTCPConnector.call(DBTCPConnector.java:216)
at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:288)
at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:273)
at com.mongodb.DB.getCollectionNames(DB.java:400)
at mongo_test.mongo_startconnection(mongo_test.java:29)
at mongo_test.main(mongo_test.java:69)
com.mongodb.MongoException$Network: Read operation to server /10.0.2.15:27017 failed on database foobar at com.mongodb.DBTCPConnector.innerCall(DBTCPConnector.java:253)
at com.mongodb.DBTCPConnector.call(DBTCPConnector.java:216)
at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:288)
at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:273)
at com.mongodb.DB.getCollectionNames(DB.java:400)
at mongo_test.mongo_startconnection(mongo_test.java:29)
at mongo_test.main(mongo_test.java:69)
Caused by: java.net.SocketTimeoutException: connect timed out
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at com.mongodb.DBPort._open(DBPort.java:223)
at com.mongodb.DBPort.go(DBPort.java:125)
at com.mongodb.DBPort.call(DBPort.java:92)
at com.mongodb.DBTCPConnector.innerCall(DBTCPConnector.java:244)
... 6 more
1.Trying to find out whether your ip address and port number is reachable.
use command: telnet 10.0.2.15",27017 to check if such a port for this ip is open for connection.
2.If you have the authority to login the mongodb server ,just login and then:
If your mongodb is a cluster , Use commmand : ps -ef|grep mongos to check the mongodb server instance is up and the port is just
27017.
if your mongodb is just a single machine ,use ps -ef|grep mongod to make the same check.
package raamji.com.start;
//import com.mongodb.MongoClient;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
public class Start {
public static void main(String[] args) throws UnknownHostException {
//crete Connection
Mongo mongoClient = new Mongo("ind-asingh", 27017);//or "localhost",27017
System.out.println("mongoClient :" + mongoClient);
DB db = mongoClient.getDB("DB Name");//e.g. MYDB
System.out.println("db :" + db);
//---------------------------Access your Collection-----------------------------
DBCollection collection = db.getCollection("message");
System.out.println("collection :" + collection);
System.out.println("Message Count: " + collection.getCount());
DBCursor cursor = collection.find();
try {
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
}//end pf psvm
}//end of class

Categories