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

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

Introduction

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

Prototype

public void connect(InetAddress host) throws SocketException, IOException 

Source Link

Document

Opens a Socket connected to a remote host at the current default port and originating from the current host at a system assigned port.

Usage

From source file:ftp_server.FTPFileUpload.java

public static void main(String[] args) throws IOException {
    FTPClient ftpclient = new FTPClient();
    FileInputStream fis = null;/*w ww . ja v a  2s . co  m*/
    boolean result;
    String ftpServerAddress = "shamalmahesh.net78.net";
    String userName = "a9959679";
    String password = "9P3IckDo";

    try {
        ftpclient.connect(ftpServerAddress);
        result = ftpclient.login(userName, password);

        if (result == true) {
            System.out.println("Logged in Successfully !");
        } else {
            System.out.println("Login Fail!");
            return;
        }
        ftpclient.enterLocalPassiveMode();
        ftpclient.setFileType(FTP.BINARY_FILE_TYPE);

        ftpclient.changeWorkingDirectory("/public_html/testing");

        File file = new File("D:/jpg/wq.jpg");
        String testName = file.getName();
        fis = new FileInputStream(file);

        // Upload file to the ftp server
        result = ftpclient.storeFile(testName, fis);

        if (result == true) {
            System.out.println("File is uploaded successfully");
        } else {
            System.out.println("File uploading failed");
        }
        ftpclient.logout();
    } catch (FTPConnectionClosedException e) {
        e.printStackTrace();
    } finally {
        try {
            ftpclient.disconnect();
        } catch (FTPConnectionClosedException e) {
            System.out.println(e);
        }
    }
}

From source file:airnowgrib2tojson.AirNowGRIB2toJSON.java

/**
 * @param args the command line arguments
 *///from   w  w  w  . j a v a  2  s.c  o m
public static void main(String[] args) {

    SimpleDateFormat GMT = new SimpleDateFormat("yyMMddHH");
    GMT.setTimeZone(TimeZone.getTimeZone("GMT-2"));

    System.out.println(GMT.format(new Date()));

    FTPClient ftpClient = new FTPClient();
    FileOutputStream fos = null;

    try {
        //Connecting to AirNow FTP server to get the fresh AQI data  
        ftpClient.connect("ftp.airnowapi.org");
        ftpClient.login("pixelshade", "GZDN8uqduwvk");
        ftpClient.enterLocalPassiveMode();
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        //downloading .grib2 file
        File of = new File("US-" + GMT.format(new Date()) + "_combined.grib2");
        OutputStream outstr = new BufferedOutputStream(new FileOutputStream(of));
        InputStream instr = ftpClient
                .retrieveFileStream("GRIB2/US-" + GMT.format(new Date()) + "_combined.grib2");
        byte[] bytesArray = new byte[4096];
        int bytesRead = -1;
        while ((bytesRead = instr.read(bytesArray)) != -1) {
            outstr.write(bytesArray, 0, bytesRead);
        }

        //Close used resources
        ftpClient.completePendingCommand();
        outstr.close();
        instr.close();

        // logout the user 
        ftpClient.logout();

    } catch (SocketException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            //disconnect from AirNow server
            ftpClient.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    try {
        //Open .grib2 file
        final File AQIfile = new File("US-" + GMT.format(new Date()) + "_combined.grib2");
        final GridDataset gridDS = GridDataset.open(AQIfile.getAbsolutePath());

        //The data type needed - AQI; since it isn't defined in GRIB2 standard,
        //Aerosol type is used instead; look AirNow API documentation for details.
        GridDatatype AQI = gridDS.findGridDatatype("Aerosol_type_msl");

        //Get the coordinate system for selected data type;
        //cut the rectangle to work with - time and height axes aren't present in these files
        //and latitude/longitude go "-1", which means all the data provided.
        GridCoordSystem AQIGCS = AQI.getCoordinateSystem();
        List<CoordinateAxis> AQI_XY = AQIGCS.getCoordinateAxes();
        Array AQIslice = AQI.readDataSlice(0, 0, -1, -1);

        //Variables for iterating through coordinates
        VariableDS var = AQI.getVariable();
        Index index = AQIslice.getIndex();

        //Variables for counting lat/long from the indices provided
        double stepX = (AQI_XY.get(2).getMaxValue() - AQI_XY.get(2).getMinValue()) / index.getShape(1);
        double stepY = (AQI_XY.get(1).getMaxValue() - AQI_XY.get(1).getMinValue()) / index.getShape(0);
        double curX = AQI_XY.get(2).getMinValue();
        double curY = AQI_XY.get(1).getMinValue();

        //Output details
        OutputStream ValLog = new FileOutputStream("USA_AQI.json");
        Writer ValWriter = new OutputStreamWriter(ValLog);

        for (int j = 0; j < index.getShape(0); j++) {
            for (int i = 0; i < index.getShape(1); i++) {
                float val = AQIslice.getFloat(index.set(j, i));

                //Write the AQI value and its coordinates if it's present by i/j indices
                if (!Float.isNaN(val))
                    ValWriter.write("{\r\n\"lat\":" + curX + ",\r\n\"lng\":" + curY + ",\r\n\"AQI\":" + val
                            + ",\r\n},\r\n");

                curX += stepX;
            }
            curY += stepY;
            curX = AQI_XY.get(2).getMinValue();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:examples.ftp.java

public static final void main(String[] args) {
    int base = 0;
    boolean storeFile = false, binaryTransfer = false, error = false;
    String server, username, password, remote, local;
    FTPClient ftp;

    for (base = 0; base < args.length; base++) {
        if (args[base].startsWith("-s"))
            storeFile = true;//  w  ww. ja  v a  2  s . co  m
        else if (args[base].startsWith("-b"))
            binaryTransfer = true;
        else
            break;
    }

    if ((args.length - base) != 5) {
        System.err.println(USAGE);
        System.exit(1);
    }

    server = args[base++];
    username = args[base++];
    password = args[base++];
    remote = args[base++];
    local = args[base];

    ftp = new FTPClient();
    ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));

    try {
        int reply;
        ftp.connect(server);
        System.out.println("Connected to " + server + ".");

        // After connection attempt, you should check the reply code to verify
        // success.
        reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            System.err.println("FTP server refused connection.");
            System.exit(1);
        }
    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        System.exit(1);
    }

    __main: try {
        if (!ftp.login(username, password)) {
            ftp.logout();
            error = true;
            break __main;
        }

        System.out.println("Remote system is " + ftp.getSystemName());

        if (binaryTransfer)
            ftp.setFileType(FTP.BINARY_FILE_TYPE);

        // Use passive mode as default because most of us are
        // behind firewalls these days.
        ftp.enterLocalPassiveMode();

        if (storeFile) {
            InputStream input;

            input = new FileInputStream(local);

            ftp.storeFile(remote, input);

            input.close();
        } else {
            OutputStream output;

            output = new FileOutputStream(local);

            ftp.retrieveFile(remote, output);

            output.close();
        }

        ftp.logout();
    } catch (FTPConnectionClosedException e) {
        error = true;
        System.err.println("Server closed connection.");
        e.printStackTrace();
    } catch (IOException e) {
        error = true;
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
    }

    System.exit(error ? 1 : 0);
}

From source file:aplicacion.sistema.version.logic.ftp.java

public static final void main(String[] args) {
    int base = 0;
    boolean storeFile = false, binaryTransfer = false, error = false;
    String server, username, password, remote, local;
    server = "gisbertrepuestos.com.ar";
    username = "gisbertrepuestos.com.ar";
    password = "ipsilon@1982";
    remote = "beta/beta-patch.msp";
    local = "c:/beta-patch-from-ftp.msp";
    FTPClient ftp;
    /*/*from  w  w w  .  ja va  2  s.c  om*/
    for (base = 0; base < args.length; base++)
    {
    if (args[base].startsWith("-s"))
        storeFile = true;
    else if (args[base].startsWith("-b"))
        binaryTransfer = true;
    else
        break;
    }
            
    if ((args.length - base) != 5)
    {
    System.err.println(USAGE);
    System.exit(1);
    }
            
    server = args[base++];
    username = args[base++];
    password = args[base++];
    remote = args[base++];
    local = args[base];
    */
    ftp = new FTPClient();
    ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));

    try {
        int reply;
        ftp.connect(server);
        System.out.println("Connected to " + server + ".");

        // After connection attempt, you should check the reply code to verify
        // success.
        reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            System.err.println("FTP server refused connection.");
            System.exit(1);
        }
    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        System.exit(1);
    }

    __main: try {
        if (!ftp.login(username, password)) {
            ftp.logout();
            error = true;
            break __main;
        }

        System.out.println("Remote system is " + ftp.getSystemName());

        if (binaryTransfer)
            ftp.setFileType(FTP.BINARY_FILE_TYPE);

        // Use passive mode as default because most of us are
        // behind firewalls these days.
        ftp.enterLocalPassiveMode();

        if (storeFile) {
            InputStream input;

            input = new FileInputStream(local);

            ftp.storeFile(remote, input);

            input.close();
        } else {
            OutputStream output;

            output = new FileOutputStream(local);

            ftp.retrieveFile(remote, output);

            output.close();
        }

        ftp.logout();
    } catch (FTPConnectionClosedException e) {
        error = true;
        System.err.println("Server closed connection.");
        e.printStackTrace();
    } catch (IOException e) {
        error = true;
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
    }

    System.exit(error ? 1 : 0);
}

From source file:examples.server2serverFTP.java

public static final void main(String[] args) {
    String server1, username1, password1, file1;
    String server2, username2, password2, file2;
    FTPClient ftp1, ftp2;
    ProtocolCommandListener listener;//www.  j a va  2 s .  c o  m

    if (args.length < 8) {
        System.err.println("Usage: ftp <host1> <user1> <pass1> <file1> <host2> <user2> <pass2> <file2>");
        System.exit(1);
    }

    server1 = args[0];
    username1 = args[1];
    password1 = args[2];
    file1 = args[3];
    server2 = args[4];
    username2 = args[5];
    password2 = args[6];
    file2 = args[7];

    listener = new PrintCommandListener(new PrintWriter(System.out));
    ftp1 = new FTPClient();
    ftp1.addProtocolCommandListener(listener);
    ftp2 = new FTPClient();
    ftp2.addProtocolCommandListener(listener);

    try {
        int reply;
        ftp1.connect(server1);
        System.out.println("Connected to " + server1 + ".");

        reply = ftp1.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp1.disconnect();
            System.err.println("FTP server1 refused connection.");
            System.exit(1);
        }
    } catch (IOException e) {
        if (ftp1.isConnected()) {
            try {
                ftp1.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server1.");
        e.printStackTrace();
        System.exit(1);
    }

    try {
        int reply;
        ftp2.connect(server2);
        System.out.println("Connected to " + server2 + ".");

        reply = ftp2.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp2.disconnect();
            System.err.println("FTP server2 refused connection.");
            System.exit(1);
        }
    } catch (IOException e) {
        if (ftp2.isConnected()) {
            try {
                ftp2.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server2.");
        e.printStackTrace();
        System.exit(1);
    }

    __main: try {
        if (!ftp1.login(username1, password1)) {
            System.err.println("Could not login to " + server1);
            break __main;
        }

        if (!ftp2.login(username2, password2)) {
            System.err.println("Could not login to " + server2);
            break __main;
        }

        // Let's just assume success for now.
        ftp2.enterRemotePassiveMode();

        ftp1.enterRemoteActiveMode(InetAddress.getByName(ftp2.getPassiveHost()), ftp2.getPassivePort());

        // Although you would think the store command should be sent to server2
        // first, in reality, ftp servers like wu-ftpd start accepting data
        // connections right after entering passive mode.  Additionally, they
        // don't even send the positive preliminary reply until after the
        // transfer is completed (in the case of passive mode transfers).
        // Therefore, calling store first would hang waiting for a preliminary
        // reply.
        if (ftp1.remoteRetrieve(file1) && ftp2.remoteStoreUnique(file2)) {
            //      if(ftp1.remoteRetrieve(file1) && ftp2.remoteStore(file2)) {
            // We have to fetch the positive completion reply.
            ftp1.completePendingCommand();
            ftp2.completePendingCommand();
        } else {
            System.err.println("Couldn't initiate transfer.  Check that filenames are valid.");
            break __main;
        }

    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    } finally {
        try {
            if (ftp1.isConnected()) {
                ftp1.logout();
                ftp1.disconnect();
            }
        } catch (IOException e) {
            // do nothing
        }

        try {
            if (ftp2.isConnected()) {
                ftp2.logout();
                ftp2.disconnect();
            }
        } catch (IOException e) {
            // do nothing
        }
    }
}

From source file:atualizador.Atualizador.java

private static void FTPDownload(String fileName, String DiretorioFTP)
        throws IOException, FileNotFoundException {
    FTPClient client = new FTPClient();
    FileOutputStream fos = null;//  w  w w  . j  av a2  s.  co  m

    client.connect("plutao.telemar");
    client.login("usrcorj", "usr341!tg");

    String filename = fileName;
    fos = new FileOutputStream(filename);

    client.changeWorkingDirectory(DiretorioFTP);
    client.retrieveFile(filename, fos);
    fos.close();
    client.disconnect();
}

From source file:com.axelor.apps.tool.net.MyFtp.java

public static void getDataFiles(String server, String username, String password, String folder,
        String destinationFolder, Calendar start, Calendar end) {

    try {// w  ww .ja  v  a2  s .c om

        // Connect and logon to FTP Server
        FTPClient ftp = new FTPClient();
        ftp.connect(server);
        ftp.login(username, password);

        // List the files in the directory
        ftp.changeWorkingDirectory(folder);
        FTPFile[] files = ftp.listFiles();

        for (int i = 0; i < files.length; i++) {

            Date fileDate = files[i].getTimestamp().getTime();
            if (fileDate.compareTo(start.getTime()) >= 0 && fileDate.compareTo(end.getTime()) <= 0) {

                // Download a file from the FTP Server
                File file = new File(destinationFolder + File.separator + files[i].getName());
                FileOutputStream fos = new FileOutputStream(file);
                ftp.retrieveFile(files[i].getName(), fos);
                fos.close();
                file.setLastModified(fileDate.getTime());
            }
        }

        // Logout from the FTP Server and disconnect
        ftp.logout();
        ftp.disconnect();

    } catch (Exception e) {

        LOG.error(e.getMessage());

    }
}

From source file:CFDI_Verification.CFDI_Verification.java

public static String test_Connection(String directory) {

    String server = "192.1.1.64";
    String user = "ftpuser";
    String pass = "Oracle123";
    String result = "No Connected!";

    FTPClient ftpClient = new FTPClient();

    try {//  w w w  . j a  v a  2 s .c o  m
        ftpClient.connect(server);
        ftpClient.login(user, pass);
        ftpClient.enterLocalPassiveMode();
        ftpClient.changeWorkingDirectory(directory);

        if (ftpClient.isConnected() == true) {
            result = "Connected to " + ftpClient.printWorkingDirectory();
        }

        ftpClient.logout();
        ftpClient.disconnect();

    } catch (IOException ex) {
        System.out.println("Ooops! Error en conexin." + ex.getMessage());
    } finally {
        return result;
    }
}

From source file:CFDI_Verification.CFDI_Verification.java

public static void list_directories(String directory) {
    String server = "192.1.1.64";
    String user = "ftpuser";
    String pass = "Oracle123";
    String result = "No Connected!";

    FTPClient ftpClient = new FTPClient();

    try {/*w  w  w . j  a va  2  s.c om*/
        ftpClient.connect(server);
        ftpClient.login(user, pass);
        ftpClient.enterLocalPassiveMode();
        ftpClient.changeWorkingDirectory(directory);

        String[] directories = ftpClient.listNames();
        String dir;

        for (int i = 0; i < directories.length; i++) {
            System.out.println(directories[i]);
            dir = directories[i];
        }

        ftpClient.logout();
        ftpClient.disconnect();

    } catch (IOException ex) {
        System.out.println("Ooops! Error en conexin." + ex.getMessage());
    }
}

From source file:CFDI_Verification.CFDI_Verification.java

public static ARRAY getDirectories(String directory) throws SQLException {
    Connection conn = new OracleDriver().defaultConnection();
    ArrayDescriptor descriptor = ArrayDescriptor.createDescriptor("DIRECTORIES_LIST", conn);

    String server = "192.1.1.64";
    String user = "ftpuser";
    String pass = "Oracle123";
    String result = "No Connected!";

    FTPClient ftpClient = new FTPClient();

    try {//from  w w w  .ja v  a 2s  . com
        ftpClient.connect(server);
        ftpClient.login(user, pass);
        ftpClient.enterLocalPassiveMode();
        ftpClient.changeWorkingDirectory(directory);

        String[] directories = ftpClient.listNames();
        ARRAY directories_list = new ARRAY(descriptor, conn, directories);

        ftpClient.logout();
        ftpClient.disconnect();

        return directories_list;
    } catch (IOException ex) {
        System.out.println("Ooops! Error en conexin." + ex.getMessage());
    }
    return null;
}