Advertisement
Guest User

Untitled

a guest
Apr 19th, 2017
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 14.90 KB | None | 0 0
  1. import org.apache.commons.net.PrintCommandListener;
  2. import org.apache.commons.net.ftp.*;
  3.  
  4. import javax.swing.*;
  5. import javax.swing.table.AbstractTableModel;
  6. import javax.swing.text.DefaultCaret;
  7. import java.awt.*;
  8. import java.awt.event.*;
  9. import java.io.*;
  10. import java.nio.ByteBuffer;
  11. import java.nio.CharBuffer;
  12. import java.nio.charset.Charset;
  13. import java.nio.charset.CharsetDecoder;
  14.  
  15. class MyTableModel extends AbstractTableModel {
  16.     private String[] columnNames = {"Name",
  17.             "Size",
  18.             "Last modified"};
  19.     private Object[][] data = {};
  20.  
  21.     MyTableModel() {
  22.     }
  23.  
  24.     MyTableModel(Object[][] data) {
  25.         this.data = data;
  26.     }
  27.  
  28.     public int getColumnCount() {
  29.         return columnNames.length;
  30.     }
  31.  
  32.     public int getRowCount() {
  33.         return data.length;
  34.     }
  35.  
  36.     public String getColumnName(int col) {
  37.         return columnNames[col];
  38.     }
  39.  
  40.     public Object getValueAt(int row, int col) {
  41.         return data[row][col];
  42.     }
  43.  
  44.     public Class getColumnClass(int c) {
  45.         return getValueAt(0, c).getClass();
  46.     }
  47.  
  48.     public boolean isCellEditable(int row, int col) {
  49.         return false;
  50.     }
  51. }
  52.  
  53. public class FTPClient {
  54.     private String FTPADDR = "localhost";
  55.     private String username = "demo";
  56.     private String password = "";
  57.     private String localPath = "C://ftptest";
  58.     private JTextArea logArea = null;
  59.     private JTable table = null;
  60.     private boolean connected = false;
  61.     private boolean downloading = false;
  62.     private final int NAME = 0;
  63.     private final int SIZE = 1;
  64.     private final int LASTMODIFIED = 2;
  65.     private final int COUNT = 3;
  66.  
  67.     private static class TextAreaOutputStream extends OutputStream {
  68.         private JTextArea textArea;
  69.         private CharsetDecoder decoder;
  70.  
  71.         TextAreaOutputStream(JTextArea textArea) {
  72.             this.textArea = textArea;
  73.             this.decoder = Charset.defaultCharset().newDecoder();
  74.         }
  75.  
  76.         @Override
  77.         public void write(byte b[]) throws IOException {
  78.             write(b, 0, b.length);
  79.         }
  80.  
  81.         @Override
  82.         public void write(byte b[], int off, int len) throws IOException {
  83.             CharBuffer charBuffer = decoder.decode(ByteBuffer.wrap(b, off, len));
  84.             textArea.append(charBuffer.toString());
  85.         }
  86.  
  87.         public void write(int b) throws IOException {
  88.             CharBuffer charBuffer = decoder.decode(ByteBuffer.wrap(new byte[]{(byte) b}));
  89.             textArea.append(charBuffer.toString());
  90.         }
  91.     }
  92.  
  93.     private org.apache.commons.net.ftp.FTPClient ftp = null;
  94.  
  95.     public static void main(String[] args) {
  96.         new FTPClient();
  97.     }
  98.  
  99.     private FTPClient() {
  100.         EventQueue.invokeLater(() -> {
  101.             try {
  102.                 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
  103.             } catch (Exception ex) {
  104.                 System.out.println("Exception caught:");
  105.                 System.out.println(ex.toString());
  106.                 ex.printStackTrace();
  107.             }
  108.             JFrame frame = new JFrame("FTP Client 1.0");
  109.             frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  110.             frame.setLayout(new BorderLayout());
  111.             frame.add(new LayoutPane());
  112.             frame.pack();
  113.             frame.setResizable(false);
  114.             frame.setLocationRelativeTo(null);
  115.             frame.setVisible(true);
  116.             ftp = new org.apache.commons.net.ftp.FTPClient();
  117.             ftp.setAutodetectUTF8(true);
  118.             ftp.setControlEncoding("UTF-8");
  119.             ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
  120.         });
  121.     }
  122.  
  123.     private class LayoutPane extends JPanel {
  124.  
  125.         private LayoutPane() {
  126.             JButton button = new JButton("Connect");
  127.             button.setPreferredSize(new Dimension(90, 22));
  128.             JButton dlButton = new JButton("Download");
  129.             dlButton.setPreferredSize(new Dimension(90, 22));
  130.             dlButton.setEnabled(false);
  131.             JLabel addressLabel = new JLabel("FTP Server:");
  132.             JLabel sizeLabel = new JLabel("Size of downloading files will be smaller than");
  133.             JLabel usernameLabel = new JLabel("Username:");
  134.             JLabel passwordLabel = new JLabel("Password:");
  135.             JLabel localPathLabel = new JLabel("Local path:");
  136.             JTextField addressField = new JTextField("localhost", 20);
  137.             JTextField sizeField = new JTextField("1000", 6);
  138.             JTextField usernameField = new JTextField(username, 9);
  139.             JTextField passwordField = new JTextField(password, 9);
  140.             JTextField localPathField = new JTextField(localPath, 20);
  141.             setLayout(new GridBagLayout());
  142.  
  143.             JPanel paneTop = new JPanel(new GridBagLayout());
  144.             JPanel paneMid = new JPanel(new GridBagLayout());
  145.             JPanel paneBottomMid = new JPanel(new GridBagLayout());
  146.             JPanel paneBot = new JPanel(new GridBagLayout());
  147.  
  148.             GridBagConstraints gbc = new GridBagConstraints();
  149.             gbc.gridx = 0;
  150.             gbc.gridy = 0;
  151.             gbc.insets = new Insets(2, 2, 2, 2);
  152.             gbc.fill = GridBagConstraints.HORIZONTAL;
  153.  
  154.             gbc.anchor = GridBagConstraints.WEST;
  155.             paneTop.add(addressLabel, gbc);
  156.             gbc.gridx++;
  157.             paneTop.add(addressField, gbc);
  158.             gbc.gridx++;
  159.             paneTop.add(usernameLabel, gbc);
  160.             gbc.gridx++;
  161.             paneTop.add(usernameField, gbc);
  162.             gbc.gridx++;
  163.             paneTop.add(passwordLabel, gbc);
  164.             gbc.gridx++;
  165.             paneTop.add(passwordField, gbc);
  166.             gbc.gridx++;
  167.             gbc.anchor = GridBagConstraints.EAST;
  168.             paneTop.add(button, gbc);
  169.             gbc.gridx = 0;
  170.             gbc.gridy = 0;
  171.             gbc.anchor = GridBagConstraints.NORTH;
  172.             add(paneTop, gbc);
  173.             gbc.gridx = 0;
  174.             gbc.gridy = 0;
  175.             table = new JTable(new MyTableModel());
  176.             gbc.fill = GridBagConstraints.BOTH;
  177.             JScrollPane scrollTable = new JScrollPane(table);
  178.             scrollTable.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
  179.             gbc.weightx = 1;
  180.             gbc.weighty = 1;
  181.             paneMid.add(scrollTable, gbc);
  182.             gbc.weightx = 0;
  183.             gbc.weighty = 0;
  184.             gbc.gridy++;
  185.             gbc.fill = GridBagConstraints.HORIZONTAL;
  186.             gbc.gridy = 2;
  187.             add(paneMid, gbc);
  188.             gbc.gridx = 0;
  189.             gbc.gridy = 0;
  190.             gbc.anchor = GridBagConstraints.SOUTH;
  191.             paneBottomMid.add(localPathLabel, gbc);
  192.             gbc.gridx++;
  193.             paneBottomMid.add(localPathField, gbc);
  194.             gbc.gridx++;
  195.             paneBottomMid.add(sizeLabel, gbc);
  196.             gbc.gridx++;
  197.             paneBottomMid.add(sizeField, gbc);
  198.             gbc.gridx++;
  199.             paneBottomMid.add(dlButton, gbc);
  200.             gbc.gridx = 0;
  201.             gbc.gridy = 3;
  202.             add(paneBottomMid, gbc);
  203.             gbc.gridx = 0;
  204.             gbc.gridy = 0;
  205.             gbc.fill = GridBagConstraints.BOTH;
  206.             logArea = new JTextArea(8, 40);
  207.             logArea.setFont(new Font("Consolas", Font.PLAIN, 12));
  208.             logArea.setEditable(false);
  209.             PrintStream ps = new PrintStream(new BufferedOutputStream((new TextAreaOutputStream(logArea))));
  210.             System.setOut(ps);
  211.             JScrollPane scrollLog = new JScrollPane(logArea);
  212.             DefaultCaret caret = (DefaultCaret) logArea.getCaret();
  213.             caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
  214.             scrollLog.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
  215.             gbc.weightx = 1;
  216.             gbc.weighty = 1;
  217.             paneBot.add(scrollLog, gbc);
  218.             gbc.gridy = 4;
  219.             add(paneBot, gbc);
  220.             gbc.fill = GridBagConstraints.BOTH;
  221.             gbc.gridx = 0;
  222.             gbc.gridy = 0;
  223.             gbc.weightx = 0;
  224.             gbc.weighty = 0;
  225.             System.out.println("HEY");
  226.  
  227.             button.addActionListener(e -> {
  228.                 if (!connected) {
  229.                     connected = true;
  230.                     FTPADDR = addressField.getText();
  231.                     username = usernameField.getText();
  232.                     password = passwordField.getText();
  233.                     addressField.setEditable(false);
  234.                     usernameField.setEditable(false);
  235.                     passwordField.setEditable(false);
  236.                     button.setText("Disconnect");
  237.                     dlButton.setEnabled(true);
  238.                     new Thread(() -> {
  239.                         try {
  240.                             logArea.setText("");
  241.                             ftp.connect(FTPADDR);
  242.                             ftp.setFileType(FTP.BINARY_FILE_TYPE);
  243.                             ftp.enterLocalPassiveMode();
  244.                             ftp.login(username, password);
  245.                             int reply = ftp.getReplyCode();
  246.                             if (!FTPReply.isPositiveCompletion(reply)) {
  247.                                 throw new Exception("Can't connect exception");
  248.                             }
  249.                             FTPFile[] list = ftp.listFiles();
  250.                             getFileTable(list);
  251.                         } catch (Exception e1) {
  252.                             disconnect();
  253.                             e1.printStackTrace();
  254.                             System.out.println("Exception caught:");
  255.                             System.out.println(e1.toString());
  256.                             connected = false;
  257.                             button.setText("Connect");
  258.                             dlButton.setEnabled(false);
  259.                             addressField.setEditable(true);
  260.                             usernameField.setEditable(true);
  261.                             passwordField.setEditable(true);
  262.                         }
  263.                     }).start();
  264.                 } else {
  265.                     connected = false;
  266.                     new Thread(FTPClient.this::disconnect).start();
  267.                     button.setText("Connect");
  268.                     dlButton.setEnabled(false);
  269.                     addressField.setEditable(true);
  270.                     usernameField.setEditable(true);
  271.                     passwordField.setEditable(true);
  272.                 }
  273.             });
  274.  
  275.             dlButton.addActionListener(e -> new Thread(() -> {
  276.                 if (!downloading) {
  277.                     sizeField.setEnabled(false);
  278.                     localPathField.setEnabled(false);
  279.                     downloading = true;
  280.                     try {
  281.                         localPath = localPathField.getText();
  282.                         downloadFiles(".", Integer.parseInt(sizeField.getText()));
  283.                         downloading = false;
  284.                     } catch (Exception e1) {
  285.                         System.out.println("Exception caught:");
  286.                         System.out.println(e1.toString());
  287.                     }
  288.                     sizeField.setEnabled(true);
  289.                     localPathField.setEnabled(true);
  290.                 } else {
  291.                     downloading = false;
  292.                     sizeField.setEnabled(true);
  293.                     localPathField.setEnabled(true);
  294.                 }
  295.             }).start());
  296.             table.addKeyListener(new KeyAdapter() {
  297.                 @Override
  298.                 public void keyPressed(KeyEvent e) {
  299.                     int row = table.getSelectedRow();
  300.                     if (e.getKeyCode() == KeyEvent.VK_ENTER && (table.getValueAt(row, SIZE) instanceof String)) {
  301.                         getFileTable(changeDir(table.getValueAt(table.getSelectedRow(), NAME).toString()));
  302.                     }
  303.                 }
  304.             });
  305.             table.addMouseListener(new MouseAdapter() {
  306.                 public void mousePressed(MouseEvent me) {
  307.                     JTable table = (JTable) me.getSource();
  308.                     Point p = me.getPoint();
  309.                     int row = table.rowAtPoint(p);
  310.                     if (me.getClickCount() == 2 && row != -1 && (table.getValueAt(row, SIZE) instanceof String)) {
  311.                         getFileTable(changeDir(table.getValueAt(row, NAME).toString()));
  312.                     }
  313.                 }
  314.             });
  315.         }
  316.     }
  317.  
  318.     private FTPFile[] changeDir(String pathname) {
  319.         FTPFile[] files;
  320.         try {
  321.             if (!ftp.changeWorkingDirectory(pathname)) {
  322.                 throw new IOException("Can't change directory exception");
  323.             }
  324.             files = ftp.listFiles();
  325.         } catch (IOException e) {
  326.             System.out.println("Exception caught:");
  327.             System.out.println(e.toString());
  328.             files = null;
  329.         }
  330.         return files;
  331.     }
  332.  
  333.     private void downloadFiles(String remotePath, int limit) {
  334.         try {
  335.             String workDir = ftp.printWorkingDirectory();
  336.             FTPFile[] list = ftp.listFiles(remotePath);
  337.             for (FTPFile aList : list) {
  338.                 String name = aList.getName();
  339.                 if (aList.isDirectory() && !name.equals(".") && !name.equals("..")) {
  340.                     downloadFiles(remotePath + "/" + name, limit);
  341.                 } else if (aList.getSize() <= limit) {
  342.                     File path = new File(localPath + workDir + remotePath);
  343.                     path.mkdirs();
  344.                     FileOutputStream fos = new FileOutputStream(localPath + workDir + remotePath + "/" + name);
  345.                     if (downloading) {
  346.                         ftp.retrieveFile(remotePath + "/" + name, fos);
  347.                     } else throw new IOException("Downloading aborted by user");
  348.                     fos.close();
  349.                 }
  350.             }
  351.         } catch (IOException e) {
  352.             System.out.println("Exception caught:");
  353.             System.out.println(e.toString());
  354.         }
  355.     }
  356.  
  357.     private void disconnect() {
  358.         try {
  359.             ftp.logout();
  360.             ftp.disconnect();
  361.             table.setModel(new MyTableModel());
  362.         } catch (IOException e) {
  363.             System.out.println("Exception caught:");
  364.             System.out.println(e.toString());
  365.         }
  366.     }
  367.  
  368.     private Object[][] getFileTable(FTPFile[] file) {
  369.         Object[][] data = new Object[file.length + 1][COUNT];
  370.         data[0][NAME] = "..";
  371.         data[0][SIZE] = "DIR";
  372.         data[0][LASTMODIFIED] = "";
  373.         for (int i = 1; i < file.length + 1; i++) {
  374.             data[i][NAME] = file[i - 1].getName();
  375.             data[i][SIZE] = (file[i - 1].isDirectory() ? "DIR" : file[i - 1].getSize());
  376.             data[i][LASTMODIFIED] = file[i - 1].getTimestamp().getTime().toString();
  377.         }
  378.         table.setModel(new MyTableModel(data));
  379.         table.revalidate();
  380.         return data;
  381.     }
  382. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement