http 500 servlet with io exception - left in a limbo - java

I am uploading a file through a servlet onto my server.
It has been working fine all along until this afternoon, when all of a sudden I started getting the
java.io.IOException: Server returned HTTP response code: 500 for URL: http://localhost:8282
I have been using tomcat 7 for the application and was working fine since long.
I am not sure what crashed within the server or where exactly the issue is happening.
I tried:
Changing different ports
Clean, delete and use different servers ( Vfabric)
Added JAVA_TOOL_OPTIONS to the system variables.
Uninstalled and reinstalled tomcat.
Tried restarting the systems to see if there are any open/daemon threads hanging.
Increased the max thread size in the server.xml in the tomcat folder.
I could not come across other possible feasible options to resolve the issue. Please suggest and provide insight if possible.
Below is the code from my application : (Client-side code):
private URLConnection getServletConnection() throws MalformedURLException,
IOException {
// Config
servletConnection.setDoInput(true);
servletConnection.setDoOutput(true);
servletConnection.setUseCaches(false);
servletConnection.setDefaultUseCaches(false);
servletConnection.setRequestMethod("POST");
servletConnection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + this.boundary);
servletConnection.setRequestProperty("Connection", "Keep-Alive");
servletConnection.connect();
return servletConnection;
}
private boolean onSendData(String fileEntry) {
try {
// Send data to the servlet
HttpURLConnection servletConnection = (HttpURLConnection) getServletConnection();
DataOutputStream dataOutputStream = new DataOutputStream(
servletConnection.getOutputStream());
final FileInputStream fileInputStream = new FileInputStream(
...
// send multipart form data necesssary after file data
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
// Receive result from servlet
InputStream inputStream = servletConnection.getInputStream();
ObjectInputStream objectInputStream = new ObjectInputStream(
inputStream);
String result = (String) objectInputStream.readObject();
objectInputStream.close();
inputStream.close();
dataOutputStream.flush();
dataOutputStream.close();
fileInputStream.close();
} catch (java.net.MalformedURLException mue) {
mue.printStackTrace();
System.out
.println("Invalid serlvetUrl, error: " + mue.getMessage());
errorLabel.setText(mue.getMessage());
} catch (java.io.IOException ioe) {
ioe.printStackTrace();
System.out.println("Couldn't open a URLConnection, error: "
+ ioe.getMessage());
errorLabel.setText(ioe.getMessage());
} catch (Exception e) {
e.printStackTrace();
System.out.println("Exception caught, error: " + e.getMessage());
errorLabel.setText(e.getMessage());
}
return fileUploaded;
}
And this is the error I am seeing (WHEN I RUN THE CODE AS AN APPLET IN MY IDE ):
Caused by: java.io.IOException: Server returned HTTP response code: 500 for URL: http://localhost:8282/UploadFile/upload
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1626)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:468)
at com.FileUpload.onSendData(FileUpload.java:317)
... 4 more
Strangely, when I am running this on a web-browser(RUNNING AS A SIGNED JAR FILE), I see the following error in the java console (This is an applet).
java.net.ConnectException: Connection refused: connect
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 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)
Couldn't open a URLConnection, error: Connection refused: connect

Related

Connection problem while connecting to PostgreSQL database through JDBC

I have an IP address 192.168.218.18
I've tried a lot of ways connecting to that server every time I'm getting a message as connection attempt failed.
For security reasons I've hidden the username and password.
Code:
public static void main(String[] args) {
String url = "jdbc:postgresql://192.168.218.18:5432/manikanta?user=*****&password=*****&ssl=true";
try {
Connection conn = DriverManager.getConnection(url);
System.out.println("connection established");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}
Exceptions i got
org.postgresql.util.PSQLException: The connection attempt failed. at
org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:292)
at
org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
at org.postgresql.jdbc.PgConnection.(PgConnection.java:211) at
org.postgresql.Driver.makeConnection(Driver.java:458) at
org.postgresql.Driver.connect(Driver.java:260) at
java.sql.DriverManager.getConnection(Unknown Source) at
java.sql.DriverManager.getConnection(Unknown Source) at
com.inno.demo.ConnectionJDBC.main(ConnectionJDBC.java:17) 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.postgresql.core.PGStream.(PGStream.java:75) at
org.postgresql.core.v3.ConnectionFactoryImpl.tryConnect(ConnectionFactoryImpl.java:91)
at
org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:192)
... 7 more
You should be passing the user and password separately, not as part of the URL:
public static void main(String[] args) {
String url = "jdbc:postgresql://192.168.218.18:5432/v";
String user = "****";
String password = "*****";
try (Connection con = DriverManager.getConnection(url, user, password);
System.out.println("connection established");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
See: http://zetcode.com/java/postgresql/
Since pinging to the IP 192.168.218.18 (I'll refer to this as target system) has failed, verify and confirm one of the following:
Your system is connected to the same network as the target system (i.e. Private network)
If you have access to the target system, try pinging your local machine's IP from that system and check if pinging is successful from there or not
Make sure that your/target system's firewall is configured to allow connections to each other
If you confirm these, I am sure you will at least have a basic idea of what and where it is going wrong. And with that your connection issue will get resolved.

Client java code fails running when server Tom Cat is not running in REST or check if server is on from client in REST

I am new to web services. I am using Rest
Trying to connect the url
http://localhost:8080/CrunchifyRESTJerseyExample/crunchify/ctofservice/22
from a client java program
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
public class CrunchifyRESTJerseyNetURLClient {
public static void main(String[] args) {
System.out.println("\n============Output:============ \n"
+ callURL("http://localhost:8080/CrunchifyRESTJerseyExample/crunchify/ctofservice/22"));
}
public static String callURL(String myURL) {
System.out.println("Requested URL: " + myURL);
StringBuilder sb = new StringBuilder();
URLConnection urlConn = null;
InputStreamReader in = null;
try {
URL url = new URL(myURL);
urlConn = url.openConnection();
if (urlConn != null)
urlConn.setReadTimeout(60 * 1000);
if (urlConn != null && urlConn.getInputStream() != null) {//checked hear
in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());
BufferedReader bufferedReader = new BufferedReader(in);
if (bufferedReader != null) {
int cp;
while ((cp = bufferedReader.read()) != -1) {
sb.append((char) cp);
}
bufferedReader.close();
}
}
in.close();
} catch (Exception e) {
throw new RuntimeException("Exception while calling URL:" + myURL, e);
}
return sb.toString();
}
}
The code runs fine on active server ie when tomcat is running.
But problem is when the server is not running.
It is throwing an exception like:
Requested URL: http://localhost:8080/CrunchifyRESTJerseyExample/crunchify/ctofservice/22
Exception in thread "main" java.lang.RuntimeException: Exception while calling URL:http://localhost:8080/CrunchifyRESTJerseyExample/crunchify/ctofservice/22
at com.crunchify.client.CrunchifyRESTJerseyNetURLClient.callURL(CrunchifyRESTJerseyNetURLClient.java:40)
at com.crunchify.client.CrunchifyRESTJerseyNetURLClient.main(CrunchifyRESTJerseyNetURLClient.java:14)
Caused by: java.net.ConnectException: Connection refused: 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 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.plainConnect0(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.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at com.crunchify.client.CrunchifyRESTJerseyNetURLClient.callURL(CrunchifyRESTJerseyNetURLClient.java:27)
... 1 more
I have checked
if (urlConn != null)
if (urlConn != null && urlConn.getInputStream() != null)
But still the code gets executed throwing exception
Kindly help
what needs to be handled .
You can access a web URL only if the server on which it is deployed is in running state. It is true for all the web pages and APIs that exists.
If you want to display some meaningful message or do some other work in case the API is not reachable, then don't throw the error (You are throwing throw new RuntimeException("Exception while calling URL:" + myURL, e); in the catch block.) or catch the thrown error in the calling method ie in main method. In the catch block you can just print some message on console or call alternate API that displays user friendly message.

Getting strange http time out error in threads

I'm using the ARIN rest whois service to look up the organizations for a list of IP addresses. Since the list is very long (the one below is just a very small subset), I opted to do this with threads for faster performance.
public class SimpleThreadPool {
public final static String[] ips = {
"192.150.16.64","192.243.232.36","208.77.139.8","63.140.35.160",
"63.140.35.161","63.140.35.162","63.140.59.142","63.140.61.200",
"66.235.132.238","66.235.137.133","66.235.138.18","66.235.138.192",
"66.235.138.195","66.235.139.152","66.235.139.172","66.235.139.204",
"66.235.139.205","66.235.139.206","66.235.139.227","66.235.141.144",
"66.235.141.145","66.235.141.146","66.235.141.16","66.235.142.20",
"66.235.142.24","66.235.141.145","184.106.60.35","207.171.162.26",
"207.171.162.75","207.171.162.95","207.171.185.201","207.171.187.117",
"207.171.187.118","207.171.189.80","207.171.189.81","216.137.37.108",
"216.137.37.122","216.137.37.128","216.137.37.138","216.137.37.140",
"216.137.37.178","216.137.37.183","216.137.37.198","216.137.37.225",
"216.137.37.235","216.137.37.37","216.137.37.52","216.137.37.57",
"216.137.37.6","216.137.37.84"
};
public static void main(String[] args) throws InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(4);
for (int i = 0; i < ips.length; i++) {
Runnable worker = new WorkerThread(ips[i]);
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {}
System.out.println("All threads finished.");
}
}
And here is WorkerThread:
public class WorkerThread implements Runnable {
private String workingIP;
public WorkerThread(String workingIP) {
this.workingIP = workingIP;
}
#Override
public void run() {
try {
URL url = new URL("http://whois.arin.net/rest/ip/" + workingIP);
InputStream inputStream = null;
HttpURLConnection con = (HttpURLConnection)(url.openConnection());
con.connect();
inputStream = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String line = null;
while( (line=br.readLine()) != null )
{
if (line.contains("<td>Organization</td><td>")) {
String companyName = line.replace("<td>Organization</td><td>", "").trim();
System.out.println(workingIP + " maps to: " + companyName);
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
On my work machine (w/ an i5-2400, 4GB RAM, 32bit Win7), this code works fine all the way down to around the 45th+ IP address in the array. Then I get java.net.ConnectException errors thrown for the remaining lookups:
...
216.137.37.57 maps to: Amazon.com, Inc.
216.137.37.6 maps to: Amazon.com, Inc.
java.net.ConnectException: Connection timed out: 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)
If I change the executor's thread pool size to 1, then everything works and no errors are thrown, but obviously the lookups take a lot longer.
The really strange thing is that if I run this same code on my 2011 Core i7 Mac, no errors whatsoever are thrown. Granted, the two are on different networks (my work machine uses my work's network, while my Mac is wirelessly tethered to a smartphone).
Any idea what's going on here, and what I can do to fix it?
You need to write sane error-handling code. It really is that simple. What do you want to do if the connection times out? If you make a lot of connections at once on a slow network, some of them may time out.

Java FTPS Problems

Still unanswered. Any and all help is appreciated!
I am using Apache Commons-Net3.1 and trying to get the FTPS working. When I try to connect, I am getting the following errors in the console :
---EDIT: CODE AND ERRORS UPDATED---
java.net.ConnectException: Connection refused: 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 org.apache.commons.net.SocketClient.connect(SocketClient.java:171)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:192)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:285)
I am sure I am just not setting up it up right. Here is my code. Any point in the right direction would be greatly appreciated. (I am trying to connect via port 990 by the way). The code errors at the line "client.connect(ftpHost);"
import org.apache.commons.net.ftp.FTPSClient;
import java.io.IOException;
import java.io.FileOutputStream;
public class MyFTP {
public void downloadFTP(){
FTPSClient client = new FTPSClient(false);
FileOutputStream fos = null;
client.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
try {
client.connect(ftpHost);
client.enterLocalPassiveMode();
client.login(ftpUser, ftpPassword);
String filename = "liveGUIfile.txt";
fos = new FileOutputStream(filename);
client.retrieveFile("/root/Desktop/" + filename, fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
FTPS may be explicit or implicit, you use explicit:
FTPSClient client = new FTPSClient(false);
But explicit one usually uses 21 port, like FTP does, and implicit one uses 990 port. So try to connect to 21 port or to use new FTPSClient(true)
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
That says it all. Plaintext connection. You are connecting to an FTP server, not an FTPS server. It's right there in the error message.

Java RMI cannot connect to host from external client

I've been using RMI in this project for a while. I've gotten the client program to connect (amongst other things) to the server when running it over my LAN, however when running it over the internet I'm running into the following exception:
java.rmi.ConnectException: Connection refused to host: (private IP of host machine); nested exception is:
java.net.ConnectException: Connection timed out: connect
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(Unknown Source)
at sun.rmi.transport.tcp.TCPChannel.createConnection(Unknown Source)
at sun.rmi.transport.tcp.TCPChannel.newConnection(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 $Proxy1.ping(Unknown Source)
at client.Launcher$PingLabel.runPing(Launcher.java:366)
at client.Launcher$PingLabel.<init>(Launcher.java:353)
at client.Launcher.setupContentPane(Launcher.java:112)
at client.Launcher.<init>(Launcher.java:99)
at client.Launcher.main(Launcher.java:59)
Caused by: java.net.ConnectException: Connection timed out: 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 java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(Unknown Source)
at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(Unknown Source)
... 12 more
This error is remeniscent of my early implementation of RMI and I can obtain the error verbatum if I run the client locally without the server program running as well. To me Connection Timed Out means a problem with the server's response.
Here's the client initiation:
public static void main(String[] args)
{
try
{
String host = "<WAN IP>";
Registry registry = LocateRegistry.getRegistry(host, 1099);
Login lstub = (Login) registry.lookup("Login Server");
Information istub = (Information) registry.lookup("Game Server");
new Launcher(istub, lstub);
}
catch (RemoteException e)
{
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
catch (NotBoundException e)
{
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
}
Interestingly enough no Remote Exception is thrown here.
Here's the server initiation:
public static void main(String args[])
{
try
{
GameServer gobj = new GameServer();
Information gstub = (Information) UnicastRemoteObject.exportObject(
gobj, 1099);
Registry registry = LocateRegistry.createRegistry(1099);
registry.bind("Game Server", gstub);
LoginServer lobj = new LoginServer(gobj);
Login lstub = (Login) UnicastRemoteObject.exportObject(lobj, 7099);
// Bind the remote object's stub in the registry
registry.bind("Login Server", lstub);
System.out.println("Server ready");
}
catch (Exception e)
{
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
Bad practice with the catch(Exception e) I know but bear with me.
Up to this stage I know it works fine over the LAN, here's where the exception occurs over the WAN and is the first place a method in the server is called:
private class PingLabel extends JLabel
{
private static final long serialVersionUID = 1L;
public PingLabel()
{
super("");
runPing();
}
public void setText(String text)
{
super.setText("Ping: " + text + "ms");
}
public void runPing()
{
try
{
PingThread pt = new PingThread();
gameServer.ping();
pt.setRecieved(true);
setText("" + pt.getTime());
}
catch (RemoteException e)
{
e.printStackTrace();
}
}
}
That's a label placed on the launcher as a ping test. the method ping(), in gameserver does nothing, as in is a null method.
It's worth noting also that ports 1099 and 7099 are forwarded to the server machine (which should be obvious from the stack trace).
Can anyone see anyting I'm missing/doing wrong? If you need any more information just ask.
EDIT: I'm practically certain the problem has nothing to do with my router settings. When disabling my port forwarding settings I get a slightly different error:
Client exception: java.rmi.ConnectException: Connection refused to host: (-WAN IP NOT LOCAL IP-);
but it appears both on the machine locally connected to the server and on the remote machine.
In addition, I got it to work seamlessly when connecting the server straight tho the modem (cutting out the router. I can only conclude the problem is in my router's settings but can't see where (I've checked and double checked the port forwarding page). That's the only answer i can come up with.
Are you using NAT (Network Address Translation)? This is the typical case if your LAN uses non-routable address behind a router (like 10.x or 192.169.x etc).
If this is the case, you need to specify the public IP of the server with following option,
-Djava.rmi.server.hostname=host_name_or_public_ip

Categories