Recent

Author Topic: LAMW - SFTP.java upload download fix  (Read 2212 times)

Mongkey

  • Sr. Member
  • ****
  • Posts: 433
LAMW - SFTP.java upload download fix
« on: May 20, 2023, 02:37:39 am »
upload procedure -> FAIL
sftp -> it has problem with download file, listing are OK.
« Last Edit: October 23, 2023, 11:47:52 pm by Mongkey »

Mongkey

  • Sr. Member
  • ****
  • Posts: 433
Re: LAMW - upload file failed (upload service, httpclient)
« Reply #1 on: October 01, 2023, 05:18:41 am »
Code: Java  [Select][+][-]
  1. package org.test.ftp;
  2.  
  3. import android.content.Context;
  4. import android.os.AsyncTask;
  5. import android.util.Log;
  6. import com.jcraft.jsch.Channel;
  7. import com.jcraft.jsch.ChannelExec;
  8. import com.jcraft.jsch.ChannelSftp;
  9. import com.jcraft.jsch.JSch;
  10. import com.jcraft.jsch.JSchException;
  11. import com.jcraft.jsch.Session;
  12. import com.jcraft.jsch.SftpATTRS;
  13. import com.jcraft.jsch.SftpException;
  14. import com.jcraft.jsch.ChannelSftp.LsEntry;
  15. import java.io.InputStream;
  16.  
  17. /*Draft java code by "Lazarus Android Module Wizard" [9/23/2019 19:05:10]*/
  18. /*https://github.com/jmpessoa/lazandroidmodulewizard*/
  19. /*jControl LAMW template*/
  20.  
  21. //ref. https://www.woolha.com/tutorials/java-connecting-to-sftp-uploading-downloading-files
  22. //https://ourcodeworld.com/articles/read/29/how-to-list-a-remote-path-with-jsch-sftp-in-android
  23. //https://stackoverflow.com/questions/41050989/basic-ssh-connection-via-jsch-on-android/43147951
  24. //https://stackoverflow.com/questions/14323661/simple-ssh-connect-with-jsch
  25. //https://www.woolha.com/tutorials/java-connecting-to-sftp-uploading-downloading-files
  26.  
  27. public class jSFTPClient /*extends ...*/ {
  28.  
  29.     private long pascalObj = 0;        //Pascal Object
  30.     private Controls controls = null; //Java/Pascal [events] Interface ...
  31.     private Context context = null;
  32.  
  33.     private String host = "test.rebex.net";
  34.     private int port = 22;
  35.     private Session session = null;
  36.  
  37.     private String identityKey = "";//if the FTP server requires certificate
  38.  
  39.     private String username = ""; //demo
  40.     private String password = "";  //password
  41.  
  42.     private boolean isConnected = false;
  43.  
  44.     //GUIDELINE: please, preferentially, init all yours params names with "_", ex: int _flag, String _hello ...
  45.  
  46.     public jSFTPClient(Controls _ctrls, long _Self) { //Add more others news "_xxx" params if needed!
  47.         //super(_ctrls.activity);
  48.         context = _ctrls.activity;
  49.         pascalObj = _Self;
  50.         controls = _ctrls;
  51.     }
  52.  
  53.     public void jFree() {
  54.         //free local objects...
  55.         if (session != null) {
  56.             session.disconnect();
  57.         }
  58.     }
  59.  
  60.     //write others [public] methods code here......
  61.     //GUIDELINE: please, preferentially, init all yours params names with "_", ex: int _flag, String _hello ...
  62.  
  63.     public boolean connect() throws JSchException {
  64.         JSch jsch = new JSch();
  65.         boolean res = false;
  66.         //if the FTP server requires certificate
  67.         if ( !identityKey.equals("") ) {
  68.             jsch.addIdentity(identityKey);
  69.         }
  70.         if (username.equals("")) {
  71.             session = jsch.getSession(host);
  72.         } else { //if the FTP server requires username/password
  73.             session = jsch.getSession(username, host, port);
  74.             session.setPassword(password);
  75.         }
  76.         session.setConfig("StrictHostKeyChecking", "no");
  77.         session.connect();
  78.         isConnected = true;
  79.         return isConnected;
  80.     }
  81.  
  82.     public boolean upload(String source, String destination) throws JSchException, SftpException {
  83.         boolean res = false;
  84.         if (session == null) return res;
  85.         Channel channel = session.openChannel("sftp");
  86.         channel.connect();
  87.         ChannelSftp sftpChannel = (ChannelSftp) channel;
  88.         String  ss = destination;
  89.         String[] arr = ss.split("/");
  90.         String pathfile = arr[arr.length-2];
  91.         //System.out.println("folder:"+pathfile);
  92.  
  93.         sftpChannel.cd(pathfile);
  94.         sftpChannel.put(source, destination);
  95.         res = true;
  96.         sftpChannel.exit();
  97.         return res;
  98.     }
  99.  
  100.     public boolean download(String source, String destination) throws JSchException, SftpException {
  101.         boolean res = false;
  102.         if (session == null) return res;
  103.         Channel channel = session.openChannel("sftp");
  104.         channel.connect();
  105.         ChannelSftp sftpChannel = (ChannelSftp) channel;
  106.         String  ss = source;
  107.         String[] arr = ss.split("/");
  108.         String pathfile = arr[arr.length-2];
  109.         //System.out.println("folder:"+pathfile);
  110.  
  111.         sftpChannel.cd(pathfile);
  112.         sftpChannel.get(source, destination);
  113.         res = true;
  114.         sftpChannel.exit();
  115.         return res;
  116.     }
  117.  
  118.     public void Disconnect() {
  119.         if (session != null) {
  120.             session.disconnect();
  121.         }
  122.     }
  123.  
  124.     public void SetHost(String _host) {
  125.         host = _host;
  126.     }
  127.  
  128.     public void SetPort(int _port) {
  129.         port = _port;
  130.     }
  131.  
  132.     public void SetIdentityCertificateKey(String _certificateKey) {
  133.         identityKey = _certificateKey;//if the FTP server requires certificate
  134.     }
  135.  
  136.     public void SetPassword(String _password) {
  137.         password = _password;
  138.     }
  139.  
  140.     public void SetUsername(String _username) {
  141.        username = _username;
  142.     }
  143.  
  144.     public void Connect() {
  145.        new ConnectTask().execute();
  146.     }
  147.  
  148.     //Params,Progress,Result
  149.     class ConnectTask extends AsyncTask<Void,Void,Boolean> {
  150.  
  151.         @Override
  152.         protected Boolean doInBackground(Void... p) {
  153.  
  154.             boolean res = false;
  155.             try {
  156.                 res = connect();
  157.             } catch (JSchException e) {
  158.                 res = false;
  159.                 e.printStackTrace();
  160.             }
  161.             return res;
  162.         }
  163.         @Override
  164.         protected void onPostExecute(Boolean conn){
  165.             controls.pOnSFTPClientTryConnect(pascalObj, (boolean)conn);
  166.         }
  167.     }
  168.  
  169.     public void Download(String _url, String saveToLocal) {
  170.        new AsyncUpOrDownTask(_url,saveToLocal).execute(0);
  171.     }
  172.  
  173.     public void Upload(String _fromLocal, String _url) {
  174.         new AsyncUpOrDownTask(_fromLocal,_url).execute(1);
  175.     }
  176.  
  177.     //Parâmetros,Progresso,Resultado
  178.     class AsyncUpOrDownTask extends AsyncTask<Integer,Integer,Boolean> {
  179.  
  180.         public String source;
  181.         public String destination;
  182.         public int task;
  183.  
  184.         public AsyncUpOrDownTask(String _source, String _destination) {
  185.             source = _source;
  186.             destination = _destination;
  187.         }
  188.  
  189.         @Override
  190.         protected Boolean doInBackground(Integer... p) {
  191.  
  192.             boolean success= false;
  193.  
  194.             try {
  195.                 if (p[0] == 0) {
  196.                     task = 0;
  197.                     success = download(source, destination);
  198.                 }
  199.                 else {
  200.                     task = 1;
  201.                     success = upload(source, destination);
  202.                 }
  203.  
  204.             } catch (JSchException e) {
  205.                 success = false;
  206.                 e.printStackTrace();
  207.             } catch (SftpException e) {
  208.                 success = false;
  209.                 e.printStackTrace();
  210.             }
  211.  
  212.             return success;
  213.         }
  214.  
  215.         protected void onProgressUpdate(Integer params){
  216.             //
  217.         }
  218.  
  219.         @Override
  220.         protected void onPostExecute(Boolean succ){
  221.             if (task == 0)
  222.                 controls.pOnSFTPClientDownloadFinished(pascalObj, destination, (boolean)succ);
  223.             else
  224.                 controls.pOnSFTPClientUploadFinished(pascalObj, destination, (boolean)succ);
  225.  
  226.         }
  227.     }
  228.  
  229.     public void ListFiles(String _remotePath) {
  230.            new AsyncListTask(_remotePath, 0).execute(_remotePath);
  231.     }
  232.  
  233.     //TODO
  234.     public void CountFiles(String _remotePath) {
  235.         new AsyncListTask(_remotePath, 1).execute(_remotePath);
  236.     }
  237.  
  238.     //Parâmetros,Progresso,Resultado
  239.     class AsyncListTask extends AsyncTask<String,String, Integer> {
  240.  
  241.         public String directory;
  242.         public int task;
  243.  
  244.         public AsyncListTask(String _directory, int _task) {
  245.             directory = _directory;
  246.             task = _task;
  247.         }
  248.  
  249.         @Override
  250.         protected Integer doInBackground(String... path) {
  251.             int count =  0;
  252.  
  253.             try {
  254.                 Channel channel = session.openChannel("sftp");
  255.                 channel.connect();
  256.                 ChannelSftp sftp = (ChannelSftp) channel;
  257.  
  258.                 // Now that we have a channel, go to a directory first if we want .. you can give to the ls the path
  259.                 //ex "/pub/example"
  260.  
  261.                 // Get the content of the actual path using ls instruction or use the previous string of the cd instruction
  262.                 @SuppressWarnings("unchecked")
  263.                 java.util.Vector<LsEntry> flLst = sftp.ls(path[0]);  //  "/pub/example"
  264.                 int i = flLst.size();
  265.                     //get info of every folder/file/link
  266.                 for (int j = 0; j < i; j++) {
  267.                         LsEntry entry = flLst.get(j);
  268.                         SftpATTRS attr = entry.getAttrs();
  269.                         System.out.println(entry.getFilename());
  270.                         if (!attr.isDir()) {
  271.                             if (!attr.isLink()) {
  272.                                 count = count + 1;
  273.                                 if (task == 0) {
  274.                                     publishProgress(path[0], entry.getFilename(), String.valueOf(attr.getSize()));
  275.                                 }
  276.                             }
  277.                         }
  278.                 }
  279.                 channel.disconnect();
  280.                 //session.disconnect();
  281.             } catch (JSchException e) {
  282.                 System.out.println(e.getMessage().toString());
  283.                 e.printStackTrace();
  284.             } catch (SftpException e) {
  285.                 System.out.println(e.getMessage().toString());
  286.                 e.printStackTrace();
  287.             }
  288.             return count;
  289.         }
  290.  
  291.         protected void onProgressUpdate(String... params){
  292.             controls.pOnSFTPClientListing(pascalObj, params[0], params[1], Integer.parseInt(params[2]));
  293.         }
  294.  
  295.         @Override
  296.         protected void onPostExecute(Integer count){
  297.             controls.pOnSFTPClientListed(pascalObj, (int)count);
  298.         }
  299.  
  300.     }
  301.  
  302.     //TODO
  303.     public void ExecCommand(String _command) {
  304.  
  305.         String host="ssh.journaldev.com";
  306.         String user="sshuser";
  307.         String password="sshpwd";
  308.         String command1="ls -ltr";
  309.  
  310.         try{
  311.             java.util.Properties config = new java.util.Properties();
  312.             config.put("StrictHostKeyChecking", "no");
  313.             JSch jsch = new JSch();
  314.             Session session=jsch.getSession(user, host, 22);
  315.             session.setPassword(password);
  316.             session.setConfig(config);
  317.             session.connect();
  318.             System.out.println("Connected");
  319.  
  320.             Channel channel=session.openChannel("exec");
  321.             ((ChannelExec)channel).setCommand(command1);
  322.             channel.setInputStream(null);
  323.             ((ChannelExec)channel).setErrStream(System.err);
  324.  
  325.             InputStream in=channel.getInputStream();
  326.             channel.connect();
  327.             byte[] tmp=new byte[1024];
  328.             while(true){
  329.                 while(in.available()>0){
  330.                     int i=in.read(tmp, 0, 1024);
  331.                     if(i<0)break;
  332.                     System.out.print(new String(tmp, 0, i));
  333.                     Log.i("TAGT", new String(tmp, 0, i));
  334.                 }
  335.                 if(channel.isClosed()){
  336.                     System.out.println("exit-status: "+channel.getExitStatus());
  337.                     Log.i("TAGEX", "exit-status: "+channel.getExitStatus());
  338.                     break;
  339.                 }
  340.                 try{Thread.sleep(1000);}catch(Exception ee){}
  341.             }
  342.             channel.disconnect();
  343.             session.disconnect();
  344.             System.out.println("DONE");
  345.         }catch(Exception e){
  346.             e.printStackTrace();
  347.         }
  348.     }
  349.  
  350. }
  351.  

Mongkey

  • Sr. Member
  • ****
  • Posts: 433
Re: LAMW - upload file failed (upload service, httpclient)
« Reply #2 on: October 01, 2023, 05:20:23 am »
This one is working SFTP upload download event, make sure you are the owner of dir and file on the system file

Thank you!
« Last Edit: October 01, 2023, 05:22:17 am by Mongkey »

jmpessoa

  • Hero Member
  • *****
  • Posts: 2317
Re: LAMW - SFTP.java upload download fix
« Reply #3 on: October 24, 2023, 12:43:51 am »
Done!

Thank you!


Can you to point out for more source to commit ?
« Last Edit: October 24, 2023, 12:47:55 am by jmpessoa »
Lamw: Lazarus Android Module Wizard
https://github.com/jmpessoa/lazandroidmodulewizard

Mongkey

  • Sr. Member
  • ****
  • Posts: 433
Re: LAMW - SFTP.java upload download fix
« Reply #4 on: October 24, 2023, 09:38:39 am »

 

TinyPortal © 2005-2018