Example usage for org.apache.commons.net.ftp FTP BINARY_FILE_TYPE

List of usage examples for org.apache.commons.net.ftp FTP BINARY_FILE_TYPE

Introduction

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

Prototype

int BINARY_FILE_TYPE

To view the source code for org.apache.commons.net.ftp FTP BINARY_FILE_TYPE.

Click Source Link

Document

A constant used to indicate the file(s) being transfered should be treated as a binary image, i.e., no translations should be performed.

Usage

From source file:edu.jhu.cvrg.services.nodeDataService.DataStaging.java

/** Service that returns a short subset of an ecg stored in a specified file, suitable for graphical display.
 * /*  w  ww  .ja v a  2s. c om*/
 * @param param0 - Contains elements brokerURL, mySqlURL, fileName... etc
 *  brokerURL - web address of the data file repository 
 *  mySqlURL - address of the mySQL database containing the annotations
 *  fileName - file containing the ECG data in RDT format.
 *  fileSize - used to size the file reading buffer.
 *  offsetMilliSeconds - number of milliseconds from the beginning of the ECG at which to start the graph.
 *  durationMilliSeconds - The requested length of the returned data subset, in milliseconds.
 *  graphWidthPixels - Width of the zoomed graph in pixels(zoom factor*unzoomed width), hence the maximum points needed in the returned VisualizationData.
 * @return - OMElement containing the values in the results
 */
public org.apache.axiom.om.OMElement collectVisualizationData(org.apache.axiom.om.OMElement param0) {
    debugPrintln("** collectVisualizationData() 2.1 called; ");
    long startTime = System.currentTimeMillis(), stopTime = 0, elapsed = 0;

    boolean success = true, oldverbose = verbose;
    // create output parent OMElement
    OMFactory factory = OMAbstractFactory.getOMFactory();
    OMNamespace dsNs = factory.createOMNamespace("http://www.cvrgrid.org/nodeDataService/", "dataStaging");

    String resultfileName = "";
    String parameterfileName = "";
    //String[] headers;
    String[] cols;
    //      String parameters="";
    //      String sFeatureColumns = "";
    int lineCount = 0;

    String ftpHost = "", mySqlURL = "", fileName = "";
    String ftpUser = "";
    String ftpPassword = "";
    String tempFile = "";
    ApacheCommonsFtpWrapper ftpClient = null;
    long fileSize = 0;
    int offsetMilliSeconds = 0, durationMilliSeconds = 0, graphWidthPixels = 0;
    String[] saLeadCSV = null; // array of comma separated ECG values, one string per lead.
    VisualizationData visData = null;
    try {// Parse parameters
        Iterator iterator = param0.getChildren();
        ftpHost = ((OMElement) iterator.next()).getText();
        ftpUser = ((OMElement) iterator.next()).getText();
        ftpPassword = ((OMElement) iterator.next()).getText();
        mySqlURL = ((OMElement) iterator.next()).getText();
        fileName = ((OMElement) iterator.next()).getText();
        fileSize = Long.parseLong(((OMElement) iterator.next()).getText());
        offsetMilliSeconds = Integer.parseInt(((OMElement) iterator.next()).getText());
        durationMilliSeconds = Integer.parseInt(((OMElement) iterator.next()).getText());
        graphWidthPixels = Integer.parseInt(((OMElement) iterator.next()).getText());
        verbose = Boolean.parseBoolean(((OMElement) iterator.next()).getText());
        utils.setVerbose(verbose);

        debugPrintln("** verbose: " + verbose + " offsetMilliSeconds: " + offsetMilliSeconds
                + " durationMilliSeconds: " + durationMilliSeconds);

        // The filename and extension without any path.
        String fileNameOnly = fileName.substring(fileName.lastIndexOf(sep) + 1);
        // The relative directory this file is in.
        String relativeDir = fileName.substring(0, fileName.lastIndexOf(sep));
        tempFile = localFtpRoot + sep + fileNameOnly + System.currentTimeMillis();

        debugPrintln("[=====================================================================]");
        debugPrintln("fileName: " + fileName);
        debugPrintln(" fileSize: " + fileSize);
        debugPrintln(" offsetMilliSeconds: " + offsetMilliSeconds);
        debugPrintln(" durationMilliSeconds: " + durationMilliSeconds);
        debugPrintln(" graphWidthPixels: " + graphWidthPixels);

        debugPrintln("ftpHost: " + ftpHost);
        debugPrintln("ftpUser: " + ftpUser);
        debugPrintln("ftpPassword: " + ftpPassword);
        debugPrintln("fileNameOnly: \"" + fileNameOnly + "\"");
        debugPrintln("relativeDir: \"" + relativeDir + "\"");
        debugPrintln("tempFile: \"" + tempFile + "\"");
        debugPrintln("[=====================================================================]");

        ftpClient = new ApacheCommonsFtpWrapper(ftpHost, ftpUser, ftpPassword);
        ftpClient.verbose = verbose;
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        //           ftpClient.cd(parentFolderNode);
        debugPrintln("changeWorkingDirectory(" + remoteFtpRoot + relativeDir + ")");
        success = ftpClient.changeWorkingDirectory(remoteFtpRoot + relativeDir);
        if (success) {
            debugPrintln("Downloading: " + fileNameOnly);
            success = ftpClient.downloadFile(fileNameOnly, tempFile);
        } else {
            debugPrintln("Directory not found on FTP server: " + remoteFtpRoot);
        }

    } catch (OMException e) {
        System.err.println("collectVisualizationData failed while parsing parameters.");
        e.printStackTrace();
        success = false;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        success = false;
    }
    if (success) {
        try {//load data from ecg file 
            visData = fetchSubjectVisualization(tempFile, fileSize, offsetMilliSeconds, durationMilliSeconds,
                    graphWidthPixels);

            saLeadCSV = new String[visData.getRdtDataLeads()];
            //initialize all to an empty string.
            for (int lead = 0; lead < visData.getRdtDataLeads(); lead++) {
                saLeadCSV[lead] = "";
            }

            //build a comma delimited list for each column
            for (int row = 0; row < visData.getRdtDataLength(); row++) {
                for (int lead = 0; lead < visData.getRdtDataLeads(); lead++) {
                    saLeadCSV[lead] = saLeadCSV[lead] + visData.getRdtData()[row][lead] + ",";
                }
            }

            // trim trailing comma 
            for (int lead = 0; lead < visData.getRdtDataLeads(); lead++) {
                saLeadCSV[lead] = saLeadCSV[lead].substring(0, saLeadCSV[lead].length() - 1);
            }
        } catch (Exception e) {
            System.err.println("collectVisualizationData failed while loading data from ecg file.");
            e.printStackTrace();
            success = false;
        } finally {
            // remove tempFile
            deleteTempFile(tempFile);
        }
    } else {
        System.err.println("collectVisualizationData() failed while FTPing " + fileName + " to " + tempFile);
    }

    // build return xml
    OMElement collectVisualizationData = factory.createOMElement("collectVisualizationData", dsNs);
    if (success) {
        addOMEChild("status", "success", collectVisualizationData, factory, dsNs);
        addOMEChild("DataLength", String.valueOf(visData.getRdtDataLength()), collectVisualizationData, factory,
                dsNs);
        addOMEChild("DataLeads", String.valueOf(visData.getRdtDataLeads()), collectVisualizationData, factory,
                dsNs);
        addOMEChild("Offset", String.valueOf(visData.getOffset()), collectVisualizationData, factory, dsNs);
        addOMEChild("SkippedSamples", String.valueOf(visData.getSkippedSamples()), collectVisualizationData,
                factory, dsNs);
        addOMEChild("MsDuration", String.valueOf(visData.msDuration), collectVisualizationData, factory, dsNs);
        for (int lead = 0; lead < visData.getRdtDataLeads(); lead++) {
            addOMEChild("lead_" + lead, saLeadCSV[lead], collectVisualizationData, factory, dsNs);
        }
    } else {
        addOMEChild("status", "fail", collectVisualizationData, factory, dsNs);
    }

    verbose = oldverbose; // reset global to previous setting, in case it matters
    stopTime = System.currentTimeMillis();
    elapsed = (stopTime - startTime);
    debugPrintln(" finished, execution time(ms): " + elapsed);

    return collectVisualizationData;
}

From source file:com.droid.app.fotobot.FotoBot.java

public boolean files_to_ftp(List<String> FTP_files) {
    String server;/*ww w .j  a  va2s. c o  m*/
    int port;
    String user;
    String pass;

    String FTP_folder = "";

    if (FTP_server.contains("/")) {

        FTP_folder = FTP_server.substring(FTP_server.indexOf("/", 1));
        FTP_folder = FTP_folder.substring(1);

        server = FTP_server.substring(0, FTP_server.indexOf("/", 1));
    } else {
        server = FTP_server;
    }

    port = Integer.parseInt(FTP_port);
    user = FTP_username;
    pass = FTP_password;

    SendMessage("FTP user: " + "<br>" + user, MSG_PASS);
    SendMessage("FTP folder: " + "<br>" + FTP_folder, MSG_PASS);
    SendMessage("FTP server: " + "<br>" + server, MSG_PASS);

    FTPClient ftpClient = new FTPClient();

    try {
        int reply;

        ftpClient.connect(server, port);
        System.out.println("Connected to " + server + ".");
        System.out.print(ftpClient.getReplyString());
        reply = ftpClient.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftpClient.disconnect();
            System.err.println("FTP server refused connection.");
            SendMessage("FTP   ?", MSG_FAIL);
            return false;
        }
    } catch (Exception e) {
    }

    try {
        ftpClient.login(user, pass);
        ftpClient.enterLocalPassiveMode();
        if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            SendMessage(
                    " ?   FTP ?,      FTP  ?.",
                    MSG_FAIL);
            return false;
        }
    } catch (Exception e) {

    }

    // chdir

    if (FTP_folder.length() > 1) {
        try {
            ftpClient.changeWorkingDirectory(FTP_folder);

            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                ftpClient.disconnect();
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.err.println("FTP chdir error");
                SendMessage(
                        "FTP  ?    <br>" + FTP_folder,
                        MSG_FAIL);
                return false;
            }

            SendMessage("FTP   <br>" + FTP_folder, MSG_PASS);
            System.out.println("Successfully changed working directory.");
        } catch (Exception e) {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
            SendMessage("FTP  ?    <br>" + FTP_folder,
                    MSG_FAIL);
            System.out.println("Failed to change working directory.");
            return false;
        }
    }

    try {
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
    } catch (Exception e) {
        SendMessage("FTP   BINARY_FILE_TYPE", MSG_FAIL);
        System.out.println("Failed to change to BINARY_FILE_TYPE.");
        return false;
    }

    // APPROACH #1: uploads first file using an InputStream

    for (String str : FTP_files) {
        File firstLocalFile = new File(str);

        String firstRemoteFile = firstLocalFile.getName();

        try {
            InputStream inputStream = new FileInputStream(firstLocalFile);

            SendMessage("? ", MSG_PASS);
            boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
            inputStream.close();

            if (done) {
                SendMessage(" " + "<br>" + str + "<br>" + " ", MSG_PASS);
            }
        } catch (IOException ex) {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            SendMessage(" ?  " + "<br>" + str + "<br>"
                    + ftpClient.getReplyCode() + "\n" + ftpClient.getReplyString() + "\n" + ex.getMessage()
                    + "<br>"
                    + "     FTP  ?.",
                    MSG_FAIL);
            ex.printStackTrace();
        }

    }

    try {
        if (ftpClient.isConnected()) {
            ftpClient.logout();
            ftpClient.disconnect();
            SendMessage("FTP ???? ", MSG_PASS);
            fbpause(h, 3);
            return true;
        }
    } catch (IOException ex) {
        ex.printStackTrace();
        SendMessage("FTP ???? ", MSG_FAIL);
    }

    return false;

}

From source file:edu.jhu.cvrg.services.nodeDataService.DataStaging.java

/** Service that returns a short subset of an ecg stored in a specified file, suitable for graphical display.
 * /* w  w w.ja va2s .c  om*/
 * @param param0 - Contains elements brokerURL, mySqlURL, fileName... etc<BR>
 *  brokerURL - web address of the data file repository <BR>
 *  fileName - file containing the ECG data in RDT format.<BR>
 *  fileSize - used to size the file reading buffer.<BR>
 *  offsetMilliSeconds - number of milliseconds from the beginning of the ECG at which to start the graph.<BR>
 *  durationMilliSeconds - The requested length of the returned data subset, in milliseconds.<BR>
 *  graphWidthPixels - Width of the zoomed graph in pixels(zoom factor*unzoomed width), hence the maximum points needed in the returned VisualizationData.<BR>
 * @return - OMElement containing the values in the results
 */
public org.apache.axiom.om.OMElement collectWFDBdataSegment(org.apache.axiom.om.OMElement param0) {
    debugPrintln("** collectWFDBdataSegment() 1.0 called; ");
    long startTime = System.currentTimeMillis(), stopTime = 0, elapsed = 0;
    int iLeadCount = 0;
    boolean success = true, oldverbose = verbose;
    boolean bTestPattern = false;

    // create output parent OMElement
    OMFactory factory = OMAbstractFactory.getOMFactory();
    OMNamespace dsNs = factory.createOMNamespace("http://www.cvrgrid.org/nodeDataService/", "dataStaging");

    String ftpHost = "", mySqlURL = "", fileName = "";
    String ftpUser = "";
    String ftpPassword = "";
    String tempFile = "";
    ApacheCommonsFtpWrapper ftpClient = null;
    long fileSize = 0;
    int offsetMilliSeconds = 0, durationMilliSeconds = 0, graphWidthPixels = 0;
    String[] saLeadCSV = null; // array of comma separated ECG values, one string per lead.
    VisualizationData visData = null;
    try {// Parse parameters
        debugPrintln("- parsing the web service's parameters without regard to order.");
        // parse the input parameter's OMElement XML into a Map.
        Map<String, Object> paramMap = DataUtils.buildParamMap(param0);
        // Assign specific input parameters to local variables.
        fileName = (String) paramMap.get("fileName");
        ftpHost = (String) paramMap.get("ftpHost");
        ftpUser = (String) paramMap.get("ftpUser");
        ftpPassword = (String) paramMap.get("ftpPassword");
        fileSize = Long.parseLong((String) paramMap.get("fileSize"));
        offsetMilliSeconds = Integer.parseInt((String) paramMap.get("offsetMilliSeconds"));
        durationMilliSeconds = Integer.parseInt((String) paramMap.get("durationMilliSeconds"));
        graphWidthPixels = Integer.parseInt((String) paramMap.get("graphWidthPixels"));
        bTestPattern = Boolean.parseBoolean((String) paramMap.get("testPattern"));

        verbose = Boolean.parseBoolean((String) paramMap.get("verbose"));

        //**************************************************
        utils.setVerbose(verbose);

        debugPrintln("** verbose: " + verbose + " offsetMilliSeconds: " + offsetMilliSeconds
                + " durationMilliSeconds: " + durationMilliSeconds);

        // The filename and extension without any path.
        String fileNameOnly = fileName.substring(fileName.lastIndexOf(sep) + 1);
        // The relative directory this file is in.
        String relativeDir = fileName.substring(0, fileName.lastIndexOf(sep));
        tempFile = localFtpRoot + sep + fileNameOnly + System.currentTimeMillis();

        String sIgnoreMess = "";
        debugPrintln("[=====================================================================]");
        debugPrintln(" bTestPattern: " + bTestPattern);
        debugPrintln(" fileSize: " + fileSize);
        debugPrintln(" offsetMilliSeconds: " + offsetMilliSeconds);
        debugPrintln(" durationMilliSeconds: " + durationMilliSeconds);
        debugPrintln(" graphWidthPixels: " + graphWidthPixels);

        if (bTestPattern)
            sIgnoreMess = "Ignored: ";
        debugPrintln(sIgnoreMess + "fileName: " + fileName);
        debugPrintln(sIgnoreMess + "ftpHost: " + ftpHost);
        debugPrintln(sIgnoreMess + "ftpUser: " + ftpUser);
        debugPrintln(sIgnoreMess + "ftpPassword: " + ftpPassword);
        debugPrintln(sIgnoreMess + "fileNameOnly: \"" + fileNameOnly + "\"");
        debugPrintln(sIgnoreMess + "relativeDir: \"" + relativeDir + "\"");
        debugPrintln(sIgnoreMess + "tempFile: \"" + tempFile + "\"");
        debugPrintln("[=====================================================================]");

        if (!bTestPattern) {
            ftpClient = new ApacheCommonsFtpWrapper(ftpHost, ftpUser, ftpPassword);
            ftpClient.verbose = verbose;
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            debugPrintln("changeWorkingDirectory(" + remoteFtpRoot + relativeDir + ")");
            success = ftpClient.changeWorkingDirectory(remoteFtpRoot + relativeDir);
            if (success) {
                debugPrintln("Downloading: " + fileNameOnly);
                success = ftpClient.downloadFile(fileNameOnly, tempFile);
                debugPrintln("Download finished.");
            } else {
                debugPrintln("Directory not found on FTP server: " + remoteFtpRoot);
            }
        } else {
            debugPrintln("Skipping FTP in favor to the test pattern.");
            success = true;
        }
    } catch (OMException e) {
        System.err.println("collectVisualizationData failed while parsing parameters.");
        e.printStackTrace();
        success = false;
    } catch (IOException e) {
        e.printStackTrace();
        success = false;
    }
    if (success) {
        debugPrintln("Creating VisualizationData bean.");
        try {//load data from ecg file 
            if (bTestPattern) {
                visData = fetchSubjectVisualizationTestPattern(fileSize, offsetMilliSeconds,
                        durationMilliSeconds, graphWidthPixels);
                success = true;
            } else {
                visData = fetchWFDBdataSegment(tempFile, fileSize, offsetMilliSeconds, durationMilliSeconds,
                        graphWidthPixels);
            }
            iLeadCount = visData.getRdtDataLeads();
            saLeadCSV = new String[visData.getRdtDataLeads()];
            //initialize all to an empty string.
            for (int lead = 0; lead < iLeadCount; lead++) {
                debugPrintln("Initializing CSV for lead: " + lead + " of " + iLeadCount);
                saLeadCSV[lead] = "";
            }

            //build a comma delimited list for each column
            for (int row = 0; row < visData.getRdtDataLength(); row++) {
                for (int lead = 0; lead < iLeadCount; lead++) {
                    saLeadCSV[lead] = saLeadCSV[lead] + visData.getRdtData()[row][lead] + ",";
                }
            }

            // trim trailing comma 
            for (int lead = 0; lead < iLeadCount; lead++) {
                debugPrintln("Finishing CSV for lead: " + lead + " of " + iLeadCount);
                saLeadCSV[lead] = saLeadCSV[lead].substring(0, saLeadCSV[lead].length() - 1);
            }
        } catch (Exception e) {
            System.err.println("collectVisualizationData failed while loading data from ecg file.");
            e.printStackTrace();
            success = false;
        } finally {
            // remove tempFile
            if (!bTestPattern) {
                deleteTempFile(tempFile);
            }
        }
    } else {
        System.err.println("collectVisualizationData() failed while FTPing " + fileName + " to " + tempFile);
    }

    // build return xml
    OMElement collectVisualizationData = factory.createOMElement("collectVisualizationData", dsNs);
    if (success) {
        debugPrintln("Building OMElement from Web Service return values");
        addOMEChild("Status", "success", collectVisualizationData, factory, dsNs);
        addOMEChild("SampleCount", String.valueOf(visData.getRdtDataLength()), collectVisualizationData,
                factory, dsNs);
        addOMEChild("LeadCount", String.valueOf(iLeadCount), collectVisualizationData, factory, dsNs);
        addOMEChild("Offset", String.valueOf(visData.getOffset()), collectVisualizationData, factory, dsNs);
        addOMEChild("SkippedSamples", String.valueOf(visData.getSkippedSamples()), collectVisualizationData,
                factory, dsNs);
        addOMEChild("SegmentDuration", String.valueOf(visData.msDuration), collectVisualizationData, factory,
                dsNs);
        for (int lead = 0; lead < iLeadCount; lead++) {
            addOMEChild("lead_" + lead, saLeadCSV[lead], collectVisualizationData, factory, dsNs);
        }
    } else {
        addOMEChild("Status", "fail", collectVisualizationData, factory, dsNs);
    }

    verbose = oldverbose; // reset global to previous setting, in case it matters
    stopTime = System.currentTimeMillis();
    elapsed = (stopTime - startTime);
    debugPrintln(" finished, execution time(ms): " + elapsed);

    return collectVisualizationData;
}

From source file:com.netpace.aims.controller.application.WapApplicationHelper.java

public static boolean wapFTPZipFile(File transferFile) throws AimsException {

    log.debug("wapFTPZipFile FTP Start. FileName: " + transferFile.getName());
    boolean loginStatus = false;
    boolean dirChanged = false;

    FileInputStream transferStream = null;
    FTPClient ftpClient = new FTPClient();

    ConfigEnvProperties envProperties = ConfigEnvProperties.getInstance();
    //ftp server config
    String ftpServerAddress = envProperties.getProperty("wap.images.ftp.server.address");
    String ftpUser = envProperties.getProperty("wap.images.ftp.user.name");
    String ftpPassword = envProperties.getProperty("wap.images.ftp.user.password");
    String ftpWorkingDirectory = envProperties.getProperty("wap.images.ftp.working.dir");

    //general exception for ftp transfer
    AimsException aimsException = new AimsException("Error");
    aimsException.addException(new AimsException("error.wap.app.ftp.transfer"));

    String errorMessage = "";

    boolean transfered = false;
    try {/*from  w w  w.j av  a  2s. co m*/
        ftpClient.connect(ftpServerAddress);
        loginStatus = ftpClient.login(ftpUser, ftpPassword);
        log.debug("Connection to server " + ftpServerAddress + " " + (loginStatus ? "success" : "failure"));
        if (loginStatus) {
            dirChanged = ftpClient.changeWorkingDirectory(ftpWorkingDirectory);
            log.debug("change remote directory to " + ftpWorkingDirectory + ": " + dirChanged);
            if (dirChanged) {
                transferStream = new FileInputStream(transferFile);
                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                transfered = ftpClient.storeFile(transferFile.getName(), transferStream);
                log.debug(transferFile.getName() + " transfered: " + transfered + " on server: "
                        + ftpServerAddress);
                if (!transfered) {
                    errorMessage = "File: " + transferFile.getName() + " not transfered to "
                            + (ftpServerAddress + "/" + ftpServerAddress);
                    System.out.println("Error in FTP Transfer: " + errorMessage);
                    sendFTPErrorMail(errorMessage);
                    throw aimsException;
                }
            } else {
                errorMessage = "Directory: " + ftpWorkingDirectory + " not found in " + ftpServerAddress;
                System.out.println("Error in FTP Transfer: " + errorMessage);
                sendFTPErrorMail(errorMessage);
                throw aimsException;
            }
        } //end loginstatus
        else {
            errorMessage = "FTP Authentication failed. \n\nServer: " + ftpServerAddress + "\nUserID: " + ftpUser
                    + "\nPassword: " + ftpPassword;
            System.out.println("Error in FTP Transfer: " + errorMessage);
            sendFTPErrorMail(errorMessage);
            throw aimsException;
        }
    } //end try
    catch (FileNotFoundException e) {
        System.out.println("Exception: " + transferFile.getName() + " not found in temp directory");
        e.printStackTrace();//zip file not found
        throw aimsException;
    } catch (IOException ioe) {
        System.out.println("Exception: Error in connection " + ftpServerAddress);
        ioe.printStackTrace();
        sendFTPErrorMail("Error in connection to : " + ftpServerAddress + "\n\n"
                + MiscUtils.getExceptionStackTraceInfo(ioe));
        throw aimsException;
    } finally {
        try {
            //close stream
            if (transferStream != null) {
                transferStream.close();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    //logout. Issues QUIT command
                    ftpClient.logout();
                } catch (IOException ioex) {
                    ioex.printStackTrace();
                } finally {
                    try {
                        //disconnect ftp session
                        ftpClient.disconnect();
                    } catch (IOException ioexc) {
                        ioexc.printStackTrace();
                    }
                }
            }
        }

    }
    log.debug("wapFTPZipFile FTP end. FileName: " + transferFile.getName() + "\t transfered: " + transfered);
    return transfered;
}

From source file:com.microsoft.tooling.msservices.helpers.azure.AzureManagerImpl.java

@Override
public void publishWebArchiveArtifact(@NotNull String subscriptionId, @NotNull String webSpaceName,
        @NotNull String webSiteName, @NotNull String artifactPath, @NotNull boolean isDeployRoot,
        @NotNull String artifactName) throws AzureCmdException {
    WebSitePublishSettings webSitePublishSettings = getWebSitePublishSettings(subscriptionId, webSpaceName,
            webSiteName);/*w w w  . ja  va 2s .c om*/
    WebSitePublishSettings.FTPPublishProfile publishProfile = null;
    for (PublishProfile pp : webSitePublishSettings.getPublishProfileList()) {
        if (pp instanceof FTPPublishProfile) {
            publishProfile = (FTPPublishProfile) pp;
            break;
        }
    }

    if (publishProfile == null) {
        throw new AzureCmdException("Unable to retrieve FTP credentials to publish web site");
    }

    URI uri;

    try {
        uri = new URI(publishProfile.getPublishUrl());
    } catch (URISyntaxException e) {
        throw new AzureCmdException("Unable to parse FTP Publish Url information", e);
    }

    final FTPClient ftp = new FTPClient();

    try {
        ftp.connect(uri.getHost());
        final int replyCode = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(replyCode)) {
            ftp.disconnect();
            throw new AzureCmdException("Unable to connect to FTP server");
        }

        if (!ftp.login(publishProfile.getUserName(), publishProfile.getPassword())) {
            ftp.logout();
            throw new AzureCmdException("Unable to login to FTP server");
        }

        ftp.setFileType(FTP.BINARY_FILE_TYPE);

        if (publishProfile.isFtpPassiveMode()) {
            ftp.enterLocalPassiveMode();
        }

        String targetDir = getAbsolutePath(uri.getPath());
        targetDir += "/webapps";

        InputStream input = new FileInputStream(artifactPath);
        if (isDeployRoot) {
            ftp.storeFile(targetDir + "/ROOT.war", input);
        } else {
            ftp.storeFile(targetDir + "/" + artifactName + ".war", input);
        }
        input.close();
        ftp.logout();
    } catch (IOException e) {
        throw new AzureCmdException("Unable to connect to the FTP server", e);
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ignored) {
            }
        }
    }
}

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public String FTPGetFile(String sServer, String sSrcFileName, String sDstFileName, OutputStream out) {
    byte[] buffer = new byte[4096];
    int nRead = 0;
    long lTotalRead = 0;
    String sRet = sErrorPrefix + "FTP Get failed for " + sSrcFileName;
    String strRet = "";
    int reply = 0;
    FileOutputStream outStream = null;
    String sTmpDstFileName = fixFileName(sDstFileName);

    FTPClient ftp = new FTPClient();
    try {/*  w w  w. j  a va2 s  . c om*/
        ftp.connect(sServer);
        reply = ftp.getReplyCode();
        if (FTPReply.isPositiveCompletion(reply)) {
            ftp.login("anonymous", "b@t.com");
            reply = ftp.getReplyCode();
            if (FTPReply.isPositiveCompletion(reply)) {
                ftp.enterLocalPassiveMode();
                if (ftp.setFileType(FTP.BINARY_FILE_TYPE)) {
                    File dstFile = new File(sTmpDstFileName);
                    outStream = new FileOutputStream(dstFile);
                    FTPFile[] ftpFiles = ftp.listFiles(sSrcFileName);
                    if (ftpFiles.length > 0) {
                        long lFtpSize = ftpFiles[0].getSize();
                        if (lFtpSize <= 0)
                            lFtpSize = 1;

                        InputStream ftpIn = ftp.retrieveFileStream(sSrcFileName);
                        while ((nRead = ftpIn.read(buffer)) != -1) {
                            lTotalRead += nRead;
                            outStream.write(buffer, 0, nRead);
                            strRet = "\r" + lTotalRead + " of " + lFtpSize + " bytes received "
                                    + ((lTotalRead * 100) / lFtpSize) + "% completed";
                            out.write(strRet.getBytes());
                            out.flush();
                        }
                        ftpIn.close();
                        @SuppressWarnings("unused")
                        boolean bRet = ftp.completePendingCommand();
                        outStream.flush();
                        outStream.close();
                        strRet = ftp.getReplyString();
                        reply = ftp.getReplyCode();
                    } else {
                        strRet = sRet;
                    }
                }
                ftp.logout();
                ftp.disconnect();
                sRet = "\n" + strRet;
            } else {
                ftp.disconnect();
                System.err.println("FTP server refused login.");
            }
        } else {
            ftp.disconnect();
            System.err.println("FTP server refused connection.");
        }
    } catch (SocketException e) {
        sRet = e.getMessage();
        strRet = ftp.getReplyString();
        reply = ftp.getReplyCode();
        sRet += "\n" + strRet;
        e.printStackTrace();
    } catch (IOException e) {
        sRet = e.getMessage();
        strRet = ftp.getReplyString();
        reply = ftp.getReplyCode();
        sRet += "\n" + strRet;
        e.printStackTrace();
    }
    return (sRet);
}

From source file:net.yacy.grid.io.assets.FTPStorageFactory.java

public FTPStorageFactory(String server, int port, String username, String password, boolean deleteafterread)
        throws IOException {
    this.server = server;
    this.username = username == null ? "" : username;
    this.password = password == null ? "" : password;
    this.port = port;
    this.deleteafterread = deleteafterread;

    this.ftpClient = new Storage<byte[]>() {

        @Override/*  w w w  .  j  a v a 2s .c  o  m*/
        public void checkConnection() throws IOException {
            return;
        }

        private FTPClient initConnection() throws IOException {
            FTPClient ftp = new FTPClient();
            ftp.setDataTimeout(3000);
            ftp.setConnectTimeout(20000);
            if (FTPStorageFactory.this.port < 0 || FTPStorageFactory.this.port == DEFAULT_PORT) {
                ftp.connect(FTPStorageFactory.this.server);
            } else {
                ftp.connect(FTPStorageFactory.this.server, FTPStorageFactory.this.port);
            }
            ftp.enterLocalPassiveMode(); // the server opens a data port to which the client conducts data transfers
            int reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                if (ftp != null)
                    try {
                        ftp.disconnect();
                    } catch (Throwable ee) {
                    }
                throw new IOException("bad connection to ftp server: " + reply);
            }
            if (!ftp.login(FTPStorageFactory.this.username, FTPStorageFactory.this.password)) {
                if (ftp != null)
                    try {
                        ftp.disconnect();
                    } catch (Throwable ee) {
                    }
                throw new IOException("login failure");
            }
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            ftp.setBufferSize(8192);
            return ftp;
        }

        @Override
        public StorageFactory<byte[]> store(String path, byte[] asset) throws IOException {
            long t0 = System.currentTimeMillis();
            FTPClient ftp = initConnection();
            try {
                long t1 = System.currentTimeMillis();
                String file = cdPath(ftp, path);
                long t2 = System.currentTimeMillis();
                ftp.enterLocalPassiveMode();
                boolean success = ftp.storeFile(file, new ByteArrayInputStream(asset));
                long t3 = System.currentTimeMillis();
                if (!success)
                    throw new IOException("storage to path " + path + " was not successful (storeFile=false)");
                Data.logger.debug("FTPStorageFactory.store ftp store successfull: check connection = "
                        + (t1 - t0) + ", cdPath = " + (t2 - t1) + ", store = " + (t3 - t2));
            } catch (IOException e) {
                throw e;
            } finally {
                if (ftp != null)
                    try {
                        ftp.disconnect();
                    } catch (Throwable ee) {
                    }
            }
            return FTPStorageFactory.this;
        }

        @Override
        public Asset<byte[]> load(String path) throws IOException {
            FTPClient ftp = initConnection();
            ByteArrayOutputStream baos = null;
            byte[] b = null;
            try {
                String file = cdPath(ftp, path);
                baos = new ByteArrayOutputStream();
                ftp.retrieveFile(file, baos);
                b = baos.toByteArray();
                if (FTPStorageFactory.this.deleteafterread)
                    try {
                        boolean deleted = ftp.deleteFile(file);
                        FTPFile[] remaining = ftp.listFiles();
                        if (remaining.length == 0) {
                            ftp.cwd("/");
                            if (path.startsWith("/"))
                                path = path.substring(1);
                            int p = path.indexOf('/');
                            if (p > 0)
                                path = path.substring(0, p);
                            ftp.removeDirectory(path);
                        }
                    } catch (Throwable e) {
                        Data.logger.warn("FTPStorageFactory.load failed to remove asset " + path, e);
                    }
            } catch (IOException e) {
                throw e;
            } finally {
                if (ftp != null)
                    try {
                        ftp.disconnect();
                    } catch (Throwable ee) {
                    }
            }
            return new Asset<byte[]>(FTPStorageFactory.this, b);
        }

        @Override
        public void close() {
        }

        private String cdPath(FTPClient ftp, String path) throws IOException {
            int success_code = ftp.cwd("/");
            if (success_code >= 300)
                throw new IOException("cannot cd into " + path + ": " + success_code);
            if (path.length() == 0 || path.equals("/"))
                return "";
            if (path.charAt(0) == '/')
                path = path.substring(1); // we consider that all paths are absolute to / (home)
            int p;
            while ((p = path.indexOf('/')) > 0) {
                String dir = path.substring(0, p);
                int code = ftp.cwd(dir);
                if (code >= 300) {
                    // path may not exist, try to create the path
                    boolean success = ftp.makeDirectory(dir);
                    if (!success)
                        throw new IOException("unable to create directory " + dir + " for path " + path);
                    code = ftp.cwd(dir);
                    if (code >= 300)
                        throw new IOException("unable to cwd into directory " + dir + " for path " + path);
                }
                path = path.substring(p + 1);
            }
            return path;
        }
    };
}

From source file:no.imr.sea2data.core.util.FTPUtil.java

/**
 * Download a single file from the FTP server
 *
 * @param ftpClient an instance of org.apache.commons.net.ftp.FTPClient
 * class./*from w  w w .  j a  v a  2 s  . co m*/
 * @param remoteFilePath path of the file on the server
 * @param localFile path of directory where the file will be stored
 * @return true if the file was downloaded successfully, false otherwise
 * @throws IOException if any network or IO error occurred.
 */
public static boolean retrieveFile(FTPClient ftpClient, String remoteFilePath, String localFile)
        throws IOException {
    File downloadFile = new File(localFile);
    File parentDir = downloadFile.getParentFile();
    if (!parentDir.exists()) {
        parentDir.mkdir();
    }
    try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(downloadFile))) {
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        return ftpClient.retrieveFile(remoteFilePath, outputStream);
    } catch (IOException ex) {
        throw ex;
    }
}

From source file:nz.govt.natlib.ndha.wctdpsdepositor.filemover.FtpFileMover.java

public void connect(WctDepositParameter depositParameter) {
    try {/*from   w  ww. jav a2 s. c  om*/
        this.ftpClient = ftpClientFactory.createInstance();

        ftpClient.connect(depositParameter.getFtpHost());
        ftpClient.user(depositParameter.getFtpUserName());
        ftpClient.pass(depositParameter.getFtpPassword());
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
    } catch (IOException ioe) {
        throw new RuntimeException("Failed to open connection to FTP server: " + depositParameter.getFtpHost(),
                ioe);
    }

}

From source file:nz.govt.natlib.ndha.wctdpsdepositor.filemover.FtpFileMoverTest.java

@Test
public void test_connect() throws IOException {
    Mockery mockContext = constructMockContext();

    final FTPClient mockedFtpClient = mockContext.mock(FTPClient.class);
    final FtpClientFactory mockedFactory = mockContext.mock(FtpClientFactory.class);

    mockContext.checking(new Expectations() {
        {//from  ww  w.j a  v a2  s  . co m
            one(mockedFactory).createInstance();
            will(returnValue(mockedFtpClient));

            one(mockedFtpClient).connect(with(any(String.class)));
            one(mockedFtpClient).user(with(any(String.class)));
            will(returnValue(1));

            one(mockedFtpClient).pass(with(any(String.class)));
            one(mockedFtpClient).setFileType(FTP.BINARY_FILE_TYPE);
        }
    });

    WctDepositParameter depositParameter = new WctDepositParameter();
    FtpFileMover ftpFileMover = new FtpFileMover(mockedFactory);
    ftpFileMover.connect(depositParameter);

    mockContext.assertIsSatisfied();
}