Example usage for org.apache.commons.net.io CopyStreamAdapter CopyStreamAdapter

List of usage examples for org.apache.commons.net.io CopyStreamAdapter CopyStreamAdapter

Introduction

In this page you can find the example usage for org.apache.commons.net.io CopyStreamAdapter CopyStreamAdapter.

Prototype

public CopyStreamAdapter() 

Source Link

Document

Creates a new copyStreamAdapter.

Usage

From source file:com.peter.javaautoupdater.JavaAutoUpdater.java

public static void run(String ftpHost, int ftpPort, String ftpUsername, String ftpPassword,
        boolean isLocalPassiveMode, boolean isRemotePassiveMode, String basePath, String softwareName,
        String args[]) {//  w  w w. ja  v a 2 s.  c  om
    System.out.println("jarName=" + jarName);
    for (String arg : args) {
        if (arg.toLowerCase().trim().equals("-noautoupdate")) {
            return;
        }
    }
    JavaAutoUpdater.basePath = basePath;
    JavaAutoUpdater.softwareName = softwareName;
    JavaAutoUpdater.args = args;

    if (!jarName.endsWith(".jar") || jarName.startsWith("JavaAutoUpdater-")) {
        if (isDebug) {
            jarName = "test.jar";
        } else {
            return;
        }
    }
    JProgressBarDialog d = new JProgressBarDialog(new JFrame(), "Auto updater", true);

    d.progressBar.setIndeterminate(true);
    d.progressBar.setStringPainted(true);
    d.progressBar.setString("Updating");
    //      d.addCancelEventListener(this);
    Thread longRunningThread = new Thread() {
        public void run() {
            d.progressBar.setString("checking latest version");
            System.out.println("checking latest version");

            FTPClient ftp = new FTPClient();
            try {
                ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
                ftp.connect(ftpHost, ftpPort);
                int reply = ftp.getReplyCode();
                System.out.println("reply=" + reply + ", " + FTPReply.isPositiveCompletion(reply));
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftp.disconnect();
                    JOptionPane.showMessageDialog(null, "FTP server refused connection", "error",
                            JOptionPane.ERROR_MESSAGE);
                }
                d.progressBar.setString("connected to ftp");
                System.out.println("connected to ftp");
                boolean success = ftp.login(ftpUsername, ftpPassword);
                if (!success) {
                    ftp.disconnect();
                    JOptionPane.showMessageDialog(null, "FTP login fail, can't update software", "error",
                            JOptionPane.ERROR_MESSAGE);
                }
                if (isLocalPassiveMode) {
                    ftp.enterLocalPassiveMode();
                }
                if (isRemotePassiveMode) {
                    ftp.enterRemotePassiveMode();
                }
                FTPFile[] ftpFiles = ftp.listFiles(basePath, new FTPFileFilter() {
                    @Override
                    public boolean accept(FTPFile file) {
                        if (file.getName().startsWith(softwareName)) {
                            return true;
                        } else {
                            return false;
                        }
                    }
                });
                if (ftpFiles.length > 0) {
                    FTPFile targetFile = ftpFiles[ftpFiles.length - 1];
                    System.out.println("targetFile : " + targetFile.getName() + " , " + targetFile.getSize()
                            + "!=" + new File(jarName).length());
                    if (!targetFile.getName().equals(jarName)
                            || targetFile.getSize() != new File(jarName).length()) {
                        int r = JOptionPane.showConfirmDialog(null,
                                "Confirm to update to " + targetFile.getName(), "Question",
                                JOptionPane.YES_NO_OPTION);
                        if (r == JOptionPane.YES_OPTION) {
                            //ftp.enterRemotePassiveMode();
                            d.progressBar.setString("downloading " + targetFile.getName());
                            ftp.setFileType(FTP.BINARY_FILE_TYPE);
                            ftp.setFileTransferMode(FTP.BINARY_FILE_TYPE);

                            d.progressBar.setIndeterminate(false);
                            d.progressBar.setMaximum(100);
                            CopyStreamAdapter streamListener = new CopyStreamAdapter() {

                                @Override
                                public void bytesTransferred(long totalBytesTransferred, int bytesTransferred,
                                        long streamSize) {
                                    int percent = (int) (totalBytesTransferred * 100 / targetFile.getSize());
                                    d.progressBar.setValue(percent);
                                }
                            };
                            ftp.setCopyStreamListener(streamListener);
                            try (FileOutputStream fos = new FileOutputStream(targetFile.getName())) {
                                ftp.retrieveFile(basePath + "/" + targetFile.getName(), fos);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            d.progressBar.setString("restarting " + targetFile.getName());
                            restartApplication(targetFile.getName());
                        }
                    }

                }
                ftp.logout();
                ftp.disconnect();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    };
    d.thread = longRunningThread;
    d.setVisible(true);
}

From source file:de.thischwa.pmcms.tool.connection.ftp.FtpTransfer.java

/**
 * Uploads a 'file' with the content of the InputStream and the name 'name' to the current dir of FTPClient.
 * If the 'file' exists, it will be deleted before.
 *
 * @throws ConnectionRunningException//from  www  .  j a  va  2s  . c  o m
 */
private void uploadToCurrentDir(final String name, final InputStream in) throws ConnectionRunningException {
    // TODO implement the server reconnect here!!
    OutputStream serverOut = null;
    try {
        // 1. check, if target file exists and delete it
        FTPFile serverFile = getByName(ftpClient.listFiles(), name);
        if (serverFile != null) {
            if (!ftpClient.deleteFile(name))
                throw new ConnectionRunningException("Couldn't delete existent file: " + name);
        }

        // 2. create the empty file 
        if (!ftpClient.storeFile(name, IOUtils.toInputStream("")))
            throw new ConnectionRunningException("Couldn't create and empty file for: " + name);

        // 3. copy stream
        serverOut = new BufferedOutputStream(ftpClient.storeFileStream(name), ftpClient.getBufferSize());
        Util.copyStream(in, serverOut, ftpClient.getBufferSize(), CopyStreamEvent.UNKNOWN_STREAM_SIZE,
                new CopyStreamAdapter() {
                    @Override
                    public void bytesTransferred(long totalBytesTransferred, int bytesTransferred,
                            long streamSize) {
                        progressAddBytes(bytesTransferred);
                    }
                });
        // not documented but necessary: flush and close the server stream !!!
        serverOut.flush();
        serverOut.close();
        if (!ftpClient.completePendingCommand()) {
            connectionManager.close();
            throw new ConnectionRunningException(
                    "[FTP] While getting/copying streams: " + ftpClient.getReplyString());
        }

    } catch (Exception e) {
        logger.error("[FTP] While getting/copying streams: " + e.getMessage(), e);
        if (!(e instanceof ConnectionException)) {
            connectionManager.close();
            throw new ConnectionRunningException("[FTP] While getting/copying streams: " + e.getMessage(), e);
        }
    } finally {
        IOUtils.closeQuietly(in);
        progressSetSubTaskMessage("");
    }
}

From source file:net.sf.webphotos.gui.util.FtpClient.java

/**
 * Construtor da classe. Prepara a interface de sincronizao. Configura o
 * sistema de sincronizao e confere o valor de enviarAltaResoluo para
 * enviar originais ou no. Seta os valores dos listeners de sincronizao
 * implementando os mtodos da interface Sync.
 *//*from   w w  w. j a v  a2s.c o m*/
public FtpClient() {
    cp = getContentPane();
    /**
     * Preparando a interface de sincronizao
     */
    retry = 3;
    try {
        //TODO: transformar este acesso em parmetro do sistema
        ftp = (Sync) ApplicationContextResource.getBean("syncObject");
        /**
         * Configurao do sistema de sincronizao
         */
        ftp.setSyncFolder(ftpRoot);
        enviarAltaResolucao = ftp.isEnviarAltaResolucao();
        ftp.loadSyncCache();
    } catch (Exception ex) {
        Util.log("[FtpClient.run]/ERRO: Inexperado.");
        log.error(ex);
        System.exit(1);
    }

    // ajusta o valor de enviarAltaResolucao
    if (enviarAltaResolucao == false) {
        this.setTitle("Transmisso FTP - Sem Enviar Originais");
    } else {
        this.setTitle("Transmisso FTP - Enviando Originais");
    }
    txtLog.setFont(new Font("courier", Font.PLAIN, 11));
    Util.setLoggingTextArea(txtLog);
    cp.setLayout(null);

    cp.add(lblArquivos);
    lblArquivos.setBounds(348, 3, 60, 18);

    cp.add(lblServidor);
    lblServidor.setBounds(8, 3, 340, 18);

    txtLog.setWrapStyleWord(true);
    txtLog.setLineWrap(true);
    cp.add(scrLog);
    scrLog.setBounds(8, 127, 400, 70);

    modeloTabela = new FTPTabelModel(ftp.getListaArquivos());
    tabela = new JTable(modeloTabela);

    cp.add(tabela);
    scrTabela = new JScrollPane(tabela);
    cp.add(scrTabela);
    scrTabela.setBounds(8, 20, 400, 100);
    cp.validate();

    // barraArquivoAtual, kbytes, botao
    cp.add(barraArquivoAtual);
    barraArquivoAtual.setStringPainted(true);
    barraArquivoAtual.setBounds(8, 235, 234, 18);
    barraArquivoAtual.setToolTipText("Progresso do arquivo atual");

    cp.add(lblKbytesArquivoAtual);
    lblKbytesArquivoAtual.setBounds(246, 235, 58, 18);

    // barra, kbytes, botao
    cp.add(barra);
    barra.setStringPainted(true);
    barra.setBounds(8, 205, 234, 18);
    barra.setToolTipText("Progresso total");

    cp.add(lblKbytes);
    lblKbytes.setBounds(246, 205, 58, 18);

    cp.add(btFechar);
    btFechar.setBounds(308, 204, 100, 20);
    btFechar.setEnabled(false);

    this.setSize(420, 300);
    this.setResizable(false);
    this.setLocationRelativeTo(null);
    this.setDefaultCloseOperation(FtpClient.DO_NOTHING_ON_CLOSE);
    this.getContentPane().repaint();
    this.setVisible(true);

    modal = new Modal(this);
    this.addWindowFocusListener(modal);

    // ouvinte para o boto fechar
    btFechar.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            exit();
        }
    });

    // ouvinte para o fechamento convencional do JFrame
    // TODO: trocar o if para checagem de parmetro
    if (1 == 2) {
        addWindowListener(new java.awt.event.WindowAdapter() {
            @Override
            public void windowClosing(java.awt.event.WindowEvent evt) {
                exit();
            }
        });
    }

    ftp.setSyncListener(new SyncAdapter() {
        @Override
        public void connected(SyncEvent e) {
            lblServidor.setText(ftpHost + ":" + ftpPort + " / usurio: " + usuario);
        }

        @Override
        public void logonStarted(SyncEvent event) {
            // Autenticacao   
            if (!event.isRetrying()) {
                if (BancoImagem.getBancoImagem().getUserFTP() != null) {
                    // Vamos tentar conectar com a senha prpria de FTP
                    usuario = BancoImagem.getBancoImagem().getUserFTP();
                    senha = BancoImagem.getBancoImagem().getPasswordFTP();
                } else if (BancoImagem.getBancoImagem().getUser() != null) {
                    // Ou o mesmo usurio/senha do banco de dados
                    usuario = BancoImagem.getBancoImagem().getUser();
                    senha = BancoImagem.getBancoImagem().getPassword();
                } else {
                    showLogonDialog();
                }
            } else {
                showLogonDialog();
            }
            ftp.setUsuario(usuario);
            ftp.setSenha(senha);
        }

        @Override
        public void disconnected(SyncEvent e) {
            //TODO: repensar esse comando
            //Util.setLoggingTextArea(PainelWebFotos.getTxtLog());
            btFechar.setEnabled(true);
        }

        private void showLogonDialog() {
            // Ou requisitamos do usurio
            Login l = new Login("FTP " + ftpHost);
            removeWindowFocusListener(modal);
            l.show();
            addWindowFocusListener(modal);
            usuario = l.getUser();
            senha = l.getPassword();
        }
    });

    ftp.setCopyStreamListener(new CopyStreamAdapter() {
        @Override
        public void bytesTransferred(long totalBytesTransferred, int bytesTransferred, long streamSize) {
            barraArquivoAtual.setValue((int) totalBytesTransferred);
            lblKbytesArquivoAtual.setText(Math.round((float) totalBytesTransferred / 1024) + " Kb");
        }
    });
}

From source file:net.seedboxer.common.ftp.FtpUploaderCommons.java

private void storeFile(String fileName, InputStream ins, Long size, final FtpUploaderListener listener)
        throws IOException {

    checkAborted();//from www  . j av  a 2  s. co m

    OutputStream outs = ftpClient.storeFileStream(fileName);

    CopyStreamAdapter adapter = new CopyStreamAdapter() {
        @Override
        public void bytesTransferred(long totalBytesTransferred, int bytesTransferred, long streamSize) {
            if (listener != null) {
                listener.bytesTransferred(bytesTransferred);
            }
        }
    };

    try {
        copyStream(ins, outs, ftpClient.getBufferSize(), size, adapter);
    } finally {
        outs.close();
        ins.close();
    }

    try {
        if (!ftpClient.completePendingCommand()) {
            throw new FtpTransferException();
        }
    } catch (MalformedServerReplyException e) {
        if (!e.getMessage().toLowerCase().contains("ok")
                && !e.getMessage().toLowerCase().contains("complete")) {
            throw e;
        }
    }
}

From source file:fr.gael.dhus.olingo.v1.entity.Node.java

@Override
public ODataResponse getEntityMedia(ODataSingleProcessor processor) throws ODataException {
    initNode();/*  ww w  .  ja v  a2 s. c om*/
    if (hasStream()) {
        try {
            User u = V1Util.getCurrentUser();
            String user_name = (u == null ? null : u.getUsername());

            InputStream is = new BufferedInputStream(getStream());

            RegulatedInputStream.Builder builder = new RegulatedInputStream.Builder(is,
                    TrafficDirection.OUTBOUND);
            builder.userName(user_name);

            CopyStreamAdapter adapter = new CopyStreamAdapter();
            CopyStreamListener recorder = new DownloadActionRecordListener(this.getId(), this.getName(), u);
            CopyStreamListener closer = new DownloadStreamCloserListener(is);
            adapter.addCopyStreamListener(recorder);
            adapter.addCopyStreamListener(closer);
            builder.copyStreamListener(adapter);
            is = builder.build();

            String etag = getName() + "-" + getContentLength();

            // A priori Node never change, so the lastModified should be as
            // far as possible than today.
            long last_modified = System.currentTimeMillis() - ONE_YEAR_MS;

            // If node is not a data file, it cannot be downloaded and set to -1
            // As a stream exists, this control is probably obsolete.
            long content_length = getContentLength() == 0 ? -1 : getContentLength();

            return V1Util.prepareMediaResponse(etag, getName(), getContentType(), last_modified, content_length,
                    processor.getContext(), is);
        } catch (Exception e) {
            throw new ODataException("An exception occured while creating the stream for node " + getName(), e);
        }
    } else {
        throw new ODataException("No stream for node " + getName());
    }
}

From source file:fr.gael.dhus.olingo.v1.entity.Product.java

@Override
public ODataResponse getEntityMedia(ODataSingleProcessor processor) throws ODataException {
    ODataResponse rsp = null;/*from w  w  w .  j av  a2 s.  co m*/
    try {
        InputStream is = new BufferedInputStream(getInputStream());
        if (requiresControl()) {
            User u = V1Util.getCurrentUser();
            String user_name = (u == null ? null : u.getUsername());

            CopyStreamAdapter adapter = new CopyStreamAdapter();
            CopyStreamListener recorder = new DownloadActionRecordListener(product.getUuid(),
                    product.getIdentifier(), u);
            CopyStreamListener closer = new DownloadStreamCloserListener(is);
            adapter.addCopyStreamListener(recorder);
            adapter.addCopyStreamListener(closer);

            RegulatedInputStream.Builder builder = new RegulatedInputStream.Builder(is,
                    TrafficDirection.OUTBOUND);
            builder.userName(user_name);
            builder.copyStreamListener(adapter);

            is = builder.build();
        }

        // Computes ETag
        String etag = getChecksumValue();
        if (etag == null)
            etag = getId();
        String filename = new File(getDownloadablePath()).getName();
        // Prepare the HTTP header for stream transfer.
        rsp = V1Util.prepareMediaResponse(etag, filename, getContentType(), getCreationDate().getTime(),
                getContentLength(), processor.getContext(), is);
    } catch (Exception e) {
        String inner_message = ".";
        if (e.getMessage() != null)
            inner_message = " : " + e.getMessage();
        throw new ODataException("An exception occured while creating a stream" + inner_message, e);
    }
    return rsp;
}

From source file:com.atomicleopard.thundr.ftp.commons.FTPClient.java

/**
 * Merge two copystream listeners, either or both of which may be null.
 *
 * @param local the listener used by this class, may be null
 * @return a merged listener or a single listener or null
 * @since 3.0/*  ww w  . j a va2  s. c o m*/
 */
private CopyStreamListener __mergeListeners(CopyStreamListener local) {
    if (local == null) {
        return __copyStreamListener;
    }
    if (__copyStreamListener == null) {
        return local;
    }
    // Both are non-null
    CopyStreamAdapter merged = new CopyStreamAdapter();
    merged.addCopyStreamListener(local);
    merged.addCopyStreamListener(__copyStreamListener);
    return merged;
}

From source file:org.openconcerto.ftp.IFtp.java

public List<File> sync(File ldir, final CopyFileListener l, boolean forceUpload)
        throws IOException, NoSuchAlgorithmException {
    // there might be more than one md5 per file, if an error occured during the last sync()
    final ListMap<String, String> nameToMD5s = new ListMap<String, String>();
    final Map<String, FTPFile> ftpFiles = new HashMap<String, FTPFile>();
    final FTPFile[] listFiles = this.listFiles();
    if (listFiles == null) {
        System.out.println("IFtp.sync(): listFiles null :" + ldir.getName());
        return new ArrayList<File>();
    }//from   w  ww  . jav a2  s . c o m

    for (int i = 0; i < listFiles.length; i++) {
        FTPFile rFile = listFiles[i];
        // Oui ca arrive!
        if (rFile != null) {
            // some FTP servers returns 450 when NLST an empty directory, so use LIST
            final String name = rFile.getName();
            if (name != null) {
                if (name.endsWith(MD5_SUFFIX)) {
                    // originalName_a045d5e6.md5
                    final int underscore = name.length() - MD5_SUFFIX.length() - MD5_LENGTH - 1;
                    if (underscore >= 0) {
                        final String fname = name.substring(0, underscore);
                        final String md5 = name.substring(underscore + 1, underscore + 1 + MD5_LENGTH);
                        nameToMD5s.add(fname, md5);
                    }
                } else {
                    ftpFiles.put(name, rFile);
                }
            } else {
                System.out.println("IFtp.sync(): rFile.getName() null : [" + i + "]" + ldir.getName());
            }
        } else {
            System.out.println("IFtp.sync(): rFile null : [" + i + "]" + ldir.getName());
        }

    }

    final List<File> uploaded = new ArrayList<File>();
    final List<File> dirs = new ArrayList<File>();
    for (final File lFile : ldir.listFiles()) {
        if (lFile.isFile() && lFile.canRead()) {
            final String lName = lFile.getName();
            final List<String> md5List = nameToMD5s.getNonNull(lName);
            final String lMD5 = MessageDigestUtils.getMD5(lFile);
            boolean shouldUpload = true;
            if (!forceUpload && ftpFiles.containsKey(lFile.getName())) {
                final long lSize = lFile.length();
                final long rSize = ftpFiles.get(lFile.getName()).getSize();
                shouldUpload = lSize != rSize || !lMD5.equalsIgnoreCase(CollectionUtils.getSole(md5List));
            }
            if (shouldUpload) {
                // delete all previous
                for (final String md5 : md5List) {
                    this.deleteFile(md5ToName(lName, md5));
                }
                if (l != null) {
                    final long fileSize = lFile.length();
                    this.streamListeners.set(new CopyStreamAdapter() {
                        @Override
                        public void bytesTransferred(long totalBytesTransferred, int bytesTransferred,
                                long streamSize) {
                            l.bytesTransferred(lFile, totalBytesTransferred, bytesTransferred, fileSize);
                        }
                    });
                }
                this.storeFile(lName, new FileInputStream(lFile));
                // don't signal the MD5 file to the listener
                this.streamListeners.set(null);
                this.storeFile(md5ToName(lName, lMD5), new StringInputStream(lMD5 + "\t" + lName));
                uploaded.add(lFile);
            }
        } else if (lFile.isDirectory())
            dirs.add(lFile);
        // ignore other types of file
    }
    for (final File dir : dirs) {
        this.makeDirectory(dir.getName());
        if (!this.changeWorkingDirectory(dir.getName()))
            throw new IllegalStateException("could not cd to " + dir.getName());
        uploaded.addAll(this.sync(dir, l, forceUpload));
        this.changeToParentDirectory();
    }
    return uploaded;
}