• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2880
  • Last Modified:

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

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

0
Rinkle
Asked:
Rinkle
  • 6
  • 2
  • 2
1 Solution
 
objectsCommented:
thats weird, and there are no errors?
0
 
CEHJCommented:
Try using a put call with InputStream as a parameter, rather than String
0
 
RinkleAuthor 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...
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

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

0
 
RinkleAuthor Commented:
objects: hmm... can i use commons net's ftp impl with ssh? :S please do tell more :)
0
 
RinkleAuthor 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

0
 
RinkleAuthor Commented:
sorry for bumping: Might the problem be EOL diff?
0
 
CEHJCommented:
You shouldn't need to convert btw - just call ascii() on the client
0
 
RinkleAuthor Commented:
Hmm, cool! I'll try that l8er :)
0
 
RinkleAuthor Commented:
Hmm, cool! I'll try that l8er :)
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 6
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now