I'm receiving java socket programming exception. This is a code from the Book "Java Complete reference Oracle"
import java.net.*;
import java.io.*;
public class Whois {
public static void main(String[] args)throws Exception{
int c;
Socket s = new Socket("whois.internic.net",43);
InputStream in = s.getInputStream();
OutputStream out = s.getOutputStream();
String str = (args.length == 0 ? "OraclePressBooks.com" : args[0]) + "\n";
byte buf[] = str.getBytes();
out.write(buf);
while((c=in.read())!=-1)
{
System.out.println((char)c);
}
s.close();
}
}
I'm getting following exception. But Why?
Exception in thread "main" 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 java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at Whois.main(Whois.java:8)
P.S. I'm using Eclipse Photon. I tried running eclipse "as administrator" and also without it.
You do not have network connectivity to remote TCP port 43.
But since you've written that you have "proper network connection" because you are "using WiFi", we may suppose you have at least a web access (through a transparent proxy, or direct connections).
Therefore, you can simply use a Whois web service to access Whois databases.
Some registrars offer a RWS-DNRD endpoint, that is a RESTful Web Service for Domain Name Registration Data (https://tools.ietf.org/id/draft-sheng-weirds-icann-rws-dnrd-01.html). You will find many examples of RESTful clients, for instance here: https://www.javacodegeeks.com/2012/09/simple-rest-client-in-java.html
In your case, you want to access the Internic database, so you can simply query their web form, using a GET request, like that (Java 9):
URL u = new URL("https://reports.internic.net/cgi/whois?whois_nic=OraclePressBooks.com&type=domain");
try (InputStream in = u.openStream()) {
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
}
Related
If the zip code is provided as an input, then corresponding city temperature will be returned as output. Here is my code:
public class IPLocationFinder {
public static void main(String[] args) {
String zipCode = args[0];
Weather service = new Weather();
WeatherSoap weatherSoap = service.getWeatherSoap();
WeatherReturn weatherSoap2 = weatherSoap.getCityWeatherByZIP(zipCode);
System.out.println("The Temperature is" + weatherSoap2.getTemperature());
}
}
I get the following error while executing the above code.
Exception in thread "main" com.sun.xml.internal.ws.fault.ServerSOAPFaultException:
Client received SOAP Fault from server: Server was unable to process request. ---> A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) Please see the server log to find more detail regarding exact cause of the failure.
at com.sun.xml.internal.ws.fault.SOAP11Fault.getProtocolException(Unknown Source)
at com.sun.xml.internal.ws.fault.SOAPFaultBuilder.createException(Unknown Source)
at com.sun.xml.internal.ws.client.sei.StubHandler.readResponse(Unknown Source)
at com.sun.xml.internal.ws.db.DatabindingImpl.deserializeResponse(Unknown Source)
at com.sun.xml.internal.ws.db.DatabindingImpl.deserializeResponse(Unknown Source)
at com.sun.xml.internal.ws.client.sei.SyncMethodHandler.invoke(Unknown Source)
at com.sun.xml.internal.ws.client.sei.SyncMethodHandler.invoke(Unknown Source)
at com.sun.xml.internal.ws.client.sei.SEIStub.invoke(Unknown Source)
at com.sun.proxy.$Proxy31.getCityWeatherByZIP(Unknown Source)
at com.kaushik.javabrains.IPLocationFinder.main(IPLocationFinder.java:19)
The error happens at the below line. Please suggest.
WeatherReturn weatherSoap2 = weatherSoap.getCityWeatherByZIP(zipCode);
I'm using two H2 databases in my Java projects. Recently, I changed my computer and since then I have no problem with connecting to one of those databases using my Java code but problems with the other one. It's exactly the same code (up to PATH_TO_DATABASE) I use to start the connection:
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConfig {
private static java.sql.Connection connection;
public static void init() {
if (connection == null) {
try {
connection = DriverManager.getConnection("jdbc:h2:tcp://192.168.178.50:9092/C:/Users/PATH_TO_DATABASE", "USER", "PW");
} catch (SQLException e) {
System.err.println("SQLException");
e.printStackTrace();
System.exit(0);
}
}
}
[...]
}
This is the stack trace I get:
SQLException
org.h2.jdbc.JdbcSQLException: Connection is broken: "java.net.SocketTimeoutException: connect timed out: 192.168.178.21:9092" [90067-196]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
at org.h2.message.DbException.get(DbException.java:168)
at org.h2.engine.SessionRemote.connectServer(SessionRemote.java:457)
at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:334)
at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:116)
at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:100)
at org.h2.Driver.connect(Driver.java:69)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at data.DatabaseConfig.init(DatabaseConfig.java:20)
...
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 org.h2.util.NetUtils.createSocket(NetUtils.java:103)
at org.h2.util.NetUtils.createSocket(NetUtils.java:83)
at org.h2.engine.SessionRemote.initTransfer(SessionRemote.java:115)
at org.h2.engine.SessionRemote.connectServer(SessionRemote.java:453)
... 8 more
Using the web interface I can connect to both databases easily.
I'm a little bit lost here since I can't figure out what's going wrong with one of the databases. The strange thing is that everything works fine with the other database.
EDIT: I just realized that the IP address in the error message is different from the one in the code (192.168.178.21:9092 vs. 192.168.178.50:9092). Maybe this is th ereason of the error. The one in the code is the correct IP address. Why do I get a different one in the error message? Is that the reason of my problem?
If it's a remote connection, do an ipconfig to find out if the 192.168.x.x. address is changed.
If it's a local connection, you can simplify your URL as
jdbc:h2:~/PATH_TO_DATABASE
I just solved the problem (it was kind of my stupidity): The project couldn't build on the new computer because the H2 jar was not properly included in the build path. That's why eclipse called all the time the old .class file and hence tried to connect to the old computer (192.168.178.21:9092) instead to the new one (192.168.178.50:9092). I didn't realize that eclipse didn't compile and was executing old stuff.
I copied the sample program from Oracle Docs and I am running it "as is" in Eclipse.
However, every time run it I get a ConnectionException. Do I need to configure anything else? Also, my understanding on this matter is quite weak, could you please recommend beginner guide regarding Java Web programming.
The code is
public class Test {
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://www.oracle.com/");
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
And the exception I am getting is
Exception in thread "main" java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at Test.main(Test.java:9)
I am able to access http://www.oracle.com via chrome and I have internet access. If it is the firewall issue, could anyone please tell me how do I solve this firewall issue?
I have taken your code, and run it locally in my eclipse environment. It works and produces output like:
<!DOCTYPE html>
<html lang="en-US" class="no-js">
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
var _U = "undefined";
var g_HttpRelativeWebRoot = "/ocom/";
var SSContributor = false;
var SSForceContributor = false;
var SSHideContributorUI = false;
var ssUrlPrefix = "/us/";
var ssUrlType = "2";
var g_navNode_Path = new Array();
g_navNode_Path[0] = '8';
var g_ssSourceNodeId = "8";
var g_ssSourceSiteId = "ocomen";
</script>
.....
This leaves a problem, because the failure is not part of your program, but part of your environment.
As I was typing this answer, you added that you have proxy settings.
You should add -Djava.net.useSystemProxies=true to the run box for your application, or add:
System.setProperty("java.net.useSystemProxies", "true");
on the first line of your main method. This is documented here:
java.net.useSystemProxies (default: false)
On recent Windows systems and on Gnome 2.x systems it is possible to
tell the java.net stack, setting this property to true, to use the
system proxy settings (both these systems let you set proxies globally
through their user interface). Note that this property is checked only
once at startup.
That should pull in the system proxy settings....
There are a number of factors which could apply:
Your network infrastructure does not allow your program to connect to the net directly. Many locations use proxy settings to get through firewalls, etc. Do you have a proxy for your browser? You can set the system property: java.net.useSystemProxies to true and hope that it will pull in the system properties.
Your windows personal firewall normally prompts you to let applications connect to the net. Have you denied/allowed your program to connect?
lots of other things....
There could
am trying to connect with active directory with the support of ssl.
i tried the steps from following web site.
http://confluence.atlassian.com/display/CROWD/Configuring+an+SSL+Certificate+for+Microsoft+Active+Directory
when i try to connect active directory from the java code it gives following error.
Exception in thread "main" javax.naming.CommunicationException: simple bind fail
ed: 172.16.12.4:636 [Root exception is java.net.SocketException: Connection rese
t]
at com.sun.jndi.ldap.LdapClient.authenticate(Unknown Source)
at com.sun.jndi.ldap.LdapCtx.connect(Unknown Source)
at com.sun.jndi.ldap.LdapCtx.<init>(Unknown Source)
at com.sun.jndi.ldap.LdapCtxFactory.getUsingURL(Unknown Source)
at com.sun.jndi.ldap.LdapCtxFactory.getUsingURLs(Unknown Source)
at com.sun.jndi.ldap.LdapCtxFactory.getLdapCtxInstance(Unknown Source)
at com.sun.jndi.ldap.LdapCtxFactory.getInitialContext(Unknown Source)
at javax.naming.spi.NamingManager.getInitialContext(Unknown Source)
at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.init(Unknown Source)
at javax.naming.InitialContext.<init>(Unknown Source)
at javax.naming.directory.InitialDirContext.<init>(Unknown Source)
at ConnectActiveDirectory.main(ConnectActiveDirectory.java:39)
Caused by: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at com.sun.net.ssl.internal.ssl.InputRecord.readFully(Unknown Source)
at com.sun.net.ssl.internal.ssl.InputRecord.read(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.waitForClose(Unknown Sourc
e)
at com.sun.net.ssl.internal.ssl.HandshakeOutStream.flush(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.kickstart(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.kickstartHandshake(Unknown
Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(Un
known Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.writeRecord(Unknown Source
)
at com.sun.net.ssl.internal.ssl.AppOutputStream.write(Unknown Source)
at java.io.BufferedOutputStream.flushBuffer(Unknown Source)
at java.io.BufferedOutputStream.flush(Unknown Source)
at com.sun.jndi.ldap.Connection.writeRequest(Unknown Source)
at com.sun.jndi.ldap.Connection.writeRequest(Unknown Source)
at com.sun.jndi.ldap.LdapClient.ldapBind(Unknown Source)
... 13 more
Code that am using is
import java.util.Hashtable;
import javax.naming.*;
import javax.naming.directory.*;
public class ConnectActiveDirectory {
public static void main(String[] args) throws NamingException {
Hashtable env = new Hashtable();
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL,"Administrator#mysite.com");
env.put(Context.SECURITY_CREDENTIALS, "password");
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldaps://172.16.12.4:636/cn=Users,dc=mysite,dc=com");
try{
java.io.InputStream in = new java.io.FileInputStream("C:\\client.crt");
java.security.cert.Certificate c = java.security.cert.CertificateFactory.getInstance("X.509").generateCertificate(in);
java.security.KeyStore ks = java.security.KeyStore.getInstance("JKS");
ks.load(null);
if (!ks.containsAlias("alias ldap")) {
ks.setCertificateEntry("alias ldap", c);
}
java.io.OutputStream out = new java.io.FileOutputStream("C:\\keystorefile.jks");
char[] kspass = "changeit".toCharArray();
ks.store(out, kspass);
out.close();
}catch(Exception e){
e.printStackTrace();
}
System.setProperty("javax.net.ssl.trustStore", "C:\\keystorefile.jks");
DirContext ctx = new InitialDirContext(env);
NamingEnumeration enm = ctx.list("");
while (enm.hasMore()) {
System.out.println(enm.next());
}
ctx.close();
}
}
does am doing any mistake?
where can i get good tutorial to do ssl connection with active directory ?
does http://confluence.atlassian.com/display/CROWD/Configuring+an+SSL+Certificate+for+Microsoft+Active+Directory site has correct steps to create and connect active directory with ssl?
could any on please help me.
I had a similar issue after my AD domain was renamed. After reinstalling certificate services, you need to delete and re-issue the certificate issued to your Domain Controller. Steps:
Open MMC
Add Snap In > Certificates > Computer > Local Computer
Navigate to Personal > Certificates
Delete any old certificates issued to this machine (in my case, these were issued by the old CA)
Right click on Certificates folder, click Request New Certificate.
Follow the steps to issue the new certificate to your domain controller.
Restart (not sure if this is necessary, but I restarted before it worked)
I had the same error message using Atlassian Crowd and Active Directory over SSL. It is not applicable to this specific question, but when I tried to find out what was happening this thread was the first Google search hit, so I will write it down here.
In my case I first tested without SSL and then changed to SSL. Turns out I forgot to change the protocol used in the Crowd Connector settings.
Before: ldap://:389
After: ldaps://:636
Accidentally using ldap://:636 gave me the "Connection reset" error.
I have a question/problem related to Java Applet security...
I use the Applet that has to take files from server (ASP.NET) and represent the information from it. Applet take files using the code:
URL u = new URL(getCodeBase(), filename);
BufferedReader d = new BufferedReader(new InputStreamReader(u.openStream()));
This code appears in two places:
Init() method
Some another method Test() that called manually from JavaScript
So, when I try to load the page with Applet using the URL http://127.0.0.1:8000/Test.aspx, everything works fine and I can read file content from both methods. But if I change the URL on http://localhost:8000/, only the first method works properly and I can get files content and for the second one I get the next error message in JavaConsole:
java.security.AccessControlException: access denied (java.net.SocketPermission 127.0.0.1:8000 connect,resolve)
What it the difference in this case? Why 'localhost' is impossible in this case? Is there any way how to grant access to 'localhost' the same as 127.0.0.1?
here is simplest applet's example:
public class TestApplet extends Applet {
public void init()
{
System.out.println( "init...");
readDocument();
}
public void readDocument()
{
System.out.println( "read test.txt file...");
URL base = getCodeBase();
String filename = "test.txt";
try {
URL u = new URL(base, filename);
BufferedReader d = new BufferedReader(new InputStreamReader(u.openStream()));
System.out.println(d.readLine());
System.out.println("Done!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
and next code used on the client side:
<applet archive="/Content/test.jar" code="test.TestApplet.class" name="testApplet" mayscript></applet>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
var testApplet = document.testApplet;
testApplet.readDocument();
});
</script>
this code works perfectly when I try to use http://127.0.0.1:8000/Test.aspx
and doesn't work when I user http://localhost:8000/Test.aspx. I java console I see the next:
init...
read test.txt file...
some text...
Done!
read test.txt file...
java.security.AccessControlException: access denied (java.net.SocketPermission 127.0.0.1:8000 connect,resolve)
at java.security.AccessControlContext.checkPermission(Unknown Source)
at java.security.AccessController.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkConnect(Unknown Source)
at sun.plugin2.applet.Applet2SecurityManager.checkConnect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at test.TestApplet.readDocument(TestApplet.java:30)
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.plugin.javascript.JSInvoke.invoke(Unknown Source)
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.plugin.javascript.JSClassLoader.invoke(Unknown Source)
at sun.plugin2.liveconnect.JavaClass$MethodInfo.invoke(Unknown Source)
at sun.plugin2.liveconnect.JavaClass$MemberBundle.invoke(Unknown Source)
at sun.plugin2.liveconnect.JavaClass.invoke0(Unknown Source)
at sun.plugin2.liveconnect.JavaClass.invoke(Unknown Source)
at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo$DefaultInvocationDelegate.invoke(Unknown Source)
at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo.doObjectOp(Unknown Source)
at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo$LiveConnectWorker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
P.S.: Applet is signed.
The problem is the call from JavaScript. If you are using JavaScript to call your method, the permissions of the call get down to the intersection of the JavaScript bridge's permissions (i.e. nothing) and the permissions of your own code - even if your own code is signed.
To avoid this, and use the full privileges of your applet's code, put the security-relevant parts inside a AccessController.doPrivileged(...) call. (Of course, your applet should first check that this can't do anything malicious.)
I have no idea why it works if you are using the IP address directly instead of localhost, though.
localhost is an alias for 127.0.0.1 so you may have to set/fix it in your enviroment. Under Windows you have to edit the file C:\Windows\System32\drivers\etc\hosts.
localhost is typically resolved to both ::1 and 127.0.0.1 and the OS/libc is usually set up so that IPv6 is preferred in these circumstances.
Therefore, it's likely you're allowing only 127.0.0.1 and not IPv6 connections from ::1.