Java FTPS Problems - java

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.

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.

Trying to connect to RMI Registry but getting java.net.ConnectException: Connection refused: connect

I have two computers. On one of them, is running an RMI Registry - which was created from this code alone:
package main;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Scanner;
public class TheRegistry{
public static void main(String[] args) {
try {
Registry reg = LocateRegistry.createRegistry(2020);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
System.out.println("Registry Created");
Scanner input = new Scanner(System.in);
input.nextInt();
System.exit(0);
}
}
}
The other computer has a server that is trying to register an Object on this registry, however, it gets an exception. Here is the code for the server:
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.rmi.*;
public class TextScramblerServer implements TextScramblerInterface
{
private static Remote obj;
// main method to export
#Override //Return input text as-is.
public String testInputText(String inputText) {
return "Your input text is: " + inputText;
}
#Override //Return the string reversed.
public String reverse(String inputText) {
String reversedInput = "";
for(int i=0; i<inputText.length();i++)
{
reversedInput=reversedInput+inputText.charAt((inputText.length()-1)-i);
}
return "Result: "+reversedInput;
}
#Override //Return the string scrambled.
public String scramble(String inputText) {
String scrambledInput="";
for(int i=0; i<inputText.length();i++)
{
if(i%2==0)
{
scrambledInput=scrambledInput+inputText.charAt(i);
}
else
{
scrambledInput=inputText.charAt(i)+scrambledInput;
}
}
return "Result: "+scrambledInput;
}
public void exportServer() throws Exception {
System.setSecurityManager(new RMISecurityManager());
obj = UnicastRemoteObject.exportObject(this, 2022);
Registry registry = LocateRegistry.getRegistry("132.205.94.50", 2020);
registry.bind("test", obj);
}
public static void main(String[] args) {
try {
(new TextScramblerServer()).exportServer();
System.out.println("Server is up and running");
}
catch(Exception e){
e.printStackTrace();
try {
UnicastRemoteObject.unexportObject(obj, true); //close port
} catch (NoSuchObjectException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
I keep getting the error:
java.rmi.ConnectException: Connection refused to host: 132.205.94.50; nested exception is:
java.net.ConnectException: Connection refused: 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.newCall(Unknown Source)
at sun.rmi.registry.RegistryImpl_Stub.bind(Unknown Source)
at TextScramblerServer.exportServer(TextScramblerServer.java:57)
at TextScramblerServer.main(TextScramblerServer.java:62)
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 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)
... 7 more
java.rmi.NoSuchObjectException: object not exported
at sun.rmi.transport.ObjectTable.unexportObject(Unknown Source)
at java.rmi.server.UnicastRemoteObject.unexportObject(Unknown Source)
at TextScramblerServer.main(TextScramblerServer.java:68)
I can't figure out why this is happening. I think I've tried everything
I ran your code and it worked for me after configuring the security policy.
Your ConnectionRefused exception means that the underlying TCP connection cannot be established. It's network issue, not an RMI issue.
Try running both the server and registry on the same host, and use localhost as the hostname. If it works, the problem is likely a firewall issue between the two hosts.
You can do a simple test of a TCP connection to the specific port using telnet. If the port isn't listening, telnet will give you a similar connection refused message. If the port is listening, you'll get something like this on the terminal:
Connected to localhost.
Escape character is '^]'.
Control-C to get out of the session.
The specific telnet output may vary based on your OS, but they are all about the same.
If it is a firewall issue, you'll have to open up the ports. How to do that depends on OS, but it's easy to find.
Either your Registry has been garbage-collected, you got the IP address wrong, or it is a public IP address and you haven't configured port forwarding.
You need to store the Registry reference in a static object to overcome garbage collection, although what the point of that program is when rmiregistry.exe already exists escapes me completely.
You're barking up the wrong tree anyway. You can only bind to an RMI Registry that is running in the local host. There is therefore never any need to use a Registry hostname other than "localhost" when binding or unbinding.
The reason you got the NoSuchObjectException is that you are trying to unexport the stub, which is referred to by obj, which is the result of UnicastRemoteObject.exportObject(), which returns the stub. See the Javadoc. You need to save the result of new TextScramblerServer() and unexport that.

Why does my SOCKS proxy code throw SocketException: Malformed reply from SOCKS server?

Why does my SOCKS proxy code throw SocketException: Malformed reply from SOCKS server? I've tried to set in URLConnection or other, but this doesn't work. Only thing that worked - chilkat lib, but it's commercial. So, how I, for example, make http request through a ASOCKS proxy? Maybe exist some free lib for that?
For example, that code:
SocketAddress addr = new InetSocketAddress(proxy_ip, proxy_port);
Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr);
Socket socket = new Socket(proxy);
InetSocketAddress dest = new InetSocketAddress("google.com", 80);
try {
socket.connect(dest);
} catch (IOException ex) {
Logger.getLogger(CheckProxy.class.getName()).log(Level.SEVERE, null, ex);
}
Throws exception:
java.net.SocketException: Malformed reply from SOCKS server
at java.net.SocksSocketImpl.readSocksReply(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at proxychecker.CheckProxy.SocksCheck(CheckProxy.java:86)
Where line 86 is "socket.connect(dest);"
Explanation of this bug: bugs.java.com/view_bug.do?bug_id=6964547
You need to manually change mode in Socket object using this code:
Class clazzSocks = socket.getClass();
Method setSockVersion = null;
Field sockImplField = null;
SocketImpl socksimpl = null;
try {
sockImplField = clazzSocks.getDeclaredField("impl");
sockImplField.setAccessible(true);
socksimpl = (SocketImpl) sockImplField.get(socket);
Class clazzSocksImpl = socksimpl.getClass();
setSockVersion = clazzSocksImpl.getDeclaredMethod("setV4");
setSockVersion.setAccessible(true);
if(null != setSockVersion){
setSockVersion.invoke(socksimpl);
}
sockImplField.set(socket, socksimpl);
} catch (Exception e) {
}
SocketException: Malformed reply from SOCKS server
That indicates that you don't have a SOCKS proxy at all. Possibly it is an HTTP proxy.
And note that you asked the wrong question. Your code was correct, it was your premiss that was wrong.

http 500 servlet with io exception - left in a limbo

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

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