I installed FileZilla FTP Server on my local Windows 7 machine.
I also installed FileZilla FTP client on the same machine.
Connection is successfull between both of them confirming the server and client partnership exists.
I wrote a small quick and dirtry Jsch program for connecting to the FileZilla FTP server and below is the program:
public class TestJSch {
/** Creates a new instance of TestCommonsNet */
public TestJSch() {
}
/**
* main - Unit test program
*
* #param args
* Command line arguments
*
*/
public static void main(String[] args) {
try {
String ftpHost = "127.0.0.1";
int ftpPort = 21;// 14147;
// int ftpPort = 990;// 14147;
String ftpUserName = "kedar";
String ftpPassword = "XXXXXXXXXXX";
String ftpRemoteDirectory = "C:\\KEDAR\\Java\\FTP_Folder";
String fileToTransmit = "C:\\KEDAR\\Java\\File_Folder\\Customer.txt";
String identityfile = "C:\\KEDAR\\Java\\Ftp\\certificate.crt";
//
// First Create a JSch session
//
JSch.setLogger(new MyLogger());
System.out.println("Creating session.");
JSch jsch = new JSch();
String knownHostsFilename = "C:\\Windows\\System32\\drivers\\etc\\hosts";
jsch.setKnownHosts(knownHostsFilename);
jsch.addIdentity(identityfile);
Session session = null;
Channel channel = null;
ChannelSftp c = null;
//
// Now connect and SFTP to the SFTP Server
//
try {
// Create a session sending through our username and password
session = jsch.getSession(ftpUserName, ftpHost, ftpPort);
System.out.println("Session created.");
session.setPassword(ftpPassword);
// Security.addProvider(new com.sun.crypto.provider.SunJCE());
// b
// Setup Strict HostKeyChecking to no so we dont get the
// unknown host key exception
//
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
System.out.println("Session connected.");
//
// Open the SFTP channel
//
System.out.println("Opening Channel.");
channel = session.openChannel("sftp");
channel.connect();
c = (ChannelSftp) channel;
} catch (Exception e) {
System.err.println("Unable to connect to FTP server."
+ e.toString());
throw e;
}
//
// Change to the remote directory
//
System.out.println("Changing to FTP remote dir: "
+ ftpRemoteDirectory);
c.cd(ftpRemoteDirectory);
//
// Send the file we generated
//
try {
File f = new File(fileToTransmit);
System.out.println("Storing file as remote filename: "
+ f.getName());
c.put(new FileInputStream(f), f.getName());
} catch (Exception e) {
System.err
.println("Storing remote file failed." + e.toString());
throw e;
}
//
// Disconnect from the FTP server
//
try {
c.quit();
} catch (Exception exc) {
System.err.println("Unable to disconnect from FTPserver. "
+ exc.toString());
}
} catch (Exception e) {
System.err.println("Error: " + e.toString());
}
System.out.println("Process Complete.");
System.exit(0);
}
public static class MyLogger implements com.jcraft.jsch.Logger {
static java.util.Hashtable name = new java.util.Hashtable();
static {
name.put(new Integer(DEBUG), "DEBUG: ");
name.put(new Integer(INFO), "INFO: ");
name.put(new Integer(WARN), "WARN: ");
name.put(new Integer(ERROR), "ERROR: ");
name.put(new Integer(FATAL), "FATAL: ");
}
public boolean isEnabled(int level) {
return true;
}
public void log(int level, String message) {
System.err.print(name.get(new Integer(level)));
System.err.println(message);
}
}
}
I tried running this program and below is the FTP log:
(000033)9/12/2011 13:08:53 PM - (not logged in) (127.0.0.1)> Connected, sending welcome message...
(000033)9/12/2011 13:08:53 PM - (not logged in) (127.0.0.1)> 220-FileZilla Server version 0.9.39 beta
(000033)9/12/2011 13:08:53 PM - (not logged in) (127.0.0.1)> 220-written by Tim Kosse (Tim.Kosse#gmx.de)
(000033)9/12/2011 13:08:53 PM - (not logged in) (127.0.0.1)> 220 Please visit http://sourceforge.net/projects/filezilla/
(000033)9/12/2011 13:08:53 PM - (not logged in) (127.0.0.1)> SSH-2.0-JSCH-0.1.44
(000033)9/12/2011 13:08:53 PM - (not logged in) (127.0.0.1)> 500 Syntax error, command unrecognized.
(000033)9/12/2011 13:09:54 PM - (not logged in) (127.0.0.1)> 421 Login time exceeded. Closing control connection.
(000033)9/12/2011 13:09:54 PM - (not logged in) (127.0.0.1)> disconnected.
I don't understand why the JSch program is issuing SSH-2.0-JSCH-0.1.44 command and the communication is then turned down. How do we avoid this?
JSch is not an FTP client. JSch is an SSH client (with an included SFTP implementation).
The SSH protocol is a protocol to allow secure connections to a server, for shell access, file transfer or port forwarding. For this, the server must have an SSH server (usually on port 22, but that can vary). SFTP is a binary file transfer protocol which is usually tunneled over SSH, and not related to FTP (other than by name).
If you want to use JSch to download/upload files, you need to install and activate an SSH/SFTP server on your computer (respective the computer you want to access).
For FTP, you have to use other Java libraries (Apache Commons FTPClient seems to be famous, from the questions here).
By the way, the known hosts file for JSch is a file listing the public keys of the SSH hosts, not the file listing their IP addresses (which is the Windows config file you are trying to supply here).
Use Apache commons-net FTP library.
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class FTPConnectionCode {
public static void main(String[] args) {
String server = "www.website.com";
// generally ftp port is 21
int port = 21;
String user = "ftpusername";
String pass = "ftppassword";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
showServerReply(ftpClient);
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println("Connect failed");
return;
}
boolean success = ftpClient.login(user, pass);
showServerReply(ftpClient);
if (!success) {
System.out.println("Could not login to the server");
return;
}
// Changes working directory
success = ftpClient.changeWorkingDirectory("/dir");
showServerReply(ftpClient);
if (success) {
System.out.println("Successfully changed working directory.");
} else {
System.out.println("Failed to change working directory. See server's reply.");
}
// logs out
ftpClient.logout();
ftpClient.disconnect();
} catch (IOException ex) {
System.out.println("Oops! Something wrong happened");
ex.printStackTrace();
}
}
private static void showServerReply(FTPClient ftpClient) {
String[] replies = ftpClient.getReplyStrings();
if (replies != null && replies.length > 0) {
for (String aReply : replies) {
System.out.println("SERVER: " + aReply);
}
}
}
}
Related
I'm using below code for Connecting to FTPS server and trying to upload file to directory.
Getting 522 Data connection must use cached TLS session error at storeFile method call.
Code:
public FTPSClient ftpsConnection(String server, String user, String pass) {
FTPSClient ftp = new FTPSClient();
try {
ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
int reply;
ftp.connect(server, port);
System.out.println("Connected to " + server + ".");
System.out.print(ftp.getReplyString());
reply = ftp.getReplyCode();
if(!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
System.err.println("FTP server refused connection.");
System.exit(1);
}
ftp.login(user, pass);
} catch(IOException e) {
e.printStackTrace();
}
return ftp;
}
public boolean UploapFileToFtpServer(String server, String user, String pass, String directory, String bdiPath, String file )
{
boolean done=false;
FTPSClient client = ftpsConnection(server,user,pass);
try {
boolean changeWorkingDirectory = client.changeWorkingDirectory(directory);
if (changeWorkingDirectory)
{
File localFile = new File(bdiPath+"/" + file);
String remoteFile = file;
InputStream inputStream = null;
try {
inputStream = new FileInputStream(localFile);
client.execPBSZ(0);
client.execPROT("P");
client.setFileType(FTP.BINARY_FILE_TYPE);
client.enterLocalPassiveMode();
done = client.storeFile(remoteFile, inputStream);
if(!done){
System.out.println("file upload failed! - "+client.getReplyString());
}
} catch (Exception e) {
System.out.println("FtpsServer exception :"+e);
}
inputStream.close();
if (done) {
System.out.println("file is uploaded successfully.");
}
}
} catch (Exception ex) {
System.out.println("FtpServer exception :"+ex);
} finally {
ftpsDisconnect(client);
}
return done;
}
Logs:
220 Service ready for new user.
AUTH TLS
234 Command AUTH okay; starting TLS connection.
Connected to ****.
234 Command AUTH okay; starting TLS connection.
USER ***
331 User name okay, need password for ***.
PASS ****
230 User logged in, proceed.
CWD /sample/location/
250 Directory changed to /sample/location
PBSZ 0
200 Command PBSZ okay.
PROT P
200 Command PROT okay.
TYPE I
200 Command TYPE okay.
PASV
227 Entering Passive Mode (44,224,94,109,32,7)
STOR test.csv
150 File status okay; about to open data connection.
522 Data connection must use cached TLS session
At client.storeFile(remoteFile, inputStream); I'm getting 522 Data connection must use cached TLS session. Could someone please help me how to resolve this issue?
I am trying to ftp the file from Linux VM to an AS400 server. I was able to login to server in passive mode but when trying to use the STOR command to upload the file getting below error:
STOR XX.YY600040.XXXZZZXXX
**550 Dataset not found, DSN=FTPID.XX.YY600040.XXXZZZXXX**
Not sure why the ftpid that i am using is getting prefixed to the filename. Is there any way to avoid it?
Below is the sample code that i am using:
private static String sendFTPFile(String fileName) throws Exception {
StringBuffer ftpMessage = new StringBuffer();
if (SHOW_DEBUG) ftpMessage.append("<ul>");
FTPClient ftp = null;
try {
String server = "****";
String username = "****";
String password = "XXXXX";
String hostDir = "";
String localFileName = fileName;
String localFilePath = "***/**/*";
boolean binaryTransfer = false, error = false;
FTPClient ftp = new FTPClient();
ftp.addProtocolCommandListener(new PrintCommandListener(
new PrintWriter(System.out)));
int reply;
ftp.connect(server)
// After connection attempt, you should check the reply code to verify
// success.
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply))
{
ftp.disconnect();
error = true;
}
if(!error) {
if (!ftp.login(username, password))
{
ftp.logout();
error = true;
}
if(!error) {
if (binaryTransfer)
ftp.setFileType(FTP.BINARY_FILE_TYPE);
// Use passive mode as default
ftp.enterLocalPassiveMode();
InputStream input;
input = new FileInputStream(localFilePath+localFileName);
boolean ftpSuccess = ftp.storeFile(hostDir+localFileName, input);
input.close();
if (!ftpSuccess) {
throw new Exception("File ftp error");
}else {
if (SHOW_DEBUG) ftpMessage.append("<li>isFtpSuccess()...success").append("</li>");
}
ftp.logout();
if (SHOW_DEBUG) ftpMessage.append("<li>ftp.logout()...success").append("</li>");
}
}
}
catch (Exception ex) {
ex.printStackTrace();
System.out.println("Exception occur while transfering file using ftp"+ ex.toString());
throw new Exception(ftpMessage.toString(), ex);
}
finally {
if (ftp!=null && ftp.isConnected())
{
try
{
ftp.disconnect();
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("Exception occur while transfering file using ftp"+ e.toString());
throw new Exception(ftpMessage.toString(), e);
}
}
if (SHOW_DEBUG) ftpMessage.append("</ul>");
}
return ftpMessage.toString();
}
I did some more debugging on doing ftp from linux to as400. And when doing pwd after logging to ftp server its giving message as:
ftp> pwd
257 "'FTPID.'" is current prefix
And thinking how to remove that prefix so i ran the below command got output as no prefix defined:
ftp> cd ..
200 "" no prefix defined
And after that when i uploaded the file using put command it was uploaded successfully. So i did some research on how to go back one directory using Apache commons.net api's that i am using and found the CDUP method.
When i ran the FTPClient.cdup() method before uploading the file. I was able to successfully FTP the file from java code as well.
ftp.cdup();
input = new FileInputStream(localFilePath+localFileName);
boolean ftpSuccess = ftp.storeFile(hostDir+localFileName, input);
I made a small application that should upload files to an FTP server. The thing is that I used passive mode with the method
enterLocalPassiveMode()
Recently I was told that no passive mode is allowed on the FTP server, so I should make my application work in active mode. I suppose it couldn't be done by simply changing the method to
enterLocalActiveMode()
What else should I change in the application to ensure it's working in active mode.
Here's a code snippet which makes the connection to the server:
public void connect() throws FTPException {
try {
ftpClient.connect(server, port);
replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
printText("FTP server refused connection.");
throw new FTPException("FTP server refused connection.");
}
boolean logged = ftpClient.login(user, pass);
if (!logged) {
ftpClient.disconnect();
printText("Could not login to the server.");
throw new FTPException("Could not login to the server.");
}
ftpClient.enterLocalPassiveMode();
} catch (IOException ex) {
printText("I/O errortest: " + ex.getMessage());
throw new FTPException("I/O error: " + ex.getMessage());
}
}
Some guidance to what I have to change?
This is old, but I stumbled onto it trying to solve the issue myself.
You have to call enterLocalPassiveMode() after calling connect() and before calling login().
See my example below which initialises the FTPClient in local passive mode, lists files for a given directory, then closes the connections.
private static FTPClient client;
public static void main(String [] args) {
//initialise the client
initPassiveClient();
//do stuff
FTPFile [] files = listFiles("./");
if( files != null ) {
logger.info("Listing Files:");
for( FTPFile f : files) {
logger.info(f.getName());
}
}
//close the client
close();
}
/**
* getPassiveClient retrive a FTPClient object that's set to local passive mode
*
* #return FTPClient
*/
public static FTPClient initPassiveClient() {
if( client == null ) {
logger.info("Getting passive FTP client");
client = new FTPClient();
try {
client.connect(server);
// After connection attempt, you should check the reply code to verify
// success.
int reply = client.getReplyCode();
if(!FTPReply.isPositiveCompletion(reply)) {
client.disconnect();
logger.error("FTP server refused connection.");
System.exit(0);
}
//after connecting to the server set the local passive mode
client.enterLocalPassiveMode();
//send username and password to login to the server
if( !client.login(user, pass) ) {
logger.error("Could not login to FTP Server");
System.exit(0);
}
} catch (SocketException e) {
String message = "Could not form socket";
logger.error(message+"\n", e);
System.exit(0);
} catch (IOException e) {
String message = "Could not connect";
logger.error(message+"\n", e);
System.exit(0);
}
}
return client;
}
public static void close() {
if( client == null ) {
logger.error("Nothing to close, the FTPClient wasn't initialized");
return;
}
//be polite and logout & close the connection before the application finishes
try {
client.logout();
client.disconnect();
} catch (IOException e) {
String message = "Could not logout";
logger.error(message+"\n", e);
}
}
/**
* listFiles uses the FTPClient to retrieve files in the specified directory
*
* #return array of FTPFile objects
*/
private static FTPFile[] listFiles(String dir) {
if( client == null ) {
logger.error("First initialize the FTPClient by calling 'initFTPPassiveClient()'");
return null;
}
try {
logger.debug("Getting file listing for current director");
FTPFile[] files = client.listFiles(dir);
return files;
} catch (IOException e) {
String message = "";
logger.error(message+"\n", e);
}
return null;
}
http://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html#enterLocalActiveMode()
Not sure if this is the FTPClient you're using but it would appear that enterLocalActiveMode does indeed exist.
FTPClient Documentation states that
public boolean enterRemoteActiveMode(InetAddress host,int port)
throws IOException
Set the current data connection mode to ACTIVE_REMOTE_DATA_CONNECTION . Use this method only for server to server data transfers. This method issues a PORT command to the server, indicating the other server and port to which it should connect for data transfers. You must call this method before EVERY server to server transfer attempt. The FTPClient will NOT automatically continue to issue PORT commands. You also must remember to call enterLocalActiveMode() if you wish to return to the normal data connection mode.
Hope this helps!
I am using jsch to download files from server, my code below.
public static void downloadFile(TpcCredentialsDTO dto) {
logger.trace("Entering downloadFile() method");
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
boolean success = false;
try {
JSch jsch = new JSch();
session = jsch.getSession(dto.getUsername(), dto.getHost(),
dto.getPort());
session.setPassword(dto.getPassword());
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
logger.info("Connected to " + dto.getHost() + ".");
channel = session.openChannel("sftp");
channel.connect();
channelSftp = (ChannelSftp) channel;
List<String> filesToDownload = getFilesToDownload(dto,channelSftp);
if (!filesToDownload.isEmpty()) {
for (String fileDownloadName : filesToDownload) {
success = false;
OutputStream output = new FileOutputStream(
"C:\Download\BLT_03112012");
channelSftp.get("BLT_03112012",output);
success = true;
if (success)
logger.info(ServerConstants.DOWNLOAD_SUCCESS_MSG
+ fileDownloadName);
output.close();
}
}else {
logger.info(ServerConstants.NO_FILES_TO_DOWNLOAD
+ ServerUtils.getDateTime());
success = true;
}
} catch (JSchException ex) {
logger.error( ServerConstants.SFTP_REFUSED_CONNECTION, ex);
} catch (SftpException ex) {
logger.error(ServerConstants.FILE_DOWNLOAD_FAILED, ex);
} catch (IOException ex) {
logger.error(ServerConstants.FILE_NOT_FOUND, ex);
}catch (Exception ex) {
logger.error(ServerConstants.ERROR, ex);
}finally {
if (channelSftp.isConnected()) {
try {
session.disconnect();
channel.disconnect();
channelSftp.quit();
logger.info( ServerConstants.FTP_DISCONNECT);
} catch (Exception ioe) {
logger.error(ServerConstants.FTP_NOT_DISCONNECT, ioe);
}
}
}
logger.trace("Exiting downloadFile() method");
}
sftpChannel.get(filename, outputstream) is throwing an error.
2: File not found
at com.jcraft.jsch.ChannelSftp.throwStatusError(ChannelSftp.java:2629)
at com.jcraft.jsch.ChannelSftp._get(ChannelSftp.java:977)
at com.jcraft.jsch.ChannelSftp.get(ChannelSftp.java:946)
at com.jcraft.jsch.ChannelSftp.get(ChannelSftp.java:924)
at za.co.tpc.sftpserver.SftpConnection.downloadFile(SftpConnection.java:72)
at za.co.tpc.server.execute.FtpMtn.main(FtpMtn.java:44)
The same code does download Text Document file types but fails for 'File' filetype
Try using paths instead of stream:
String destPath = "filename.txt";
if (!filesToDownload.isEmpty()) {
for (String fileDownloadName : filesToDownload) {
success = false;
sftpChannel.get(fileDownloadName , destPath);
If you wanna use file and streams check this example:
http://kodehelp.com/java-program-for-downloading-file-from-sftp-server/
Please find in the below code sample comprising the file upload and download functionalities. Please pull the relevant details from properties files where ever string marked in lt;sftp.user.namegt;. I am deleting the file once the file is downloaded you can have it as per your requirement.
The event and locale parameters what I have added as part of download functionality is to filter the file(s); you can pass parameters as par you need.
Have placed a check to set proxy which can be used on need basis.
package com.util;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.ProxyHTTP;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import java.io.File;
import java.io.FileInputStream;
import java.util.Date;
import java.util.Properties;
import java.util.Vector;
/**
*
* #author Dinesh.Lomte
*/
public class SftpUtil {
/**
*
* #param fileName
* #throws Exception
*/
public static void upload(String fileName)
throws Exception {
String method = "upload(String fileName)";
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
try {
// Creating and instantiating the jsch specific instance
JSch jsch = new JSch();
// Fetching and setting the parameters like: user name, host and port
// from the properties file
session = jsch.getSession("<sftp.user.name>",
"<sftp.host>",
Integer.valueOf("<sftp.port>"));
// Fetching and setting the password as configured in properties files
session.setPassword("<sftp.user.password>");
// Setting the configuration specific properties
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
// Validating if proxy is enabled to access the sftp
isSftpProxyEnabled(session);
// Execution start time
long lStartTime = new Date().getTime();
System.out.println("Connecting to the sftp...");
// Connecting to the sftp
session.connect();
System.out.println("Connected to the sftp.");
// Execution end time
long lEndTime = new Date().getTime();
System.out.println("---------------------------------------------");
System.out.println("Connected to SFTP in : " + (lEndTime - lStartTime));
// Setting the channel type as sftp
channel = session.openChannel("sftp");
// Establishing the connection
channel.connect();
channelSftp = (ChannelSftp) channel;
// Setting the folder location of the external system as configured
channelSftp.cd("<sftp.output.folder.url>");
// Creating the file instance
File file = new File(fileName);
// Creating an fileInputStream instance
FileInputStream fileInputStream = new FileInputStream(file);
// Transfering the file from it source to destination location via sftp
channelSftp.put(fileInputStream, file.getName());
// Closing the fileInputStream instance
fileInputStream.close();
// De-allocating the fileInputStream instance memory by assigning null
fileInputStream = null;
} catch (Exception exception) {
throw exception;
} finally {
// Validating if channel sftp is not null to exit
if (channelSftp != null) {
channelSftp.exit();
}
// Validating if channel is not null to disconnect
if (channel != null) {
channel.disconnect();
}
// Validating if session instance is not null to disconnect
if (session != null) {
session.disconnect();
}
}
}
/**
*
* #param session
*/
private static void isSftpProxyEnabled(Session session) {
// Fetching the sftp proxy flag set as part of the properties file
boolean isSftpProxyEnabled = Boolean.valueOf("<sftp.proxy.enable>");
// Validating if proxy is enabled to access the sftp
if (isSftpProxyEnabled) {
// Setting host and port of the proxy to access the SFTP
session.setProxy(new ProxyHTTP("<sftp.proxy.host>",
Integer.valueOf("<sftp.proxy.port>");
}
System.out.println("Proxy status: " + isSftpProxyEnabled);
}
/**
*
* #param folder
* #param event
* #param locale
*/
public static void download(String folder, String event, String locale) {
String method = "download(String folder, String event, String locale)";
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
try {
// Creating and instantiating the jsch specific instance
JSch jsch = new JSch();
// Fetching and setting the parameters like: user name, host and port
// from the properties file
session = jsch.getSession("<sftp.user.name>",
"<sftp.host>",
Integer.valueOf("<sftp.port>"));
// Fetching and setting the password as configured in properties files
session.setPassword("<sftp.user.password>");
// Setting the configuration specific properties
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
// Validating if proxy is enabled to access the sftp
isSftpProxyEnabled(session);
// Execution start time
long lStartTime = new Date().getTime();
System.out.println("Connecting to the sftp...");
// Connecting to the sftp
session.connect();
System.out.println("Connected to the sftp.");
// Execution end time
long lEndTime = new Date().getTime();
System.out.println("---------------------------------------------");
System.out.println("Connected to SFTP in : " + (lEndTime - lStartTime));
// Setting the channel type as sftp
channel = session.openChannel(SFTP);
// Establishing the connection
channel.connect();
channelSftp = (ChannelSftp) channel;
try {
// Setting the folder location of the external system as configured
// to download the file from
channelSftp.cd("<sftp.input.folder.url>");
} catch (SftpException sftpException) {
System.out.println("Failed to change the directory in sftp.");
}
// Listing all the .csv file(s) specific to the source system, event type (download) and locale code
Vector<ChannelSftp.LsEntry> lsEntries = channelSftp.ls(
new StringBuilder("*").append("<sys.code>").append("*").append(event)
.append("*").append(locale).append("*").append(".csv").toString());
// Validating if files exist to process the request further
if (lsEntries.isEmpty()) {
System.out.println("No file exist in the specified sftp folder location.");
}
// Iterating the list of entries to download the file(s) from the sftp
for (ChannelSftp.LsEntry entry : lsEntries) {
try {
// Downloading the specified file from the sftp to the specified folder path
channelSftp.get(entry.getFilename(), new StringBuilder(folder)
.append(File.separator).append(entry.getFilename()).toString());
} catch (SftpException sftpException) {
System.out.println("Failed to download the file the sftp folder location.");
}
}
// Iterating the list of entries to delete the file(s) from the sftp
for (ChannelSftp.LsEntry entry : lsEntries) {
try {
// Deleting the specified file from the sftp
channelSftp.rm(entry.getFilename());
} catch (SftpException sftpException) {
System.out.println("Failed to delete the file from the sftp folder location.");
}
}
} catch (Exception exception) {
System.out.println("Failed to download the file(s) from SFTP.");
} finally {
// Validating if channel sftp is not null to exit
if (channelSftp != null) {
channelSftp.exit();
}
// Validating if channel is not null to disconnect
if (channel != null) {
channel.disconnect();
}
// Validating if session instance is not null to disconnect
if (session != null) {
session.disconnect();
}
}
}
}
I fixed in this way:
Vector<ChannelSftp.LsEntry> files = sftp.ls(remotePath);
String remotePath = properties.getFtpPath();
Vector<ChannelSftp.LsEntry> files = sftp.ls(remotePath);
for (ChannelSftp.LsEntry entry : files) {
InputStream stream = sftp.get(remotePath + "/" + entry.getFilename());
// Your business code here
}
Where remotePath is the remote SFTP folder name.
I am trying to connect to an openfire server using smack API, I am unable to do so.
Here is the code:
public class Tests{
public static void main( String[] args ) {
System.out.println("Starting IM client");
// gtalk requires this or your messages bounce back as errors
ConnectionConfiguration connConfig = new ConnectionConfiguration("localhost", 5222);
XMPPConnection connection = new XMPPConnection(connConfig);
try {
connection.connect();
System.out.println("Connected to " + connection.getHost());
} catch (XMPPException ex) {
//ex.printStackTrace();
System.out.println("Failed to connect to " + connection.getHost());
System.exit(1);
}
try {
connection.login("test#example.com", "setup1");
System.out.println("Logged in as " + connection.getUser());
Presence presence = new Presence(Presence.Type.available);
connection.sendPacket(presence);
} catch (XMPPException ex) {
//ex.printStackTrace();
System.out.println("Failed to log in as " + connection.getUser());
System.exit(1);
}
connection.disconnect();
}
}
The following is the output:
Starting IM client
Connected to localhost
Failed to log in as null
It seems to connect to the server but can't log in.
connection.login("test#example.com", "setup1");
You definitely shouldn't be logging in to example.com domain if your server is started on localhost.
Try just:
connection.login("test", "setup1");
But remember that to be able to login, you need to have a valid username and password. That means you have to create user "test" with password "setup1" on your server.