Example usage for org.apache.commons.net.ftp FTPClient storeFile

List of usage examples for org.apache.commons.net.ftp FTPClient storeFile

Introduction

In this page you can find the example usage for org.apache.commons.net.ftp FTPClient storeFile.

Prototype

public boolean storeFile(String remote, InputStream local) throws IOException 

Source Link

Document

Stores a file on the server using the given name and taking input from the given InputStream.

Usage

From source file:org.wso2.carbon.connector.FileFtpOverProxyConnector.java

/**
 * Send file FTP over Proxy./*  ww w.  jav a 2s  . c  om*/
 *
 * @param messageContext The message context that is generated for processing the file.
 * @return true, if the FTP client tunnels over an HTTP proxy connection or stores a file on the server.
 *
 */
public boolean ftpOverHttpProxy(MessageContext messageContext) {
    String proxyHost = StringUtils
            .trim((String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.PROXY_HOST));
    String proxyPort = StringUtils
            .trim((String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.PROXY_PORT));
    String proxyUsername = StringUtils.trim(
            (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.PROXY_USERNAME));
    String proxyPassword = StringUtils.trim(
            (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.PROXY_PASSWORD));
    String ftpHost = StringUtils
            .trim((String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.FTP_SERVER));
    String ftpPort = StringUtils
            .trim((String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.FTP_PORT));
    String ftpUsername = StringUtils
            .trim((String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.FTP_USERNAME));
    String ftpPassword = StringUtils
            .trim((String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.FTP_PASSWORD));
    String keepAliveTimeout = StringUtils.trim(
            (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.KEEP_ALIVE_TIMEOUT));
    String controlKeepAliveReplyTimeout = StringUtils.trim((String) ConnectorUtils
            .lookupTemplateParamater(messageContext, FileConstants.CONTROL_KEEP_ALIVE_REPLY_TIMEOUT));
    String targetPath = StringUtils
            .trim((String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.TARGET_PATH));
    String targetFile = StringUtils
            .trim((String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.TARGET_FILE));
    String activeMode = StringUtils
            .trim((String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.ACTIVE_MODE));
    String fileType = StringUtils
            .trim((String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.FILE_TYPE));
    boolean activeModeParameter = false;

    if (StringUtils.isEmpty(keepAliveTimeout)) {
        keepAliveTimeout = FileConstants.DEFAULT_KEEP_ALIVE_TIMEOUT;
    }
    if (StringUtils.isEmpty(controlKeepAliveReplyTimeout)) {
        controlKeepAliveReplyTimeout = FileConstants.DEFAULT_CONTROL_KEEP_ALIVE_REPLY_TIMEOUT;
    }
    if (StringUtils.isNotEmpty(activeMode)) {
        activeModeParameter = Boolean.parseBoolean(activeMode);
    }

    InputStream inputStream = null;
    FTPClient ftp = new FTPClient();
    if (StringUtils.isNotEmpty(proxyHost) && StringUtils.isNotEmpty(proxyPort)
            && StringUtils.isNotEmpty(proxyUsername) && StringUtils.isNotEmpty(proxyPassword)) {
        ftp = new FTPHTTPClient(proxyHost, Integer.parseInt(proxyPort), proxyUsername, proxyPassword);
    }
    //Set the time to wait between sending control connection keep alive messages when processing file upload or
    // download (Zero (or less) disables).
    ftp.setControlKeepAliveTimeout(Long.parseLong(keepAliveTimeout));
    //Set how long to wait for control keep-alive message replies.(defaults to 1000 milliseconds.)
    ftp.setControlKeepAliveReplyTimeout(Integer.parseInt(controlKeepAliveReplyTimeout));
    try {
        int reply;
        int IntFtpPort = Integer.parseInt(ftpPort);
        if (IntFtpPort > 0) {
            ftp.connect(ftpHost, IntFtpPort);
        } else {
            ftp.connect(ftpHost);
        }
        if (log.isDebugEnabled()) {
            log.debug(" Connected to " + ftpHost + " on " + (IntFtpPort > 0 ? ftpPort : ftp.getDefaultPort()));
        }
        // After connection attempt, should check the reply code to verify success.
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            log.error("FTP ftpServer refused connection.");
        }
        if (!ftp.login(ftpUsername, ftpPassword)) {
            ftp.logout();
            throw new SynapseException("Error while login ftp server.");
        }
        setFileType(fileType, ftp);

        // Use passive mode as default because most of us are behind firewalls these days.
        if (activeModeParameter) {
            ftp.enterLocalActiveMode();
        } else {
            ftp.enterLocalPassiveMode();
        }
        inputStream = new ByteArrayInputStream(
                messageContext.getEnvelope().getBody().getFirstElement().toString().getBytes());
        if (StringUtils.isNotEmpty(targetPath)) {
            ftp.changeWorkingDirectory(targetPath);
            ftp.storeFile(targetFile, inputStream);
            if (log.isDebugEnabled()) {
                log.debug("Successfully FTP server transferred the File");
            }
        }
        // check that control connection is working
        if (log.isDebugEnabled()) {
            log.debug("The code received from the server." + ftp.noop());
        }
    } catch (IOException e) {
        throw new SynapseException("Could not connect to FTP Server", e);
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
                ftp.logout();
            } catch (IOException f) {
                log.error("Error while disconnecting/logging out ftp server");
            }
        }
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException f) {
                log.error("Error while closing inputStream");
            }
        }
    }
    return true;
}

From source file:org.wso2.iot.agent.services.FileUploadService.java

/**
 * File upload operation using an FTP client.
 *
 * @param operation       - operation object.
 * @param host            - host name.//  w  w  w.  j  av  a2 s  .  com
 * @param ftpUserName     - ftp user name.
 * @param ftpPassword     - ftp password.
 * @param uploadDirectory - ftp directory to upload file.
 * @param fileLocation    - local file location.
 * @param serverPort      - ftp port to connect.
 * @throws AndroidAgentException - AndroidAgent exception.
 */
private void uploadFileUsingFTPClient(Operation operation, String host, String ftpUserName, String ftpPassword,
        String uploadDirectory, String fileLocation, int serverPort) throws AndroidAgentException {
    FTPClient ftpClient = new FTPClient();
    String fileName = null;
    InputStream inputStream = null;
    String response;
    try {
        File file = new File(fileLocation);
        fileName = file.getName();
        ftpClient.connect(host, serverPort);
        ftpClient.enterLocalPassiveMode();
        ftpClient.login(ftpUserName, ftpPassword);
        inputStream = new FileInputStream(file);
        ftpClient.changeWorkingDirectory(uploadDirectory);
        if (ftpClient.storeFile(file.getName(), inputStream)) {
            response = "File uploaded from the device completed ( " + fileName + " ).";
            operation.setStatus(resources.getString(R.string.operation_value_completed));
        } else {
            response = "File uploaded from the device not completed ( " + fileName + " ).";
            operation.setStatus(resources.getString(R.string.operation_value_error));
        }
        operation.setOperationResponse(response);
    } catch (FTPConnectionClosedException e) {
        uploadFileUsingFTPSClient(operation, host, ftpUserName, ftpPassword, uploadDirectory, fileLocation,
                serverPort);
    } catch (IOException e) {
        handleOperationError(operation, fileTransferExceptionCause(e, fileName), e, resources);
    } finally {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.logout();
            } catch (IOException ignored) {
            }
        }
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
            } catch (IOException ignored) {
            }
        }
        cleanupStreams(inputStream, null, null, null, null, null, null, null);
    }
}

From source file:password.pwm.svc.telemetry.FtpTelemetrySender.java

private void ftpPut(final TelemetryPublishBean telemetryPublishBean) throws PwmUnrecoverableException {
    final FTPClient ftpClient;
    switch (settings.getFtpMode()) {
    case ftp:/*from   w  ww. jav  a2  s .  co  m*/
        ftpClient = new FTPClient();
        break;

    case ftps:
        ftpClient = new FTPSClient();
        break;

    default:
        JavaHelper.unhandledSwitchStatement(settings.getFtpMode());
        throw new UnsupportedOperationException();
    }

    // connect
    try {
        LOGGER.trace(SessionLabel.TELEMETRY_SESSION_LABEL,
                "establishing " + settings.getFtpMode() + " connection to " + settings.getHost());
        ftpClient.connect(settings.getHost());

        final int reply = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            disconnectFtpClient(ftpClient);
            final String msg = "error " + reply + " connecting to " + settings.getHost();
            throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_TELEMETRY_SEND_ERROR, msg));
        }

        LOGGER.trace(SessionLabel.TELEMETRY_SESSION_LABEL, "connected to " + settings.getHost());
    } catch (IOException e) {
        disconnectFtpClient(ftpClient);
        final String msg = "unable to connect to " + settings.getHost() + ", error: " + e.getMessage();
        throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_TELEMETRY_SEND_ERROR, msg));
    }

    // set modes
    try {
        ftpClient.enterLocalPassiveMode();
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        final int reply = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            disconnectFtpClient(ftpClient);
            final String msg = "error setting file type mode to binary, error=" + reply;
            throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_TELEMETRY_SEND_ERROR, msg));
        }
    } catch (IOException e) {
        disconnectFtpClient(ftpClient);
        final String msg = "unable to connect to " + settings.getHost() + ", error: " + e.getMessage();
        throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_TELEMETRY_SEND_ERROR, msg));
    }

    // authenticate
    try {
        ftpClient.login(settings.getUsername(), settings.getPassword());

        final int reply = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            disconnectFtpClient(ftpClient);
            final String msg = "error authenticating as " + settings.getUsername() + " to " + settings.getHost()
                    + ", error=" + reply;
            throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_TELEMETRY_SEND_ERROR, msg));
        }

        LOGGER.trace(SessionLabel.TELEMETRY_SESSION_LABEL,
                "authenticated to " + settings.getHost() + " as " + settings.getUsername());
    } catch (IOException e) {
        disconnectFtpClient(ftpClient);
        final String msg = "error authenticating as " + settings.getUsername() + " to " + settings.getHost()
                + ", error: " + e.getMessage();
        throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_TELEMETRY_SEND_ERROR, msg));
    }

    // upload
    try {
        final String filePath = settings.getPath() + "/" + telemetryPublishBean.getId() + ".zip";
        final byte[] fileBytes = dataToJsonZipFile(telemetryPublishBean);
        final ByteArrayInputStream fileStream = new ByteArrayInputStream(fileBytes);

        LOGGER.trace(SessionLabel.TELEMETRY_SESSION_LABEL,
                "preparing to transfer " + fileBytes.length + " bytes to file path " + filePath);

        final Instant startTime = Instant.now();
        ftpClient.storeFile(filePath, fileStream);

        final int reply = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            disconnectFtpClient(ftpClient);
            final String msg = "error uploading file  to " + settings.getHost() + ", error=" + reply;
            throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_TELEMETRY_SEND_ERROR, msg));
        }

        LOGGER.trace(SessionLabel.TELEMETRY_SESSION_LABEL, "completed transfer of " + fileBytes.length + " in "
                + TimeDuration.compactFromCurrent(startTime));
    } catch (IOException e) {
        disconnectFtpClient(ftpClient);
        final String msg = "error uploading file  to " + settings.getHost() + ", error: " + e.getMessage();
        throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_TELEMETRY_SEND_ERROR, msg));
    }
}

From source file:Proiect.uploadFTP.java

public void actionFTP() {
    adressf.addCaretListener(new CaretListener() {
        public void caretUpdate(CaretEvent e) {
            InetAddress thisIp;// w ww . jav a  2  s  .c  o m
            try {
                thisIp = InetAddress.getLocalHost();
                titleFTP.setText("Connection: " + thisIp.getHostAddress() + " -> " + adressf.getText());
            } catch (UnknownHostException e1) {
                e1.printStackTrace();
            }
        }
    });

    exit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            saveState();
            uploadFTP.dispose();
            tree.dispose();
        }
    });

    connect.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            FTPClient client = new FTPClient();
            FileInputStream fis = null;
            String pass = String.valueOf(passf.getPassword());
            try {
                if (filename == null) {
                    status.setText("File does not exist!");
                } else {
                    // Server address
                    client.connect(adressf.getText());
                    // Login credentials
                    client.login(userf.getText(), pass);
                    if (client.isConnected()) {
                        status.setText("Succesfull transfer!");
                        // File type
                        client.setFileType(FTP.BINARY_FILE_TYPE);
                        // File location
                        File file = new File(filepath);
                        fis = new FileInputStream(file);
                        // Change the folder on the server
                        client.changeWorkingDirectory(folderf.getText());
                        // Save the file on the server
                        client.storeFile(filename, fis);
                    } else {
                        status.setText("Transfer failed!");
                    }
                }
                client.logout();
            } catch (IOException e1) {
                Encrypter.printException(e1);
            } finally {
                try {
                    if (fis != null) {
                        fis.close();
                    }
                    client.disconnect();
                } catch (IOException e1) {
                    Encrypter.printException(e1);
                }
            }
        }
    });

    browsef.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            int retval = chooserf.showOpenDialog(chooserf);
            if (retval == JFileChooser.APPROVE_OPTION) {
                status.setText("");
                filename = chooserf.getSelectedFile().getName().toString();
                filepath = chooserf.getSelectedFile().getPath();
                filenf.setText(chooserf.getSelectedFile().getName().toString());
            }
        }
    });

    adv.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {

            tree.setSize(220, uploadFTP.getHeight());
            tree.setLocation(uploadFTP.getX() + 405, uploadFTP.getY());
            tree.setResizable(false);
            tree.setIconImage(Toolkit.getDefaultToolkit()
                    .getImage(getClass().getClassLoader().getResource("assets/ico.png")));
            tree.setUndecorated(true);
            tree.getRootPane().setBorder(BorderFactory.createLineBorder(Encrypter.color_black, 2));
            tree.setVisible(true);
            tree.setLayout(new BorderLayout());

            JLabel labeltree = new JLabel("Server documents");
            labeltree.setOpaque(true);
            labeltree.setBackground(Encrypter.color_light);
            labeltree.setBorder(BorderFactory.createMatteBorder(8, 10, 10, 0, Encrypter.color_light));
            labeltree.setForeground(Encrypter.color_blue);
            labeltree.setFont(Encrypter.font16);

            JButton refresh = new JButton("");
            ImageIcon refresh_icon = getImageIcon("assets/icons/refresh.png");
            refresh.setIcon(refresh_icon);
            refresh.setBackground(Encrypter.color_light);
            refresh.setBorder(BorderFactory.createEmptyBorder(0, 0, 5, 0));
            refresh.setForeground(Encrypter.color_black);
            refresh.setFont(Encrypter.font16);
            refresh.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

            final FTPClient client = new FTPClient();
            DefaultMutableTreeNode top = new DefaultMutableTreeNode(adressf.getText());
            DefaultMutableTreeNode files = null;
            DefaultMutableTreeNode leaf = null;

            final JTree tree_view = new JTree(top);
            tree_view.setForeground(Encrypter.color_black);
            tree_view.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0));
            tree_view.putClientProperty("JTree.lineStyle", "None");
            tree_view.setBackground(Encrypter.color_light);
            JScrollPane scrolltree = new JScrollPane(tree_view);
            scrolltree.setBackground(Encrypter.color_light);
            scrolltree.getVerticalScrollBar().setPreferredSize(new Dimension(0, 0));

            UIManager.put("Tree.textBackground", Encrypter.color_light);
            UIManager.put("Tree.selectionBackground", Encrypter.color_blue);
            UIManager.put("Tree.selectionBorderColor", Encrypter.color_blue);

            tree_view.updateUI();

            final String pass = String.valueOf(passf.getPassword());
            try {
                client.connect(adressf.getText());
                client.login(userf.getText(), pass);
                client.enterLocalPassiveMode();
                if (client.isConnected()) {
                    try {
                        FTPFile[] ftpFiles = client.listFiles();
                        for (FTPFile ftpFile : ftpFiles) {
                            files = new DefaultMutableTreeNode(ftpFile.getName());
                            top.add(files);
                            if (ftpFile.getType() == FTPFile.DIRECTORY_TYPE) {
                                FTPFile[] ftpFiles1 = client.listFiles(ftpFile.getName());
                                for (FTPFile ftpFile1 : ftpFiles1) {
                                    leaf = new DefaultMutableTreeNode(ftpFile1.getName());
                                    files.add(leaf);
                                }
                            }
                        }
                    } catch (IOException e1) {
                        Encrypter.printException(e1);
                    }
                    client.disconnect();
                } else {
                    status.setText("Failed connection!");
                }
            } catch (IOException e1) {
                Encrypter.printException(e1);
            } finally {
                try {
                    client.disconnect();
                } catch (IOException e1) {
                    Encrypter.printException(e1);
                }
            }

            tree.add(labeltree, BorderLayout.NORTH);
            tree.add(scrolltree, BorderLayout.CENTER);
            tree.add(refresh, BorderLayout.SOUTH);

            uploadFTP.addComponentListener(new ComponentListener() {

                public void componentMoved(ComponentEvent e) {
                    tree.setLocation(uploadFTP.getX() + 405, uploadFTP.getY());
                }

                public void componentShown(ComponentEvent e) {
                }

                public void componentResized(ComponentEvent e) {
                }

                public void componentHidden(ComponentEvent e) {
                }
            });

            uploadFTP.addWindowListener(new WindowListener() {
                public void windowActivated(WindowEvent e) {
                    tree.toFront();
                }

                public void windowOpened(WindowEvent e) {
                }

                public void windowIconified(WindowEvent e) {
                }

                public void windowDeiconified(WindowEvent e) {
                }

                public void windowDeactivated(WindowEvent e) {
                }

                public void windowClosing(WindowEvent e) {
                }

                public void windowClosed(WindowEvent e) {
                }
            });

            refresh.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    tree.dispose();
                    tree.setVisible(true);
                }
            });
        }
    });

}

From source file:projetocsv.framePrincipal.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    Oracle conexao = new Oracle("localhost", "winston", "winston");
    if (conexao.connect()) {
        JOptionPane.showMessageDialog(null, "Conectado");

        //ExportCSV csv = new ExportCSV();
        //csv.gerar("teste.csv", conexao);
        CSVWriter writer = null;//from w  w w . java2 s  .com
        try {
            writer = new CSVWriter(new FileWriter("teste.csv"), '\t', ';');
        } catch (IOException ex) {
            Logger.getLogger(framePrincipal.class.getName()).log(Level.SEVERE, null, ex);
        }
        Boolean includeHeaders = false;

        java.sql.ResultSet myResultSet = conexao.executar("select * from testtable");

        try {
            writer.writeAll(myResultSet, includeHeaders);

        } catch (SQLException ex) {
            Logger.getLogger(framePrincipal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(framePrincipal.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            JOptionPane.showMessageDialog(null, "Gerao finalizada");
            conexao.disconnect();
        }

        try {
            writer.close();
            FTPClient ftp = new FTPClient();
            try {
                ftp.connect("ftp.testeftpm.xp3.biz");
                ftp.login("testeftpm.xp3.biz ", "passftp");
                System.out.println("Ftp conectado");
            } catch (Exception e) {
                System.out.println("Erro ao conectar");
            }

            FileInputStream arqEnviar = new FileInputStream("teste.csv");
            if (ftp.storeFile("teste.csv", arqEnviar)) {
                System.out.println("Arquivo enviado com sucesso!");
                JOptionPane.showMessageDialog(null, "Arquivo enviado com sucesso!");
            } else {
                System.out.println("Erro ao enviar arquivo.");
            }

        } catch (IOException ex) {
            Logger.getLogger(framePrincipal.class.getName()).log(Level.SEVERE, null, ex);
        }

    } else {
        JOptionPane.showMessageDialog(null, "Erro ao estabelecer conexo");
    }

}

From source file:rapture.ftp.common.FTPConnection.java

public boolean sendFile(InputStream stream, String fileName) throws IOException {
    int slash = fileName.lastIndexOf('/');
    FTPClient client = getFtpClient();
    if (slash > 0) {
        client.changeWorkingDirectory(fileName.substring(0, slash));
    }/*from  w w  w.j  a  va  2  s.  c o m*/
    return client.storeFile(fileName.substring(slash + 1), stream);
}

From source file:rems.Global.java

public static String UploadFile(InetAddress ftpserverurl, String serverAppDirectory, String PureFileName,
        String fullLocFileUrl, String userName, String password) {
    // get an ftpClient object  
    FTPClient ftpClient = new FTPClient();
    FileInputStream inputStream = null;
    String responsTxt = "";
    try {/*w ww  .  j av a2 s .  c  o m*/
        // pass directory path on server to connect
        // pass username and password, returned true if authentication is  
        // successful  
        ftpClient.connect(ftpserverurl, 21);
        boolean login = ftpClient.login(userName, password);
        ftpClient.setKeepAlive(false);
        ftpClient.setPassiveNatWorkaround(true);
        if (login) {
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            File firstLocalFile = new File(fullLocFileUrl);
            inputStream = new FileInputStream(firstLocalFile);
            //inputStream.reset();
            boolean uploaded = ftpClient.storeFile(serverAppDirectory + PureFileName, inputStream);
            inputStream.close();
            responsTxt = ftpClient.getReplyString();
            if (uploaded) {
                responsTxt += "File uploaded successfully !";
            } else {
                responsTxt += "Error in uploading file !::" + serverAppDirectory + PureFileName;
            }

            Global.updateLogMsg(Global.logMsgID, "\r\n\r\n\r\nUpload Response ==>\r\n" + responsTxt,
                    Global.logTbl, Global.gnrlDateStr, Global.rnUser_ID);
            // logout the user, returned true if logout successfully  
            boolean logout = ftpClient.logout();
            if (logout) {
                //System.out.println("Connection close...");
            }
        } else {
            Global.errorLog += "Connection Failed..." + responsTxt;
            Global.updateLogMsg(Global.logMsgID,
                    "\r\n\r\n\r\nThe Program has Errored Out ==>\r\n\r\n" + Global.errorLog, Global.logTbl,
                    Global.gnrlDateStr, Global.rnUser_ID);
            Global.writeToLog();
        }
        return responsTxt;
    } catch (SocketException e) {
        Global.errorLog += e.getMessage() + "\r\n" + Arrays.toString(e.getStackTrace());
        Global.updateLogMsg(Global.logMsgID,
                "\r\n\r\n\r\nThe Program has Errored Out ==>\r\n\r\n" + Global.errorLog, Global.logTbl,
                Global.gnrlDateStr, Global.rnUser_ID);
        Global.writeToLog();
    } catch (IOException e) {
        Global.errorLog += e.getMessage() + "\r\n" + Arrays.toString(e.getStackTrace());
        Global.updateLogMsg(Global.logMsgID,
                "\r\n\r\n\r\nThe Program has Errored Out ==>\r\n\r\n" + Global.errorLog, Global.logTbl,
                Global.gnrlDateStr, Global.rnUser_ID);
        Global.writeToLog();
    } finally {
        try {
            ftpClient.disconnect();
        } catch (IOException e) {
            Global.errorLog += e.getMessage() + "\r\n" + Arrays.toString(e.getStackTrace());
            Global.updateLogMsg(Global.logMsgID,
                    "\r\n\r\n\r\nThe Program has Errored Out ==>\r\n\r\n" + Global.errorLog, Global.logTbl,
                    Global.gnrlDateStr, Global.rnUser_ID);
            Global.writeToLog();
        } finally {

        }
    }
    return "";
}

From source file:ro.kuberam.libs.java.ftclient.FTP.FTP.java

public boolean storeResource(Object abstractConnection, String remoteDirectoryPath, String resourceName,
        InputStream resourceInputStream) throws Exception {
    long startTime = new Date().getTime();
    FTPClient connection = (FTPClient) abstractConnection;
    if (!connection.isConnected()) {
        throw new Exception(ErrorMessages.err_FTC002);
    }/*from  ww  w  . ja  va2s  .co  m*/

    Boolean result = true;
    try {
        if (resourceName.length() == 0) {
            resourceName = remoteDirectoryPath.substring(remoteDirectoryPath.lastIndexOf("/") + 1);
            remoteDirectoryPath = remoteDirectoryPath.substring(0, remoteDirectoryPath.lastIndexOf("/"));
            _checkResourcePath(connection, remoteDirectoryPath, "store-resource", true);
            result = connection.makeDirectory(resourceName);
        } else {
            _checkResourcePath(connection, remoteDirectoryPath, "store-resource", false);
            result = connection.storeFile(resourceName, resourceInputStream);
            resourceInputStream.close();
        }
    } catch (IOException ioe) {
        log.error(ioe.getMessage(), ioe);
        // TODO: add throw exception here for cases when server doesn't
        // allow storage of file - a use case is when vsftpd was configured
        // with mandatory SSL encryption
        result = false;
    }

    // if(!FTPconnection.completePendingCommand()) {
    // throw new Exception(
    // "err:FTC007: The current operation failed.");
    // }

    log.info("The FTP sub-module stored the resource '" + resourceName + "' at '" + remoteDirectoryPath
            + "' in " + (new Date().getTime() - startTime) + " ms.");

    return result;
}

From source file:ru.in360.FTPUtil.java

public static void upload(File src, FTPClient ftp) throws IOException {
    if (src.isDirectory()) {
        ftp.makeDirectory(src.getName());
        ftp.changeWorkingDirectory(src.getName());
        for (File file : src.listFiles()) {
            upload(file, ftp);/*ww  w .j  ava2s.  c o m*/
        }
        ftp.changeToParentDirectory();
    } else {
        InputStream srcStream = null;
        try {
            srcStream = src.toURI().toURL().openStream();
            ftp.storeFile(src.getName(), srcStream);
        } finally {
            IOUtils.closeQuietly(srcStream);
        }
    }
}

From source file:s32a.CodebaseDeployer.java

/**
 * Uploads given files to ftp server.// w w  w .  jav  a  2  s  .  com
 *
 * @param input key: desired name on server, Value: file to upload.
 */
private void uploadFiles(Map<String, File> input) {

    FTPClient client = null;
    if (SSL) {
        client = new FTPSClient(false);
    } else {
        client = new FTPClient();
    }
    FileInputStream fis = null;
    FileOutputStream fos = null;

    try {
        System.out.println("connecting");
        client.connect(ftpServer);
        boolean login = client.login(this.userName, this.password);
        System.out.println("login: " + login);
        client.enterLocalPassiveMode();

        //            client.setFileType(FTP.ASCII_FILE_TYPE);

        //Creates all directories required on the server
        System.out.println("creating directories");
        client.makeDirectory("Airhockey");
        client.makeDirectory("Airhockey/Codebase");
        client.makeDirectory("Airhockey/Servers");
        client.makeDirectory("Airhockey/Codebase/s32a");
        System.out.println("default directories made");
        for (String s : directories) {
            client.makeDirectory(s);
        }

        //Uploads codebase URL
        fis = new FileInputStream(this.codebaseFile);
        boolean stored = client.storeFile("Airhockey/Codebase/codebase.properties", fis);
        //            client.completePendingCommand();
        System.out.println("Stored codebase file: " + stored);
        fis.close();

        // Removes references to all servers
        for (FTPFile f : client.listFiles("Airhockey/Servers")) {
            if (f.isFile()) {
                System.out.println("Deleting Server Listing: " + f.getName());
                client.deleteFile("/Airhockey/Servers/" + f.getName());
            }
        }

        // Uploads all class files
        System.out.println("Uploading classes");
        String defaultLoc = fs + "Airhockey" + fs + "Codebase" + fs;
        for (String dest : input.keySet()) {
            fis = new FileInputStream(input.get(dest));
            if (!client.storeFile(defaultLoc + dest, fis)) {
                System.out.println("unable to save: " + defaultLoc + dest);
            }
            fis.close();
            //                client.completePendingCommand();
        }

        client.logout();
    } catch (IOException ex) {
        System.out.println("IOException: " + ex.getMessage());
        ex.printStackTrace();
    } catch (Exception ex) {
        System.out.println("exception caught: " + ex.getMessage());
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            if (fos != null) {
                fos.close();
            }
            client.disconnect();
            System.exit(0);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}