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

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

Introduction

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

Prototype

public boolean changeWorkingDirectory(String pathname) throws IOException 

Source Link

Document

Change the current working directory of the FTP session.

Usage

From source file:com.ephesoft.dcma.util.FTPUtil.java

/**
 * API to create an arbitrary directory hierarchy on the remote ftp server
 * //from  www  . j a  va  2  s . co  m
 * @param client {@link FTPClient} the ftp client instance.
 * @param dirTree the directory tree only delimited with / chars.
 * @throws IOException if a [problem occurs while making the directory or traversing down the directory structure.
 */
private static void createFtpDirectoryTree(final FTPClient client, final String dirTree) throws IOException {

    boolean dirExists = true;

    /*
     * tokenize the string and attempt to change into each directory level. If you cannot, then start creating. Needs to be updated
     * with a proper regex for being the system independent working. NOTE: Cannot use File.seperator here as for windows its value
     * is "\", which is a special character in terms of regex.
     */
    String[] directories = dirTree.split(DIRECTORY_SEPARATOR);
    for (String dir : directories) {
        if (!dir.isEmpty()) {
            if (dirExists) {
                dirExists = client.changeWorkingDirectory(dir);
            }
            if (!dirExists) {
                if (!client.makeDirectory(dir)) {
                    throw new IOException(EphesoftStringUtil.concatenate("Unable to create remote directory :",
                            dir, "\t error :", client.getReplyString()));
                }
                if (!client.changeWorkingDirectory(dir)) {
                    throw new IOException(EphesoftStringUtil.concatenate(
                            "Unable to change into newly created remote directory :", dir, "\t  error :",
                            client.getReplyString()));
                }
            }
        }
    }
}

From source file:moskitt4me.repositoryClient.core.util.RepositoryClientUtil.java

public static FTPClient connect(RepositoryLocation location, boolean showErrors) {

    FTPClient client = new FTPClient();
    String errorMessage = "";

    try {/* www.  j a v a  2s.c o m*/
        client.connect(location.getHost());
        boolean ok = client.login(location.getUser(), location.getPassword());
        if (ok) {
            boolean ok2 = client.changeWorkingDirectory(location.getRepositoryPath());
            if (!ok2) {
                client = null;
                errorMessage = "Incorrect repository path";
            }
        } else {
            client = null;
            errorMessage = "Incorrect user name and password";
        }
    } catch (Exception e) {
        client = null;
        errorMessage = "Unknown host";
    }

    if (!errorMessage.equals("") && showErrors) {
        MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
                "Connection failed", errorMessage);
    }

    return client;
}

From source file:com.mendhak.gpslogger.senders.ftp.Ftp.java

public static boolean Upload(String server, String username, String password, int port, boolean useFtps,
        String protocol, boolean implicit, InputStream inputStream, String fileName) {
    FTPClient client = null;

    try {/*from w  ww. j  a  va 2 s.  c  om*/
        if (useFtps) {
            client = new FTPSClient(protocol, implicit);

            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(null, null);
            KeyManager km = kmf.getKeyManagers()[0];
            ((FTPSClient) client).setKeyManager(km);
        } else {
            client = new FTPClient();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        Utilities.LogDebug("Connecting to FTP");
        client.connect(server, port);

        Utilities.LogDebug("Logging in to FTP server");
        if (client.login(username, password)) {
            client.enterLocalPassiveMode();

            Utilities.LogDebug("Uploading file to FTP server");

            FTPFile[] existingDirectory = client.listFiles("GPSLogger");

            if (existingDirectory.length <= 0) {
                client.makeDirectory("GPSLogger");
            }

            client.changeWorkingDirectory("GPSLogger");
            boolean result = client.storeFile(fileName, inputStream);
            inputStream.close();
            if (result) {
                Utilities.LogDebug("Successfully FTPd file");
            } else {
                Utilities.LogDebug("Failed to FTP file");
            }

        } else {
            Utilities.LogDebug("Could not log in to FTP server");
            return false;
        }

    } catch (Exception e) {
        Utilities.LogError("Could not connect or upload to FTP server.", e);
    } finally {
        try {
            Utilities.LogDebug("Logging out of FTP server");
            client.logout();

            Utilities.LogDebug("Disconnecting from FTP server");
            client.disconnect();
        } catch (Exception e) {
            Utilities.LogError("Could not logout or disconnect", e);
        }
    }

    return true;
}

From source file:ca.rmen.android.networkmonitor.app.speedtest.SpeedTestUpload.java

public static SpeedTestResult upload(SpeedTestUploadConfig uploadConfig) {
    Log.v(TAG, "upload " + uploadConfig);
    // Make sure we have a file to upload
    if (!uploadConfig.file.exists())
        return new SpeedTestResult(0, 0, 0, SpeedTestStatus.INVALID_FILE);

    FTPClient ftp = new FTPClient();
    // For debugging, we'll log all the ftp commands
    if (BuildConfig.DEBUG) {
        PrintCommandListener printCommandListener = new PrintCommandListener(System.out);
        ftp.addProtocolCommandListener(printCommandListener);
    }//from ww  w . j  ava 2  s.c o m
    InputStream is = null;
    try {
        // Set buffer size of FTP client
        ftp.setBufferSize(1048576);
        // Open a connection to the FTP server
        ftp.connect(uploadConfig.server, uploadConfig.port);
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE);
        }
        // Login to the FTP server
        if (!ftp.login(uploadConfig.user, uploadConfig.password)) {
            ftp.disconnect();
            return new SpeedTestResult(0, 0, 0, SpeedTestStatus.AUTH_FAILURE);
        }
        // Try to change directories
        if (!TextUtils.isEmpty(uploadConfig.path) && !ftp.changeWorkingDirectory(uploadConfig.path)) {
            Log.v(TAG, "Upload: could not change path to " + uploadConfig.path);
            return new SpeedTestResult(0, 0, 0, SpeedTestStatus.INVALID_FILE);
        }

        // set the file type to be read as a binary file
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.enterLocalPassiveMode();
        // Upload the file
        is = new FileInputStream(uploadConfig.file);
        long before = System.currentTimeMillis();
        long txBytesBefore = TrafficStats.getTotalTxBytes();
        if (!ftp.storeFile(uploadConfig.file.getName(), is)) {
            ftp.disconnect();
            Log.v(TAG, "Upload: could not store file to " + uploadConfig.path + ". Error code: "
                    + ftp.getReplyCode() + ", error string: " + ftp.getReplyString());
            return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE);
        }

        // Calculate stats
        long after = System.currentTimeMillis();
        long txBytesAfter = TrafficStats.getTotalTxBytes();
        ftp.logout();
        ftp.disconnect();
        Log.v(TAG, "Upload complete");
        return new SpeedTestResult(txBytesAfter - txBytesBefore, uploadConfig.file.length(), after - before,
                SpeedTestStatus.SUCCESS);
    } catch (SocketException e) {
        Log.e(TAG, "upload " + e.getMessage(), e);
        return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE);
    } catch (IOException e) {
        Log.e(TAG, "upload " + e.getMessage(), e);
        return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE);
    } finally {
        IoUtil.closeSilently(is);
    }
}

From source file:co.nubetech.hiho.mapreduce.lib.output.FTPTextOutputFormat.java

@Override
public RecordWriter<K, V> getRecordWriter(TaskAttemptContext job) throws IOException, InterruptedException {

    Configuration conf = job.getConfiguration();

    String ip = conf.get(HIHOConf.FTP_ADDRESS);
    String portno = conf.get(HIHOConf.FTP_PORT);
    String usr = conf.get(HIHOConf.FTP_USER);
    String pwd = conf.get(HIHOConf.FTP_PASSWORD);
    String dir = getOutputPath(job).toString();
    System.out.println("\n\ninside ftpoutputformat" + ip + " " + portno + " " + usr + " " + pwd + " " + dir);
    String keyValueSeparator = conf.get("mapred.textoutputformat.separator", "\t");
    FTPClient f = new FTPClient();
    f.connect(ip, Integer.parseInt(portno));
    f.login(usr, pwd);/*from   w w w  .  j a v  a2  s  . co  m*/
    f.changeWorkingDirectory(dir);
    f.setFileType(FTP.BINARY_FILE_TYPE);

    boolean isCompressed = getCompressOutput(job);
    CompressionCodec codec = null;
    String extension = "";
    if (isCompressed) {
        Class<? extends CompressionCodec> codecClass = getOutputCompressorClass(job, GzipCodec.class);
        codec = (CompressionCodec) ReflectionUtils.newInstance(codecClass, conf);
        extension = codec.getDefaultExtension();
    }
    Path file = getDefaultWorkFile(job, extension);
    FileSystem fs = file.getFileSystem(conf);
    String filename = file.getName();
    if (!isCompressed) {
        // FSDataOutputStream fileOut = fs.create(file, false);
        OutputStream os = f.appendFileStream(filename);
        DataOutputStream fileOut = new DataOutputStream(os);
        return new FTPLineRecordWriter<K, V>(fileOut, new String(keyValueSeparator), f);

    } else {
        // FSDataOutputStream fileOut = fs.create(file, false);
        OutputStream os = f.appendFileStream(filename);
        DataOutputStream fileOut = new DataOutputStream(os);
        return new FTPLineRecordWriter<K, V>(new DataOutputStream(codec.createOutputStream(fileOut)),
                keyValueSeparator, f);
    }
}

From source file:de.idos.updates.lookup.FtpLookup.java

private Version findLatestVersion() throws IOException {
    FTPClient ftpClient = new FTPClient();
    ftpClient.connect(inetAddress);/*from   w  w w .  j  a v a  2s .  com*/
    ftpClient.enterLocalPassiveMode();

    if (login != null) {
        ftpClient.login(login, null);
    }

    if (workingDir != null) {
        ftpClient.changeWorkingDirectory(workingDir);
    }

    FTPFile[] availableVersionsDirs = ftpClient.listDirectories();
    List<String> strings = new ArrayList<String>();
    for (FTPFile ftpFile : availableVersionsDirs) {
        strings.add(ftpFile.getName());
    }

    List<Version> versions = new VersionFactory().createVersionsFromStrings(strings);
    return new VersionFinder().findLatestVersion(versions);
}

From source file:ftp_server.FileUpload.java

public void uploadingWithProgress() {
    FTPClient ftp = new FTPClient();
    FileInputStream fis = null;//w  ww .  ja v  a  2  s .c  om
    try {
        ftp.connect("shamalmahesh.net78.net");
        ftp.login("a9959679", "9P3IckDo");
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.changeWorkingDirectory("/public_html/testing");
        int reply = ftp.getReplyCode();
        if (FTPReply.isPositiveCompletion(reply)) {
            System.out.println("Uploading....");
        } else {
            System.out.println("Failed connect to the server!");
        }
        File f1 = new File("D:\\jpg\\1.jpg");

        //            fis = new FileInputStream(ftp.storeFile("one.jpg", fis));
        System.out.println("Done!");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:br.com.atmatech.painel.util.EnviaLogs.java

public void enviarBD(File file, String enderecoFTP, String login, String senha) throws IOException {
    String nomeArquivo = null;//from   ww  w  . j a  v  a2  s.  c o m
    FTPClient ftp = new FTPClient();
    ftp.connect(enderecoFTP);
    //verifica se conectou com sucesso! 

    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
        ftp.login(login, senha);
    } else {
        //erro ao se conectar  
        ftp.disconnect();
    }
    ftp.changeWorkingDirectory("/atmatech.com.br/ErroLogsPainelFX/");
    //abre um stream com o arquivo a ser enviado              
    InputStream is = new FileInputStream(file);
    //pega apenas o nome do arquivo             
    int idx = file.getName().lastIndexOf(File.separator);
    if (idx < 0)
        idx = 0;
    else
        idx++;
    nomeArquivo = file.getName().substring(idx, file.getName().length());
    //ajusta o tipo do arquivo a ser enviado  
    ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
    //faz o envio do arquivo  
    ftp.storeFile(nomeArquivo, is);
    ftp.disconnect();

}

From source file:it.zero11.acme.example.FTPChallengeListener.java

private boolean createChallengeFiles(String token, String challengeBody) {
    boolean success = false;
    FTPClient ftp = new FTPClient();
    try {//from  w ww  . j  av a2  s.c o m
        ftp.connect(host);
        if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
            ftp.disconnect();
            return false;
        }

        ftp.login(username, password);
        ftp.changeWorkingDirectory(webroot);
        ftp.makeDirectory(".well-known");
        ftp.changeWorkingDirectory(".well-known");
        ftp.makeDirectory("acme-challenge");
        ftp.changeWorkingDirectory("acme-challenge");
        ftp.enterLocalPassiveMode();
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE, FTPClient.BINARY_FILE_TYPE);
        ftp.setFileTransferMode(FTPClient.BINARY_FILE_TYPE);
        success = ftp.storeFile(token, new ByteArrayInputStream(challengeBody.getBytes()));
        if (!success)
            System.err.println("FTP error uploading file: " + ftp.getReplyCode() + ": " + ftp.getReplyString());
        ftp.logout();
    } catch (IOException e) {
        throw new AcmeException(e);
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
            }
        }
    }

    return success;
}

From source file:it.zero11.acme.example.FTPChallengeListener.java

private void deleteChallengeFiles() {
    FTPClient ftp = new FTPClient();
    try {//w w w  .  j  a  v  a  2 s .  c  o  m
        ftp.connect(host);
        if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
            ftp.disconnect();
            return;
        }

        ftp.login(username, password);
        ftp.changeWorkingDirectory(webroot);
        ftp.changeWorkingDirectory(".well-known");
        ftp.changeWorkingDirectory("acme-challenge");

        FTPFile[] subFiles = ftp.listFiles();

        if (subFiles != null && subFiles.length > 0) {
            for (FTPFile aFile : subFiles) {
                String currentFileName = aFile.getName();
                if (currentFileName.equals(".") || currentFileName.equals("..")) {
                    continue;
                } else {
                    ftp.deleteFile(currentFileName);
                }
            }
        }
        ftp.changeToParentDirectory();
        ftp.removeDirectory("acme-challenge");
        ftp.changeToParentDirectory();
        ftp.removeDirectory(".well-known");
        ftp.logout();
    } catch (IOException e) {
        throw new AcmeException(e);
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
            }
        }
    }
}