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

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

Introduction

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

Prototype

public InputStream retrieveFileStream(String remote) throws IOException 

Source Link

Document

Returns an InputStream from which a named file from the server can be read.

Usage

From source file:airnowgrib2tojson.AirNowGRIB2toJSON.java

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

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

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

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

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

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

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

        // logout the user 
        ftpClient.logout();

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

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

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

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

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

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

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

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

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

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

From source file:controller.FTPServerController.java

public static String getFileFTPServer(FTPClient ftpClient, String file) throws IOException {

    BufferedReader bufferedReader = null;
    String contentXML = null;//from w w  w .j  a  v a 2  s  . c  o m

    InputStream inputStream = ftpClient.retrieveFileStream(file);

    if (inputStream != null) {
        bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        contentXML = org.apache.commons.io.IOUtils.toString(bufferedReader);
    }

    return contentXML;
}

From source file:com.kcs.core.utilities.FtpUtil.java

public static boolean checkFileExists(String filePath, FTPClient ftpClient) throws IOException {
    InputStream inputStream = ftpClient.retrieveFileStream(filePath);
    int returnCode = ftpClient.getReplyCode();
    if (inputStream == null || returnCode == 550) {
        return false;
    }/*www. j  av a  2s.  c  o m*/
    return true;
}

From source file:com.jaspersoft.jasperserver.api.engine.common.util.impl.FTPUtil.java

private static InputStream getFile(FTPClient ftpClient, String fileName) throws Exception {
    if (ftpClient == null)
        throw new JSException("Please connect to FTP server first before changing directory!");
    return ftpClient.retrieveFileStream(fileName);
}

From source file:com.kcs.core.utilities.FtpUtil.java

public static boolean checkFileExists(String hostname, int port, String username, String password,
        String fileName) throws IOException, Exception {
    FTPClient ftp = null;
    boolean result = true;
    try {/*  ww w  . j a va  2 s .c  o  m*/
        ftp = FtpUtil.openFtpConnect(hostname, port, username, password);
        if (null != ftp && ftp.isConnected()) {
            InputStream inputStream = ftp.retrieveFileStream(fileName);
            int returnCode = ftp.getReplyCode();
            if (inputStream == null || returnCode == 550) {
                System.out.println("File [ " + fileName + " ] not found in server.");
                return false;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } finally {
        FtpUtil.closeFtpServer(ftp);
    }
    return result;
}

From source file:com.feilong.tools.net.ZClientTest.java

/**
 * Gets the files./* w w w  .jav a2  s .c o  m*/
 * 
 * @param ftp
 *            the ftp
 * @param localDir
 *            the local dir
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
private static void testGetFiles(FTPClient ftp, File localDir) throws IOException {
    String[] names = ftp.listNames();
    for (String name : names) {
        File file = new File(localDir.getPath() + File.separator + name);
        if (!file.exists()) {
            file.createNewFile();
        }
        long pos = file.length();
        RandomAccessFile raf = new RandomAccessFile(file, "rw");
        raf.seek(pos);
        ftp.setRestartOffset(pos);
        InputStream is = ftp.retrieveFileStream(name);
        if (is == null) {
            log.info("no such file:" + name);
        } else {
            log.info("start getting file:" + name);
            int b;
            while ((b = is.read()) != -1) {
                raf.write(b);
            }
            is.close();
            if (ftp.completePendingCommand()) {
                log.info("done!");
            } else {
                log.info("can't get file:" + name);
            }
        }
        raf.close();
    }
}

From source file:com.kcs.core.utilities.FtpUtil.java

public static boolean getFileByStream(String hostname, int port, String username, String password,
        String remoteFileName, String localFileName) throws Exception {
    FTPClient ftp = null;
    boolean result = false;
    try {//from   w  w  w .  j  av a 2 s.  c  om
        ftp = FtpUtil.openFtpConnect(hostname, port, username, password);
        if (null != ftp && ftp.isConnected()) {
            System.out.println("File has been start downloaded..............");
            System.out.println("downloading file " + remoteFileName + " to " + localFileName + ".");
            InputStream inputStream = ftp.retrieveFileStream(remoteFileName);
            if (null == inputStream) {
                throw new Exception("File not found in server.");
            } else {
                File localFile = new File(localFileName);
                BufferedOutputStream bOut = new BufferedOutputStream(new FileOutputStream(localFile));
                int b;
                long count = 0;
                while ((b = inputStream.read()) > -1) {
                    bOut.write(b);
                    count++;
                }
                bOut.close();
                inputStream.close();
                System.out.println("download file " + remoteFileName + "(" + count + ")bytes to "
                        + localFileName + " done.");
                if (count > 0) {
                    result = true;
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new Exception("Error : File not found in server.");
    } finally {
        FtpUtil.closeFtpServer(ftp);
    }
    return result;
}

From source file:facturacion.ftp.FtpServer.java

public static InputStream getFileInputStream(String remote_file_ruta) {
    FTPClient ftpClient = new FTPClient();
    try {//from   ww  w  . j a v a 2 s  . c  o  m
        ftpClient.connect(Config.getInstance().getProperty(Config.ServerFtpToken),
                Integer.parseInt(Config.getInstance().getProperty(Config.PortFtpToken)));
        ftpClient.login(Config.getInstance().getProperty(Config.UserFtpToken),
                Config.getInstance().getProperty(Config.PassFtpToken));
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        //ftpClient.enterLocalPassiveMode();
        // crear directorio
        //OutputStream outputStream2 = new BufferedOutputStream(new FileOutputStream(file_ruta));
        //System.out.println("File #1 has been downloaded successfully. 1");
        //FileInputStream fis = new FileInputStream("C:\\Users\\aaguerra\\Desktop\\firmado2.p12");
        //InputStream is = fis;
        System.out.println("File ruta=" + "1/" + remote_file_ruta);
        InputStream is = ftpClient.retrieveFileStream(remote_file_ruta);

        if (is == null)
            System.out.println("File #1 es null");
        else
            System.out.println("File #1 no es null");

        //return ftpClient.retrieveFileStream(remote_file_ruta);
        return is;
    } catch (IOException ex) {
        System.out.println("File #1 has been downloaded successfully. 222");
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            System.out.println("File #1 has been downloaded successfully. 3");
            return null;
            //ex.printStackTrace();
        }
    }
    return null;
}

From source file:co.cask.hydrator.action.ftp.FTPCopyAction.java

private void copyZip(FTPClient ftp, String source, FileSystem fs, Path destination) throws IOException {
    InputStream is = ftp.retrieveFileStream(source);
    try (ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is))) {
        ZipEntry entry;//from w ww. j ava  2  s . c o  m
        while ((entry = zis.getNextEntry()) != null) {
            LOG.debug("Extracting {}", entry);
            Path destinationPath = fs.makeQualified(new Path(destination, entry.getName()));
            try (OutputStream os = fs.create(destinationPath)) {
                LOG.debug("Downloading {} to {}", entry.getName(), destinationPath.toString());
                ByteStreams.copy(zis, os);
            }
        }
    }
}

From source file:com.datos.vfs.provider.ftp.FTPClientWrapper.java

@Override
public InputStream retrieveFileStream(final String relPath, final long restartOffset) throws IOException {
    try {/*from w  w  w .  j  a  v a2s . c o  m*/
        final FTPClient client = getFtpClient();
        client.setRestartOffset(restartOffset);
        return client.retrieveFileStream(relPath);
    } catch (final IOException e) {
        disconnect();
        final FTPClient client = getFtpClient();
        client.setRestartOffset(restartOffset);
        return client.retrieveFileStream(relPath);
    }
}