Search in sources :

Example 1 with PrintCommandListener

use of org.apache.commons.net.PrintCommandListener in project network-monitor by caarmen.

the class SpeedTestUpload method upload.

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();
    ftp.setConnectTimeout(TIMEOUT);
    ftp.setDataTimeout(TIMEOUT);
    ftp.setDefaultTimeout(TIMEOUT);
    // For debugging, we'll log all the ftp commands
    if (BuildConfig.DEBUG) {
        PrintCommandListener printCommandListener = new PrintCommandListener(System.out);
        ftp.addProtocolCommandListener(printCommandListener);
    }
    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);
    }
}
Also used : SocketException(java.net.SocketException) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) PrintCommandListener(org.apache.commons.net.PrintCommandListener) IOException(java.io.IOException) FTPClient(org.apache.commons.net.ftp.FTPClient) FileInputStream(java.io.FileInputStream)

Example 2 with PrintCommandListener

use of org.apache.commons.net.PrintCommandListener in project irontest by zheng-wang.

the class FTPTeststepRunner method put.

private void put(Endpoint endpoint, FtpPutRequest ftpPutRequest) throws IOException {
    String username = StringUtils.trimToEmpty(endpoint.getUsername());
    String remoteFilePath = StringUtils.trimToEmpty(ftpPutRequest.getRemoteFilePath());
    byte[] fileBytes;
    // validate arguments
    if ("".equals(username)) {
        throw new IllegalArgumentException("Username not specified in Endpoint.");
    } else if ("".equals(remoteFilePath)) {
        throw new IllegalArgumentException("Target File Path not specified.");
    }
    if (ftpPutRequest instanceof FtpPutRequestFileFromText) {
        FtpPutRequestFileFromText ftpPutRequestFileFromText = (FtpPutRequestFileFromText) ftpPutRequest;
        String fileContent = ftpPutRequestFileFromText.getFileContent();
        // validate arguments
        if ("".equals(StringUtils.trimToEmpty(fileContent))) {
            throw new IllegalArgumentException("No file content.");
        }
        fileBytes = fileContent.getBytes();
    } else {
        FtpPutRequestFileFromFile ftpPutRequestFileFromFile = (FtpPutRequestFileFromFile) ftpPutRequest;
        fileBytes = ftpPutRequestFileFromFile.getFileContent();
        // validate arguments
        if (fileBytes == null || fileBytes.length == 0) {
            throw new IllegalArgumentException("No file content.");
        }
    }
    FTPEndpointProperties endpointProperties = (FTPEndpointProperties) endpoint.getOtherProperties();
    String password = getDecryptedEndpointPassword();
    FTPClient ftpClient;
    if (endpointProperties.isUseSSL()) {
        ftpClient = new FTPSClient();
        ((FTPSClient) ftpClient).setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
    } else {
        ftpClient = new FTPClient();
    }
    ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
    ftpClient.addProtocolCommandListener(new ProtocolCommandListener() {

        @Override
        public void protocolCommandSent(ProtocolCommandEvent event) {
        }

        @Override
        public void protocolReplyReceived(ProtocolCommandEvent event) {
            if (FTPReply.isNegativePermanent(event.getReplyCode())) {
                throw new RuntimeException("Failed to put the file. " + event.getMessage());
            }
        }
    });
    try {
        ftpClient.connect(endpoint.getHost(), endpoint.getPort());
        ftpClient.login(username, password);
        ftpClient.enterLocalPassiveMode();
        if (endpointProperties.isUseSSL()) {
            ((FTPSClient) ftpClient).execPROT("P");
        }
        ftpClient.storeFile(remoteFilePath, new ByteArrayInputStream(fileBytes));
    } finally {
        ftpClient.disconnect();
    }
}
Also used : ProtocolCommandEvent(org.apache.commons.net.ProtocolCommandEvent) FTPClient(org.apache.commons.net.ftp.FTPClient) ByteArrayInputStream(java.io.ByteArrayInputStream) FTPEndpointProperties(io.irontest.models.endpoint.FTPEndpointProperties) FTPSClient(org.apache.commons.net.ftp.FTPSClient) PrintCommandListener(org.apache.commons.net.PrintCommandListener) ProtocolCommandListener(org.apache.commons.net.ProtocolCommandListener) PrintWriter(java.io.PrintWriter)

Example 3 with PrintCommandListener

use of org.apache.commons.net.PrintCommandListener in project audit4j-core by audit4j.

the class FTPArchiveClient method init.

/**
 * Inits the.
 *
 * @param args the args
 * @throws UnknownHostException the unknown host exception
 */
public static void init(String[] args) throws UnknownHostException {
    boolean storeFile = false, binaryTransfer = false, error = false, listFiles = false, listNames = false, hidden = false;
    boolean localActive = false, useEpsvWithIPv4 = false, feat = false, printHash = false;
    boolean mlst = false, mlsd = false;
    boolean lenient = false;
    long keepAliveTimeout = -1;
    int controlKeepAliveReplyTimeout = -1;
    // listings require 3 params
    int minParams = 5;
    // SSL protocol
    String protocol = null;
    String doCommand = null;
    String trustmgr = null;
    String proxyHost = null;
    int proxyPort = 80;
    String proxyUser = null;
    String proxyPassword = null;
    String username = null;
    String password = null;
    int base = 0;
    for (base = 0; base < args.length; base++) {
        if (args[base].equals("-s")) {
            storeFile = true;
        } else if (args[base].equals("-a")) {
            localActive = true;
        } else if (args[base].equals("-A")) {
            username = "anonymous";
            password = System.getProperty("user.name") + "@" + InetAddress.getLocalHost().getHostName();
        } else if (args[base].equals("-b")) {
            binaryTransfer = true;
        } else if (args[base].equals("-c")) {
            doCommand = args[++base];
            minParams = 3;
        } else if (args[base].equals("-d")) {
            mlsd = true;
            minParams = 3;
        } else if (args[base].equals("-e")) {
            useEpsvWithIPv4 = true;
        } else if (args[base].equals("-f")) {
            feat = true;
            minParams = 3;
        } else if (args[base].equals("-h")) {
            hidden = true;
        } else if (args[base].equals("-k")) {
            keepAliveTimeout = Long.parseLong(args[++base]);
        } else if (args[base].equals("-l")) {
            listFiles = true;
            minParams = 3;
        } else if (args[base].equals("-L")) {
            lenient = true;
        } else if (args[base].equals("-n")) {
            listNames = true;
            minParams = 3;
        } else if (args[base].equals("-p")) {
            protocol = args[++base];
        } else if (args[base].equals("-t")) {
            mlst = true;
            minParams = 3;
        } else if (args[base].equals("-w")) {
            controlKeepAliveReplyTimeout = Integer.parseInt(args[++base]);
        } else if (args[base].equals("-T")) {
            trustmgr = args[++base];
        } else if (args[base].equals("-PrH")) {
            proxyHost = args[++base];
            String[] parts = proxyHost.split(":");
            if (parts.length == 2) {
                proxyHost = parts[0];
                proxyPort = Integer.parseInt(parts[1]);
            }
        } else if (args[base].equals("-PrU")) {
            proxyUser = args[++base];
        } else if (args[base].equals("-PrP")) {
            proxyPassword = args[++base];
        } else if (args[base].equals("-#")) {
            printHash = true;
        } else {
            break;
        }
    }
    int remain = args.length - base;
    if (username != null) {
        minParams -= 2;
    }
    if (// server, user, pass, remote, local [protocol]
    remain < minParams) {
        System.err.println(USAGE);
        System.exit(1);
    }
    String server = args[base++];
    int port = 0;
    String[] parts = server.split(":");
    if (parts.length == 2) {
        server = parts[0];
        port = Integer.parseInt(parts[1]);
    }
    if (username == null) {
        username = args[base++];
        password = args[base++];
    }
    String remote = null;
    if (args.length - base > 0) {
        remote = args[base++];
    }
    String local = null;
    if (args.length - base > 0) {
        local = args[base++];
    }
    final FTPClient ftp;
    if (protocol == null) {
        if (proxyHost != null) {
            System.out.println("Using HTTP proxy server: " + proxyHost);
            ftp = new FTPHTTPClient(proxyHost, proxyPort, proxyUser, proxyPassword);
        } else {
            ftp = new FTPClient();
        }
    } else {
        FTPSClient ftps;
        if (protocol.equals("true")) {
            ftps = new FTPSClient(true);
        } else if (protocol.equals("false")) {
            ftps = new FTPSClient(false);
        } else {
            String[] prot = protocol.split(",");
            if (prot.length == 1) {
                // Just protocol
                ftps = new FTPSClient(protocol);
            } else {
                // protocol,true|false
                ftps = new FTPSClient(prot[0], Boolean.parseBoolean(prot[1]));
            }
        }
        ftp = ftps;
        if ("all".equals(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
        } else if ("valid".equals(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager());
        } else if ("none".equals(trustmgr)) {
            ftps.setTrustManager(null);
        }
    }
    if (printHash) {
        ftp.setCopyStreamListener(createListener());
    }
    if (keepAliveTimeout >= 0) {
        ftp.setControlKeepAliveTimeout(keepAliveTimeout);
    }
    if (controlKeepAliveReplyTimeout >= 0) {
        ftp.setControlKeepAliveReplyTimeout(controlKeepAliveReplyTimeout);
    }
    ftp.setListHiddenFiles(hidden);
    // suppress login details
    ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));
    try {
        int reply;
        if (port > 0) {
            ftp.connect(server, port);
        } else {
            ftp.connect(server);
        }
        System.out.println("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));
        // 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.getSystemType());
        if (binaryTransfer) {
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
        } else {
            // in theory this should not be necessary as servers should
            // default to ASCII
            // but they don't all do so - see NET-500
            ftp.setFileType(FTP.ASCII_FILE_TYPE);
        }
        // behind firewalls these days.
        if (localActive) {
            ftp.enterLocalActiveMode();
        } else {
            ftp.enterLocalPassiveMode();
        }
        ftp.setUseEPSVwithIPv4(useEpsvWithIPv4);
        if (storeFile) {
            InputStream input;
            input = new FileInputStream(local);
            ftp.storeFile(remote, input);
            input.close();
        } else if (listFiles) {
            if (lenient) {
                FTPClientConfig config = new FTPClientConfig();
                config.setLenientFutureDates(true);
                ftp.configure(config);
            }
            for (FTPFile f : ftp.listFiles(remote)) {
                System.out.println(f.getRawListing());
                System.out.println(f.toFormattedString());
            }
        } else if (mlsd) {
            for (FTPFile f : ftp.mlistDir(remote)) {
                System.out.println(f.getRawListing());
                System.out.println(f.toFormattedString());
            }
        } else if (mlst) {
            FTPFile f = ftp.mlistFile(remote);
            if (f != null) {
                System.out.println(f.toFormattedString());
            }
        } else if (listNames) {
            for (String s : ftp.listNames(remote)) {
                System.out.println(s);
            }
        } else if (feat) {
            // boolean feature check
            if (remote != null) {
                // See if the command is present
                if (ftp.hasFeature(remote)) {
                    System.out.println("Has feature: " + remote);
                } else {
                    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                        System.out.println("FEAT " + remote + " was not detected");
                    } else {
                        System.out.println("Command failed: " + ftp.getReplyString());
                    }
                }
                // Strings feature check
                String[] features = ftp.featureValues(remote);
                if (features != null) {
                    for (String f : features) {
                        System.out.println("FEAT " + remote + "=" + f + ".");
                    }
                } else {
                    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                        System.out.println("FEAT " + remote + " is not present");
                    } else {
                        System.out.println("Command failed: " + ftp.getReplyString());
                    }
                }
            } else {
                if (ftp.features()) {
                // Command listener has already printed the output
                } else {
                    System.out.println("Failed: " + ftp.getReplyString());
                }
            }
        } else if (doCommand != null) {
            if (ftp.doCommand(doCommand, remote)) {
            // Command listener has already printed the output
            // for(String s : ftp.getReplyStrings()) {
            // System.out.println(s);
            // }
            } else {
                System.out.println("Failed: " + ftp.getReplyString());
            }
        } else {
            OutputStream output;
            output = new FileOutputStream(local);
            ftp.retrieveFile(remote, output);
            output.close();
        }
        // check that control connection is working OK
        ftp.noop();
        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);
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) FTPClientConfig(org.apache.commons.net.ftp.FTPClientConfig) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FTPHTTPClient(org.apache.commons.net.ftp.FTPHTTPClient) FTPFile(org.apache.commons.net.ftp.FTPFile) IOException(java.io.IOException) FTPClient(org.apache.commons.net.ftp.FTPClient) FileInputStream(java.io.FileInputStream) FTPConnectionClosedException(org.apache.commons.net.ftp.FTPConnectionClosedException) FileOutputStream(java.io.FileOutputStream) FTPSClient(org.apache.commons.net.ftp.FTPSClient) PrintCommandListener(org.apache.commons.net.PrintCommandListener) PrintWriter(java.io.PrintWriter)

Example 4 with PrintCommandListener

use of org.apache.commons.net.PrintCommandListener in project network-monitor by caarmen.

the class Emailer method sendEmail.

/**
 * Sends an e-mail in UTF-8 encoding.
 *
 * @param protocol    this has been tested with "TLS", "SSL", and null.
 * @param attachments optional attachments to include in the mail.
 */
static void sendEmail(String protocol, String server, int port, String user, String password, String from, String[] recipients, String subject, String body, Set<File> attachments) throws Exception {
    // Set up the mail connectivity
    final AuthenticatingSMTPClient client;
    if (protocol == null)
        client = new AuthenticatingSMTPClient();
    else
        client = new AuthenticatingSMTPClient(protocol);
    if (BuildConfig.DEBUG)
        client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));
    client.setDefaultTimeout(SMTP_TIMEOUT_MS);
    client.setCharset(Charset.forName(ENCODING));
    client.connect(server, port);
    checkReply(client);
    client.helo("[" + client.getLocalAddress().getHostAddress() + "]");
    checkReply(client);
    if ("TLS".equals(protocol)) {
        if (!client.execTLS()) {
            checkReply(client);
            throw new RuntimeException("Could not start tls");
        }
    }
    client.auth(AuthenticatingSMTPClient.AUTH_METHOD.LOGIN, user, password);
    checkReply(client);
    // Set up the mail participants
    client.setSender(from);
    checkReply(client);
    for (String recipient : recipients) {
        client.addRecipient(recipient);
        checkReply(client);
    }
    // Set up the mail content
    Writer writer = client.sendMessageData();
    SimpleSMTPHeader header = new SimpleSMTPHeader(from, recipients[0], subject);
    for (int i = 1; i < recipients.length; i++) header.addCC(recipients[i]);
    // Just plain text mail: no attachments
    if (attachments == null || attachments.isEmpty()) {
        header.addHeaderField("Content-Type", "text/plain; charset=" + ENCODING);
        writer.write(header.toString());
        writer.write(body);
    } else // Mail with attachments
    {
        String boundary = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 28);
        header.addHeaderField("Content-Type", "multipart/mixed; boundary=" + boundary);
        writer.write(header.toString());
        // Write the main text message
        writer.write("--" + boundary + "\n");
        writer.write("Content-Type: text/plain; charset=" + ENCODING + "\n\n");
        writer.write(body);
        writer.write("\n");
        // Write the attachments
        appendAttachments(writer, boundary, attachments);
        writer.write("--" + boundary + "--\n\n");
    }
    writer.close();
    if (!client.completePendingCommand()) {
        throw new RuntimeException("Could not send mail");
    }
    client.logout();
    client.disconnect();
}
Also used : AuthenticatingSMTPClient(org.apache.commons.net.smtp.AuthenticatingSMTPClient) PrintCommandListener(org.apache.commons.net.PrintCommandListener) PrintWriter(java.io.PrintWriter) Writer(java.io.Writer) SimpleSMTPHeader(org.apache.commons.net.smtp.SimpleSMTPHeader) PrintWriter(java.io.PrintWriter)

Example 5 with PrintCommandListener

use of org.apache.commons.net.PrintCommandListener in project alfresco-repository by Alfresco.

the class FTPServerTest method connectClient.

private FTPClient connectClient() throws IOException {
    FTPClient ftp = new FTPClient();
    if (logger.isDebugEnabled()) {
        ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
    }
    ftp.connect(HOSTNAME, ftpConfigSection.getFTPPort());
    return ftp;
}
Also used : PrintCommandListener(org.apache.commons.net.PrintCommandListener) FTPClient(org.apache.commons.net.ftp.FTPClient) PrintWriter(java.io.PrintWriter)

Aggregations

PrintCommandListener (org.apache.commons.net.PrintCommandListener)5 PrintWriter (java.io.PrintWriter)4 FTPClient (org.apache.commons.net.ftp.FTPClient)4 FileInputStream (java.io.FileInputStream)2 IOException (java.io.IOException)2 InputStream (java.io.InputStream)2 FTPSClient (org.apache.commons.net.ftp.FTPSClient)2 FTPEndpointProperties (io.irontest.models.endpoint.FTPEndpointProperties)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 FileOutputStream (java.io.FileOutputStream)1 OutputStream (java.io.OutputStream)1 Writer (java.io.Writer)1 SocketException (java.net.SocketException)1 ProtocolCommandEvent (org.apache.commons.net.ProtocolCommandEvent)1 ProtocolCommandListener (org.apache.commons.net.ProtocolCommandListener)1 FTPClientConfig (org.apache.commons.net.ftp.FTPClientConfig)1 FTPConnectionClosedException (org.apache.commons.net.ftp.FTPConnectionClosedException)1 FTPFile (org.apache.commons.net.ftp.FTPFile)1 FTPHTTPClient (org.apache.commons.net.ftp.FTPHTTPClient)1 AuthenticatingSMTPClient (org.apache.commons.net.smtp.AuthenticatingSMTPClient)1