I have hit an issue and I am unsure as to where it is going wrong. I am establishing an SSH connection to my remote server and from there I am trying to access a MySQL Database. The SSH connection connects properly however, when attempting to access the MySQL db I keep getting an error.
I have searched beyond belief for almost a week before running for help
UPDATE!!!
Alright so I have been able to pull this down to being something to do with JSCH. I established an SSH connection using putty externally and ran the code without actually using JSCH to make the SSH connection and I was able to access teh DB entirely. At this point any help with JSCH would be very helpful.
int lport=3306;
String rhost="SERVERNAME";
String host="SERVERNAME";
int rport=3306;
String user="USERNAME";
String password="SSHPass";
String dbuserName = "DBUSER";
String dbpassword = "DBPWD";
String url = "jdbc:mysql://localhost:3306/dbname";
String driverName="com.mysql.jdbc.Driver";
Connection conn = null;
Session session= null;
try{
//Set StrictHostKeyChecking property to no to avoid UnknownHostKey issue
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
session=jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig(config);
session.connect();
System.out.println("Connected");
int assinged_port=session.setPortForwardingL(lport, rhost, rport);
System.out.println("localhost:"+assinged_port+" -> "+rhost+":"+rport);
System.out.println("Port Forwarded");
//mysql database connectivity
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, dbuserName, dbpassword);
System.out.println ("Database connection established");
System.out.println("DONE");
}catch(Exception e){
e.printStackTrace();
}finally{
if(conn != null && !conn.isClosed()){
System.out.println("Closing Database Connection");
conn.close();
}
if(session !=null && session.isConnected()){
System.out.println("Closing SSH Connection");
session.disconnect();
}
}
com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception:
** BEGIN NESTED EXCEPTION **
com.mysql.jdbc.CommunicationsException
MESSAGE: Communications link failure due to underlying exception:
** BEGIN NESTED EXCEPTION **
java.io.EOFException
MESSAGE: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.
STACKTRACE:
java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.
at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:1997)
at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:573)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1044)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2775)
at com.mysql.jdbc.Connection.<init>(Connection.java:1555)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at Data.SQLConnection.getConnection(SQLConnection.java:49)
at finalproject.Dashboard.jButton1ActionPerformed(Dashboard.java:391)
at finalproject.Dashboard.access$200(Dashboard.java:37)
at finalproject.Dashboard$4.actionPerformed(Dashboard.java:221)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6525)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6290)
at java.awt.Container.processEvent(Container.java:2234)
at java.awt.Component.dispatchEventImpl(Component.java:4881)
at java.awt.Container.dispatchEventImpl(Container.java:2292)
at java.awt.Component.dispatchEvent(Component.java:4703)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
at java.awt.Container.dispatchEventImpl(Container.java:2278)
at java.awt.Window.dispatchEventImpl(Window.java:2750)
at java.awt.Component.dispatchEvent(Component.java:4703)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Any assistance would be greatly appreciated.
WOOOOO I got it working! So what I did (and I have no idea why this works) is I just created a new Class that establishes the SSH connection with JSCH. I then put all the fun SQL stuff in another. From my dashboard gui under the connect event handler I added the JSCH connection first and after that I connect to the SQL DB.
Thank you everyone for all of your help! You are all awesome!
Related
I am trying to figure out why my app has trouble connecting to my database, only on mac OS so I'm using a small program to run on terminal on OS to see what was causing that.
It seems the hostname is causing the issue, but my service provider cannot give me an ip address to try if it fixes my issue. Does anyone have a fix for this or an idea on what I could try? Thanks a lot for your time.
here is the connection program. the database user can select only, the hostname is correct and password as well. This issue only happens on MAC OS and not all the time. My database accepts conneciton from all ip, I used a wildcard. Any idea on what to try next is appreciated.
import java.sql.Connection;
import java.sql.DriverManager;
public class test
{
public static void main(String[] args) {
System.out.println("\nMySQL JDBC Connection To G4THER DBase Tester");
Connection conn = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
String userName = "app";
String password = "password";
String url = "jdbc:mysql://hostname:3306/dbase";
conn = DriverManager.getConnection(url, userName, password);
System.out.println("\nDatabase Connection Established...");
Thread.sleep(1500L);
}
catch (Exception ex) {
System.err.println("Cannot connect to database server");
ex.printStackTrace();
}
finally {
if (conn != null)
try {
System.out.println("\nNow Lets terminate the Connection...");
Thread.sleep(1500L);
conn.close();
System.out.println("\nDatabase connection terminated...");
Thread.sleep(1500L);
System.out.println("\n***** Everything works fine Ol' man *****");
}
catch (Exception ex) {
System.out.println("Error in connection termination!");
}
}
}
}
here is the error log.
Last login: Thu Dec 12 12:25:13 on ttys000
Michaels-iMac:~ michael$ cd downloads
Michaels-iMac:downloads michael$ java -jar dbasetester.jar
***** MySQL JDBC Connection To G4THER DBase Tester *****
Cannot connect to database server
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:836)
at com.mysql.cj.jdbc.ConnectionImpl.(ConnectionImpl.java:456)
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246)
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:199)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:677)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
at test.main(test.java:18)
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 java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
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:144)
at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:956)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:826)
... 6 more
Caused by: java.net.UnknownHostException: cpl81.hosting24.com: nodename nor servname provided, or not known
at java.base/java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
at java.base/java.net.InetAddress$PlatformNameService.lookupAllHostAddr(InetAddress.java:930)
at java.base/java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1499)
at java.base/java.net.InetAddress$NameServiceAddresses.get(InetAddress.java:849)
at java.base/java.net.InetAddress.getAllByName0(InetAddress.java:1489)
at java.base/java.net.InetAddress.getAllByName(InetAddress.java:1348)
at java.base/java.net.InetAddress.getAllByName(InetAddress.java:1282)
at com.mysql.cj.protocol.StandardSocketFactory.connect(StandardSocketFactory.java:132)
at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:65)
... 9 more
Michaels-iMac:downloads michael$
thanks
I was able to fix the issue using an IP address instead of the hostname. I used a site to find the IP with the hostname and changed my code. So far so good.
I'm using NetBeans 8.2 connecting to SQL server 2012 through the sqljdbc4.jar driver.
I create an interface java class named Provider:
public interface Provider {
String driver="com.microsoft.sqlserver.jdbc.SQLServerDriver";
String url="jdbc:sqlserver://DESKTOP-MF8EEF8;DatabaseName=db_Class_Payment;integrated Security=false;";
String username="sa;";
String password="123;";
}
and then I call Provider into the connection class named DBFactory.
public class DBFactory {
static Connection con;
static
{
try
{
Class.forName(driver);
con = DriverManager.getConnection(url,username,password);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static Connection getcon()
{
return con;
}
}
And then I test with this below code:
if(con==null){
JOptionPane.showMessageDialog(null, "Connecting failed");
}else{
JOptionPane.showMessageDialog(null, "Connecting successfully.");
}
the process gives me with connecting failed or connection null with error msg;
com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host DESKTOP-MF8EEF8, port 1433 has failed. Error: "Connection refused: connect. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.".
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:190)
at com.microsoft.sqlserver.jdbc.SQLServerException.ConvertConnectExceptionToSQLServerException(SQLServerException.java:241)
at com.microsoft.sqlserver.jdbc.SocketFinder.findSocket(IOBuffer.java:2243)
at com.microsoft.sqlserver.jdbc.TDSChannel.open(IOBuffer.java:491)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1309)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:991)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:827)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1012)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at Class.DBFactory.<clinit>(DBFactory.java:18)
at Frame.Home.<init>(Home.java:16)
at Frame.Home$4.run(Home.java:449)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
BUILD SUCCESSFUL (total time: 23 seconds)
I already and library sqljdbc4.jar to the libraries in project.
It is still giving error result.
Your connection url is wrong.
integrated Security=false;
It should be
integratedSecurity=false;
Read the Building the Connection URL to get better.
This question already has answers here:
Java JDBC Access denied for user [closed]
(4 answers)
Closed 5 years ago.
I am newbie with java and i need help with how to create connection pool for JDBC in my java application project.
I have been able to connect to my database but the performance of my application is slow since i call on the connection on every frame as i saw on a lots of video tutorials on youtube.
This is how i connect to the database. I call on the connection in every frame like DBConnection.getConnectDB() in most of my frame.
How can i create a JDBC connection pool for java in netbeans. Thank you
DBConnect
public class DBConnection {
public static Connection ConnectDB(){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://server/db_name","user","pass");
System.out.println("Connected");
return conn;
}
catch(Exception ex){
JOptionPane.showMessageDialog(null, ex);
return null;
}}
}
update
public static Connection ConnectDB(){
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://localhost:3306/simpsons");
config.setUsername("username");
config.setPassword("pass");
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
HikariDataSource ds = new HikariDataSource(config);
return (Connection) new HikariDataSource(config);
}
}
Console
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Exception in thread "AWT-EventQueue-0" com.zaxxer.hikari.pool.HikariPool$PoolInitializationException: Failed to initialize pool: Access denied for user 'qweqsbra_wagyingo'#'197.251.142.100' (using password: YES)
at com.zaxxer.hikari.pool.HikariPool.throwPoolInitializationException(HikariPool.java:543)
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:535)
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:111)
at com.zaxxer.hikari.HikariDataSource.<init>(HikariDataSource.java:72)
at wagyingohostel.DBConnection.DBConnection.ConnectDB(DBConnection.java:41)
at wagyingohostel.LoginAndRegistration.Login.<init>(Login.java:34)
at wagyingohostel.LoginAndRegistration.Login$4.run(Login.java:228)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Caused by: java.sql.SQLException: Access denied for user 'qweqsbra_wagyingo'#'197.251.142.100' (using password: YES)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:873)
at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1710)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1226)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2198)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2229)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2024)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:779)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
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.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:389)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:330)
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:112)
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:118)
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:358)
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:201)
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:443)
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:514)
... 19 more
BUILD SUCCESSFUL (total time: 20 seconds)
If you are using maven or gradle (you should be) you can use a pool like HikariCP and create a jdbc connection pool like this.
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://localhost:3306/simpsons");
config.setUsername("bart");
config.setPassword("51mp50n");
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
HikariDataSource ds = new HikariDataSource(config);
Here is a more detailed example configuring multiple hikaricp pools
You need to Configuring JNDI DataSource for Database Connection Pooling in Netbeans.Please follow the the steps mentioned in below URL to create a connection pool using Netbeans ID
https://dzone.com/articles/nb-class-glassfish-mysql-jdbc
I cannot tell if its a credentials/SSL issue or an LDAP configuration issue on the server. I tried accessing the local version and i had no problem (then again local Ldap and server setup is a little different). The socket is definitely not closed as we are using that url in our processing system and it is not down.
Code is failing at this line:
NamingEnumeration<?> namingEnum = ctx.search("dc=barney,dc=com", "(objectclass=person)", getSimpleSearchControls());
Code block:
final String ldapAdServer = "ldap://myspecialhost.barney.us:389";
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, ldapAdServer);
LdapContext ctx = new InitialLdapContext(env, null);
ctx.setRequestControls(null);
NamingEnumeration<?> namingEnum = ctx.search("dc=barney,dc=com", "(objectclass=person)", getSimpleSearchControls());
And the stacktrace is here:
javax.naming.ServiceUnavailableException: tiffany.barney.ca:389; socket closed; remaining name 'dc=barney,dc=com'
at com.sun.jndi.ldap.Connection.readReply(Connection.java:437)
at com.sun.jndi.ldap.LdapClient.getSearchReply(LdapClient.java:613)
at com.sun.jndi.ldap.LdapClient.search(LdapClient.java:536)
at com.sun.jndi.ldap.LdapCtx.doSearch(LdapCtx.java:1965)
at com.sun.jndi.ldap.LdapCtx.searchAux(LdapCtx.java:1827)
at com.sun.jndi.ldap.LdapCtx.c_search(LdapCtx.java:1752)
at com.sun.jndi.toolkit.ctx.ComponentDirContext.p_search(ComponentDirContext.java:368)
at com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.search(PartialCompositeDirContext.java:338)
at com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.search(PartialCompositeDirContext.java:321)
at javax.naming.directory.InitialDirContext.search(InitialDirContext.java:248)
at com.barney.shopping.tiffany.LDAPImpTest.main(LDAPImplTest.java:154)
EDIT 1:
I tried using a different url and i get a connection timed out. Does this new url seem more right and i'm getting closer to the correct url perhaps?
EDIT 2:
new stacktrace
javax.naming.CommunicationException: possibleURL:389 [Root exception is java.net.ConnectException: Connection timed out: connect]
at com.sun.jndi.ldap.Connection.<init>(Connection.java:209)
at com.sun.jndi.ldap.LdapClient.<init>(LdapClient.java:116)
at com.sun.jndi.ldap.LdapClient.getInstance(LdapClient.java:1582)
at com.sun.jndi.ldap.LdapCtx.connect(LdapCtx.java:2678)
at com.sun.jndi.ldap.LdapCtx.<init>(LdapCtx.java:296)
at com.sun.jndi.ldap.LdapCtxFactory.getUsingURL(LdapCtxFactory.java:175)
at com.sun.jndi.ldap.LdapCtxFactory.getUsingURLs(LdapCtxFactory.java:193)
at com.sun.jndi.ldap.LdapCtxFactory.getLdapCtxInstance(LdapCtxFactory.java:136)
at com.sun.jndi.ldap.LdapCtxFactory.getInitialContext(LdapCtxFactory.java:66)
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:667)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
at javax.naming.InitialContext.init(InitialContext.java:223)
at javax.naming.ldap.InitialLdapContext.<init>(InitialLdapContext.java:134)
at blablalbla.LDAPInterfaceTest.main(LDAPInterfaceTest.java:154)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at java.net.Socket.<init>(Socket.java:375)
at java.net.Socket.<init>(Socket.java:189)
at com.sun.jndi.ldap.Connection.createSocket(Connection.java:351)
at com.sun.jndi.ldap.Connection.<init>(Connection.java:186)
... 13 more
I want to check the status code of request to url but getting code
java.net.ConnectException: connect: Address is invalid on local machine or port is not valid on remote machine
here is my code
public static boolean linkExists(String URLName){
URLName = "http://www.google.com";
try {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con =
(HttpURLConnection) new URL(URLName).openConnection();
con.connect();
System.out.println(con.getResponseCode());
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
}
catch (Exception e) {
return false;
}
}
stack trace
java.net.ConnectException: connect: Address is invalid on local machine, or port is not valid on remote machine
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at sun.net.NetworkClient.doConnect(NetworkClient.java:180)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:378)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:473)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:203)
at sun.net.www.http.HttpClient.New(HttpClient.java:290)
at sun.net.www.http.HttpClient.New(HttpClient.java:306)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:995)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:931)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:849)
at com.sls.lms.test.utilities.Utilities.linkExists(Utilities.java:70)
at com.sls.lms.test.report.ReportTest.checkReportData(ReportTest.java:70)
at com.sls.lms.test.report.ReportTest.CheckReportForGST(ReportTest.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
at org.junit.runner.JUnitCore.run(JUnitCore.java:138)
at org.testng.junit.JUnit4TestRunner.start(JUnit4TestRunner.java:81)
at org.testng.junit.JUnit4TestRunner.run(JUnit4TestRunner.java:69)
at org.testng.TestRunner$1.run(TestRunner.java:682)
at org.testng.TestRunner.runWorkers(TestRunner.java:1012)
at org.testng.TestRunner.privateRunJUnit(TestRunner.java:713)
at org.testng.TestRunner.run(TestRunner.java:614)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
at org.testng.SuiteRunner.run(SuiteRunner.java:240)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1198)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1123)
at org.testng.TestNG.run(TestNG.java:1031)
at org.testng.TestNG.privateMain(TestNG.java:1338)
at org.testng.TestNG.main(TestNG.java:1307)
I believe that this issue is caused by Java attempting to use an IPV6 address, when either your OS doesn't support it, or is not set up properly to handle it.
You can force Java to use an IPV4 address with the following property:
-Djava.net.preferIPv4Stack=true
One thing I notice is that your URL connection has not been used... you haven't called connect(). I would be disappointed in the error message if that fixed your problem, but you probably can't get a response code until after you have made a request.
http://docs.oracle.com/javase/6/docs/api/java/net/URLConnection.html
Works fine for me with Eclipse. Definitely take Nikolay's advice and check if you have a firewall running. Any forum post I have seen related to this exception have been related somehow to this situation.
Close all java programs and open up run (winkey + R) or just search run if you have a start button like me, and write -Djava.net.preferIPv4Stack=true in. :)
Encountered this problem but just shutdown my antivirus and phew it is working, this has to do with the antivirus blocking the ports.
i faced the same problem.
i have windows8 64 use netbeans7.4.
my antivirus is kaspersky. the solution is to
turn of your antivirus or make the antivirus pause then run the code it will work
import java.net.*;
import java.io.*;
public class URLReader {
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://www.oracle.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
I have faced the same problem.My anitvirus is kaspersky.the solution for this is,open kapsperksy->settings->Anti virus protection->moinitored ports->select
I got this message when trying to open Socket with IPv4 address and Port 0. May be you should check the port used when you see this message.
I was creating a socket connection to a remote server by providing IP address and port number of the server. Was able to ping the server and was also able to telnet to the port. So no connectivity issues, still got same error posted in the question.
I made a silly mistake of passing in an empty string to creating the socket instance. It is useful to use debug mode to point out such mistakes.