We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you two Citrix podcasts. Learn about 2020 trends and get answers to your biggest Citrix questions!Listen Now

x

Problems using sshtools.j2ssh.SftpClient, uploads only the first line of a file

Rinkle
Rinkle asked
on
Medium Priority
3,015 Views
Last Modified: 2012-05-06
Hi, im setting up a simple sFTP-Client wich send a file over to a remote server,
everything works great except that only the first line gets sent to the remote server...

Seems like the SFTPClient take \n as end of file :S

Does anyone know how to fix this? Im out of ideas :(
package se.cybercomgroup.pm.safe2go.payment.batchfile.sftp;
 
import java.io.*;
 
//import org.apache.log4j.Logger;
 
import com.sshtools.j2ssh.SftpClient;
import com.sshtools.j2ssh.SshClient;
import com.sshtools.j2ssh.authentication.AuthenticationProtocolState;
import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient;
 
/**
 * SSH-2 FTP-Client Class.
 *
 */
public class SFtp {
	
	// PRIVATE ATTRIBUTES ////////////////////////////////////////////////////////////////
	
	private static final Logger logger = Logger.getLogger(SFtp.class);
	
	private String sftpHostName;
	private String sftpPortnumber;
	private String sftpUsername;
	private String sftpPassword;
	
	private String filePath;
	
	private String sftHostKeyFilePath;
	
	// Null Instances
	private SshClient ssh;
	private SftpClient client;
	private PasswordAuthenticationClient pwdAuthClient;
	
	// RFPF = READ FROM PROPERTIES FILE
	private static String RFPF = SFtpAttr.SFTPCLIENT_ATTIR;
 
	// CONSTRUCTORS //////////////////////////////////////////////////////////////////////
	
	 /**
     * Creates a new SFTPClient instance.
     * @param sftpHostname the sFTP hostname
     * @param sftpPortnumber the sFTP portname
     * @param sftpUsername the sFTP username
     * @param sftpPassword the sFTP password
     * @param sftpAuthFilePath the sFTP HostKeyVerfication
     */
	public SFtp(String sftpHostname, String sftpPortnumber, String sftpUsername,
			String sftpPassword, String sftpHostKeyFilePath) {
		
		logger.info("##  Initializing SFTP-Client Attributes...");
		
		this.sftpHostName = sftpHostname;
		this.sftpPortnumber = sftpPortnumber;
		this.sftpUsername = sftpUsername;
		this.sftpPassword = sftpPassword;
		this.sftHostKeyFilePath = sftpHostKeyFilePath;
		
		//Read From .Properties-file if attributes == CONSTANT
		if (sftpHostname == RFPF){
			this.sftpHostName = getAttributeFromProperties(SFtpAttr.SFTP_HOSTENAME);
		}
		if (sftpPortnumber == RFPF){
			this.sftpPortnumber = getAttributeFromProperties(SFtpAttr.SFTP_PORTNUMBER);
		}
		if (sftpUsername == RFPF){
			this.sftpUsername = getAttributeFromProperties(SFtpAttr.SFTP_USERNAME);
		}
		if (sftpPassword == RFPF){
			this.sftpPassword = getAttributeFromProperties(SFtpAttr.SFTP_PASSWORD);
		}
		if (sftpHostKeyFilePath == RFPF){
			this.sftHostKeyFilePath = getAttributeFromProperties(
														SFtpAttr.SFTP_HOSTKEYAUTH_FILE);
		}
	}
	
	/**
     * Creates a new SFTPClient instance,
     * which doesn't use HostKeyVerfication.
     * 
     * @param sftpHostname the sFTP hostname
     * @param sftpPortnumber the sFTP portname
     * @param sftpUsername the sFTP username
     * @param sftpPassword the sFTP password
     */ 
	public SFtp(String sftpHostname, String sftpPortnumber, 
					String sftpUsername, String sftpPassword) {
			this(sftpHostname, sftpPortnumber, sftpUsername, sftpPassword, "NOAFREQ");
	}
 
	/**
	 * Creates a new SFTPClient instance,
	 * but reads all attributes from an .propertis-file.
	 * 
	 * IMPORTANT: READS FROM .PROPERTIES-FILE !!!
	 */
	public SFtp() {
		this(RFPF, RFPF, RFPF, RFPF, RFPF);
	}
	
 
	// PUBLIC METHODS ////////////////////////////////////////////////////////////////////
	
	public void open() throws Exception {
		ssh = new SshClient();
		ssh.connect(sftpHostName, Integer.valueOf(sftpPortnumber));
 
		//Authenticate Connection
		pwdAuthClient = new PasswordAuthenticationClient();
		pwdAuthClient.setUsername(sftpUsername);
		pwdAuthClient.setPassword(sftpPassword);
		
		int result = ssh.authenticate(pwdAuthClient);
		if(result != AuthenticationProtocolState.COMPLETE){
			String errorStr = "Login " + sftpUsername + ":" + sftpPassword + "@" + 
								sftpHostName + ":" + sftpPortnumber + " failed!!! ";
 
			logger.debug(errorStr);
			throw new Exception(errorStr);
		}
		
	}
	
	public void send(String filePath) throws IOException{
		//	  Open the SFTP channel
		client = ssh.openSftpClient();
		//    Send the file
		try { 
			client.put(filePath,"done.txt");
		} catch (Exception e) {
			logger.debug("Error sending " + filePath + " to " + sftpHostName, e);
		}
		//    disconnect
		client.quit();
	}
	
	public void disconnect () throws IOException{
		//client.quit();
		ssh.disconnect();
		ssh = null;
		
		logger.info(SftpLogger.generate());
		System.out.println(SftpLogger.generate());
	}
	
	// PRIVATE METHODS ///////////////////////////////////////////////////////////////////
	
	private String getAttributeFromProperties(String attributeName){
		String attribute = "";
		
		try {
			logger.info("Reading attribute \"" + attributeName + "\" from properties...");
			attribute = Safe2GoSFTPropertyHandler.getMandatoryProperty(attributeName);
 
		} catch (IOException e) {
			logger.debug("Unknown IoException when reading attribute! ", e);
		} catch (NoSuchFieldException e) {
			logger.debug("Attribute \"" + attributeName + "\" it NOT set! ", e);
		}
		
		return attribute;
	}
	
	// GLOBAL OVERIDES ///////////////////////////////////////////////////////////////////
	
	@Override
	protected void finalize() throws Throwable {
		super.finalize();
		if (ssh != null || client != null){
			logger.debug("disconnect() was never called! Calling disconnect...");
			disconnect();
		}
	}
	
	//////////////////////////////////////////////////////////////////////////////////////
	//																				MAIN
	//////////////////////////////////////////////////////////////////////////////////////
	public static void main(String[] args) throws Exception {
		if( args.length > 3) {
			System.out.println("\n   Usage: SFTP.[bat|sh] file_to_send");
			System.exit(0);
		}
		SFtp sftp = new SFtp();
		sftp.open();
		sftp.send("c:\\txt.txt");
		sftp.disconnect();
	}
}

Open in new window

Comment
Watch Question

Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
thats weird, and there are no errors?
CERTIFIED EXPERT
Top Expert 2016

Commented:
Try using a put call with InputStream as a parameter, rather than String

Author

Commented:
objects: Nope, none that i can see =/

CEHJ: On it, worth a try but still dont see why put(String str) woudn't work...
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
bit of a worry :)
we use commons net's ftp implementation without any problem, might want to give that try

Author

Commented:
objects: hmm... can i use commons net's ftp impl with ssh? :S please do tell more :)

Author

Commented:
This is so weird, i took a look at the source and cant find anything wrong there either...

http://www.docjar.com/html/api/com/sshtools/j2ssh/SftpClient.java.html

Anyone got an working SFTP example using this or other libs?
       private void transferFile(
           InputStream in, 
           OutputStream out,
           FileTransferProgress progress)
         throws IOException, TransferCancelledException 
       {
         try {
           long bytesSoFar = 0;
           byte[] buffer = new byte[BLOCKSIZE];
           int read;
           
           while ((read = in.read(buffer)) > -1) {
             if ((progress != null) && progress.isCancelled()) {
               throw new TransferCancelledException();
             }
             
             if (read > 0) {
               out.write(buffer, 0, read);
               
               //out.flush();
               bytesSoFar += read;
               
               if (progress != null) {
                 progress.progressed(bytesSoFar);
               }
             }
           }
         } 
         finally {
           try {
             in.close();
             out.close();
           } 
           catch (IOException ex) {
           }
         }
       }

Open in new window

Commented:
sorry for bumping: Might the problem be EOL diff?

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
CERTIFIED EXPERT
Top Expert 2016

Commented:
You shouldn't need to convert btw - just call ascii() on the client

Author

Commented:
Hmm, cool! I'll try that l8er :)

Author

Commented:
Hmm, cool! I'll try that l8er :)
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.