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

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

Introduction

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

Prototype

public void enterLocalPassiveMode() 

Source Link

Document

Set the current data connection mode to PASSIVE_LOCAL_DATA_CONNECTION_MODE .

Usage

From source file:org.kuali.kfs.module.cg.service.impl.CfdaServiceImpl.java

/**
 * @return//w w w  .  j av a  2s .c  o m
 * @throws IOException
 */
public SortedMap<String, CFDA> getGovCodes() throws IOException {
    Calendar calendar = dateTimeService.getCurrentCalendar();
    SortedMap<String, CFDA> govMap = new TreeMap<String, CFDA>();

    // ftp://ftp.cfda.gov/programs09187.csv
    String govURL = parameterService.getParameterValueAsString(CfdaBatchStep.class,
            KFSConstants.SOURCE_URL_PARAMETER);
    String fileName = StringUtils.substringAfterLast(govURL, "/");
    govURL = StringUtils.substringBeforeLast(govURL, "/");
    if (StringUtils.contains(govURL, "ftp://")) {
        govURL = StringUtils.remove(govURL, "ftp://");
    }

    // need to pull off the '20' in 2009
    String year = "" + calendar.get(Calendar.YEAR);
    year = year.substring(2, 4);
    fileName = fileName + year;

    // the last 3 numbers in the file name are the day of the year, but the files are from "yesterday"
    fileName = fileName + String.format("%03d", calendar.get(Calendar.DAY_OF_YEAR) - 1);
    fileName = fileName + ".csv";

    LOG.info("Getting government file: " + fileName + " for update");

    InputStream inputStream = null;
    FTPClient ftp = new FTPClient();
    try {
        ftp.connect(govURL);
        int reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            LOG.error("FTP connection to server not established.");
            throw new IOException("FTP connection to server not established.");
        }

        boolean isLoggedIn = ftp.login("anonymous", "");
        if (!isLoggedIn) {
            LOG.error("Could not login as anonymous.");
            throw new IOException("Could not login as anonymous.");
        }

        LOG.info("Successfully connected and logged in");
        ftp.enterLocalPassiveMode();
        inputStream = ftp.retrieveFileStream(fileName);
        if (inputStream != null) {
            LOG.info("reading input stream");
            InputStreamReader screenReader = new InputStreamReader(inputStream);
            BufferedReader screen = new BufferedReader(screenReader);

            CSVReader csvReader = new CSVReader(screenReader, ',', '"', 1);
            List<String[]> lines = csvReader.readAll();
            for (String[] line : lines) {
                String title = line[0];
                String number = line[1];

                CFDA cfda = new CFDA();
                cfda.setCfdaNumber(number);
                cfda.setCfdaProgramTitleName(title);

                govMap.put(number, cfda);
            }
        }

        ftp.logout();
        ftp.disconnect();
    } finally {
        if (ftp.isConnected()) {
            ftp.disconnect();
        }
    }

    return govMap;
}

From source file:org.kuali.kra.external.Cfda.service.impl.CfdaServiceImpl.java

/**
 * This method connects to the FTP server.
 * @param url//ww  w  .  j a va2s  . com
 * @return ftp
 */
public FTPClient connect(String url) {
    FTPClient ftp = new FTPClient();
    try {
        ftp.connect(getGovURL());
        // Entering passive mode to prevent firewall issues. The client will establish a  data transfer
        // connection.
        ftp.enterLocalPassiveMode();
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            LOG.error("FTP connection to server not established.");
            throw new IOException("FTP connection to server not established.");
        }

        boolean loggedIn = ftp.login(Constants.CFDA_GOV_LOGIN_USERNAME, "");
        LOG.info("Logged in as " + Constants.CFDA_GOV_LOGIN_USERNAME);
        if (!loggedIn) {
            LOG.error("Could not login as anonymous.");
            throw new IOException("Could not login as anonymous.");
        }

    } catch (IOException io) {
        LOG.error(io.getMessage());
    }
    return ftp;
}

From source file:org.kuali.ole.coa.service.impl.CfdaServiceImpl.java

/**
 * @return/*from  ww w .  j  av a 2  s.c om*/
 * @throws IOException
 */
public SortedMap<String, CFDA> getGovCodes() throws IOException {
    Calendar calendar = SpringContext.getBean(DateTimeService.class).getCurrentCalendar();
    SortedMap<String, CFDA> govMap = new TreeMap<String, CFDA>();

    // ftp://ftp.cfda.gov/programs09187.csv
    String govURL = SpringContext.getBean(ParameterService.class).getParameterValueAsString(CfdaBatchStep.class,
            OLEConstants.SOURCE_URL_PARAMETER);
    String fileName = StringUtils.substringAfterLast(govURL, "/");
    govURL = StringUtils.substringBeforeLast(govURL, "/");
    if (StringUtils.contains(govURL, "ftp://")) {
        govURL = StringUtils.remove(govURL, "ftp://");
    }

    // need to pull off the '20' in 2009
    String year = "" + calendar.get(Calendar.YEAR);
    year = year.substring(2, 4);
    fileName = fileName + year;

    // the last 3 numbers in the file name are the day of the year, but the files are from "yesterday"
    fileName = fileName + String.format("%03d", calendar.get(Calendar.DAY_OF_YEAR) - 1);
    fileName = fileName + ".csv";

    LOG.info("Getting government file: " + fileName + " for update");

    InputStream inputStream = null;
    FTPClient ftp = new FTPClient();
    try {
        ftp.connect(govURL);
        int reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            LOG.error("FTP connection to server not established.");
            throw new IOException("FTP connection to server not established.");
        }

        boolean loggedIn = ftp.login("anonymous", "");
        if (!loggedIn) {
            LOG.error("Could not login as anonymous.");
            throw new IOException("Could not login as anonymous.");
        }

        LOG.info("Successfully connected and logged in");
        ftp.enterLocalPassiveMode();
        inputStream = ftp.retrieveFileStream(fileName);
        if (inputStream != null) {
            LOG.info("reading input stream");
            InputStreamReader screenReader = new InputStreamReader(inputStream);
            BufferedReader screen = new BufferedReader(screenReader);

            CSVReader csvReader = new CSVReader(screenReader, ',', '"', 1);
            List<String[]> lines = csvReader.readAll();
            for (String[] line : lines) {
                String title = line[0];
                String number = line[1];

                CFDA cfda = new CFDA();
                cfda.setCfdaNumber(number);
                cfda.setCfdaProgramTitleName(title);

                govMap.put(number, cfda);
            }
        }

        ftp.logout();
        ftp.disconnect();
    } finally {
        if (ftp.isConnected()) {
            ftp.disconnect();
        }
    }

    return govMap;
}

From source file:org.kuali.ole.module.purap.transmission.service.impl.TransmissionServiceImpl.java

/**
 * This method is to perform file upload
 *
 * @param ftpHostname// w  w w. j a va  2  s.c  o  m
 * @param ftpUsername
 * @param ftpPassword
 * @param file
 * @param fileName
 */
@Override
public void doFTPUpload(String ftpHostname, String ftpUsername, String ftpPassword, String file,
        String fileName) {
    LOG.trace("************************************doFTPUpload() started************************************");
    FTPClient ftpClient = new FTPClient();
    FileInputStream inputStream = null;
    FileOutputStream outputStream = null;
    try {
        ftpClient.connect(ftpHostname);
        ftpClient.login(ftpUsername, ftpPassword);
        ftpClient.enterLocalPassiveMode();
        int reply = ftpClient.getReplyCode();
        if (FTPReply.isPositiveCompletion(reply)) {
            LOG.debug("Connected to FTP server.");
        } else {
            LOG.debug("FTP server refused connection.");
        }

        // upload
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        String fileLocation = getFileLocation();
        if (LOG.isDebugEnabled()) {
            LOG.debug("File Location in FTP Server================>" + fileLocation);
            LOG.debug("File source=================================>" + file);
            LOG.debug("FileName====================================>" + fileName);
        }
        ftpClient.mkd(fileLocation);
        ftpClient.cwd(fileLocation);
        inputStream = new FileInputStream(file);
        ftpClient.storeFile(fileName, inputStream);

        ftpClient.logout();
        inputStream.close();
    } catch (Exception e) {
        LOG.error("Exception performing SFTP upload of " + file + " to " + ftpHostname, e);
        throw new RuntimeException(e);
    }
    LOG.trace(
            "************************************doFTPUpload() completed************************************");
}

From source file:org.mule.transport.ftp.FtpConnector.java

/**
 * Passive mode is OFF by default. The value is taken from the connector
 * settings. In case there are any overriding properties set on the endpoint,
 * those will be used.//from   w ww . j a  va2s .  co m
 *
 * @see #setPassive(boolean)
 */
public void enterActiveOrPassiveMode(FTPClient client, ImmutableEndpoint endpoint) {
    // well, no endpoint URI here, as we have to use the most common denominator
    // in API :(
    final String passiveString = (String) endpoint.getProperty(FtpConnector.PROPERTY_PASSIVE_MODE);
    if (passiveString == null) {
        // try the connector properties then
        if (isPassive()) {
            if (logger.isTraceEnabled()) {
                logger.trace("Entering FTP passive mode");
            }
            client.enterLocalPassiveMode();
        } else {
            if (logger.isTraceEnabled()) {
                logger.trace("Entering FTP active mode");
            }
            client.enterLocalActiveMode();
        }
    } else {
        // override with endpoint's definition
        final boolean passiveMode = Boolean.valueOf(passiveString).booleanValue();
        if (passiveMode) {
            if (logger.isTraceEnabled()) {
                logger.trace("Entering FTP passive mode (endpoint override)");
            }
            client.enterLocalPassiveMode();
        } else {
            if (logger.isTraceEnabled()) {
                logger.trace("Entering FTP active mode (endpoint override)");
            }
            client.enterLocalActiveMode();
        }
    }
}

From source file:org.nmdp.service.epitope.task.URLProcessor.java

public long getFtpLastModifiedTime(URL url) {
    FTPClient ftpClient = new FTPClient();
    try {//w w w.j a  v a  2s .com
        ftpClient.connect(url.getHost(), url.getPort() == -1 ? url.getDefaultPort() : url.getPort());
        ftpClient.login("anonymous", "anonymous");
        ftpClient.enterLocalPassiveMode();
        String filePath = url.getPath();
        String time = ftpClient.getModificationTime(filePath);
        //logger.debug("server replied: " + time);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String timePart = time.split(" ")[1];
        Date modificationTime = dateFormat.parse(timePart);
        //logger.debug("parsed time: " + modificationTime);
        return modificationTime.getTime();
    } catch (Exception e) {
        logger.error("failed to parse time for url: " + url, e);
        return 0;
    } finally {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

From source file:org.opennms.systemreport.formatters.FtpSystemReportFormatter.java

@Override
public void end() {
    m_zipFormatter.end();/*from   w ww.j  ava2s. c om*/
    IOUtils.closeQuietly(m_outputStream);

    final FTPClient ftp = new FTPClient();
    FileInputStream fis = null;
    try {
        if (m_url.getPort() == -1 || m_url.getPort() == 0 || m_url.getPort() == m_url.getDefaultPort()) {
            ftp.connect(m_url.getHost());
        } else {
            ftp.connect(m_url.getHost(), m_url.getPort());
        }
        if (m_url.getUserInfo() != null && m_url.getUserInfo().length() > 0) {
            final String[] userInfo = m_url.getUserInfo().split(":", 2);
            ftp.login(userInfo[0], userInfo[1]);
        } else {
            ftp.login("anonymous", "opennmsftp@");
        }
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            LOG.error("FTP server refused connection.");
            return;
        }

        String path = m_url.getPath();
        if (path.endsWith("/")) {
            LOG.error("Your FTP URL must specify a filename.");
            return;
        }
        File f = new File(path);
        path = f.getParent();
        if (!ftp.changeWorkingDirectory(path)) {
            LOG.info("unable to change working directory to {}", path);
            return;
        }
        LOG.info("uploading {} to {}", f.getName(), path);
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.enterLocalPassiveMode();
        fis = new FileInputStream(m_zipFile);
        if (!ftp.storeFile(f.getName(), fis)) {
            LOG.info("unable to store file");
            return;
        }
        LOG.info("finished uploading");
    } catch (final Exception e) {
        LOG.error("Unable to FTP file to {}", m_url, e);
    } finally {
        IOUtils.closeQuietly(fis);
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
                // do nothing
            }
        }
    }
}

From source file:org.openspice.vfs.ftp.FtpVVolume.java

public FTPClient getConnectedFTPClient() {
    Print.println(Print.VFS, "Trying to connect to FTP server ....");
    final FTPClient ftpc = this.getFTPClient();
    try {//  w w  w .  j  av  a 2s .co m
        if (!ftpc.isConnected()) {
            Print.println(Print.VFS, "Not connected - trying to reconnect");
            this.reconnect(ftpc);
        }
        ftpc.noop();
    } catch (final FTPConnectionClosedException e) {
        try {
            ftpc.disconnect();
            this.reconnect(ftpc);
        } catch (IOException e1) {
            throw new RuntimeException(e1);
        }
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
    //      try {
    ftpc.enterLocalPassiveMode();
    //         ftpc.setSoTimeout( 30 * 1000 );         //   Set 30 second timeout.
    //      } catch ( SocketException e ) {
    //         throw new RuntimeException( e );
    //      }
    return ftpc;
}

From source file:org.ow2.proactive.scheduler.examples.FTPConnector.java

/**
 * @see JavaExecutable#execute(TaskResult[])
 *///from w  w  w .j  a va 2 s  .  co m
@Override
public Serializable execute(TaskResult... results) throws IOException {
    List<String> filesRelativePathName;
    FTPClient ftpClient = new FTPClient();

    try {
        //connect to the server
        ftpClient.connect(ftpHostname, ftpPort);
        int reply = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftpClient.disconnect();
            throw new IOException("Exception in connecting to FTP Server");
        }
        //login to the server
        if (!ftpClient.login(ftpUsername, ftpPassword)) {
            throw new IOException("Logging refused. check the FTP_USERNAME and FTP_PASSWORD values.");
        }

        // use local passive mode to pass firewall
        ftpClient.enterLocalPassiveMode();

        getOut().println("Connected");

        switch (ftpMode) {
        //FTP mode is GET
        case GET:
            filesRelativePathName = ftpGet(ftpClient);
            break;

        //FTP mode is PUT
        case "PUT":
            filesRelativePathName = ftpPut(ftpClient);
            break;

        default:
            throw new IllegalArgumentException("FTP MODE can only be " + PUT + " or " + GET);

        }
    } finally {
        // log out and disconnect from the server
        ftpClient.logout();
        ftpClient.disconnect();
        getOut().println("Disconnected");
    }
    return (Serializable) filesRelativePathName;
}

From source file:org.ramadda.repository.monitor.FtpAction.java

/**
 * _more_//from w w  w .  j  a  va 2 s.co m
 *
 *
 * @param monitor _more_
 * @param entry _more_
 */
protected void entryMatched(EntryMonitor monitor, Entry entry) {
    FTPClient ftpClient = new FTPClient();
    try {
        Resource resource = entry.getResource();
        if (!resource.isFile()) {
            return;
        }
        if (server.length() == 0) {
            return;
        }

        String passwordToUse = monitor.getRepository().getPageHandler().processTemplate(password, false);
        ftpClient.connect(server);
        if (user.length() > 0) {
            ftpClient.login(user, password);
        }
        int reply = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftpClient.disconnect();
            monitor.handleError("FTP server refused connection:" + server, null);

            return;
        }
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpClient.enterLocalPassiveMode();
        if (directory.length() > 0) {
            ftpClient.changeWorkingDirectory(directory);
        }

        String filename = monitor.getRepository().getEntryManager().replaceMacros(entry, fileTemplate);

        InputStream is = new BufferedInputStream(
                monitor.getRepository().getStorageManager().getFileInputStream(new File(resource.getPath())));
        boolean ok = ftpClient.storeUniqueFile(filename, is);
        is.close();
        if (ok) {
            monitor.logInfo("Wrote file:" + directory + " " + filename);
        } else {
            monitor.handleError("Failed to write file:" + directory + " " + filename, null);
        }
    } catch (Exception exc) {
        monitor.handleError("Error posting to FTP:" + server, exc);
    } finally {
        try {
            ftpClient.logout();
        } catch (Exception exc) {
        }
        try {
            ftpClient.disconnect();
        } catch (Exception exc) {
        }
    }
}