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

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

Introduction

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

Prototype

public boolean storeFile(String remote, InputStream local) throws IOException 

Source Link

Document

Stores a file on the server using the given name and taking input from the given InputStream.

Usage

From source file:com.microsoft.azuretools.utils.WebAppUtils.java

private static void uploadWebConfigForCustomJdk(FTPClient ftp, WebApp webApp, String jdkFolderName,
        WebContainer webContainer, IProgressIndicator indicator) throws IOException {
    if (jdkFolderName == null || jdkFolderName.isEmpty()) {
        throw new IllegalArgumentException("jdkFolderName is null or empty");
    }/*from w  w w.jav a  2 s.  com*/

    if (indicator != null)
        indicator.setText("Stopping the service...");
    webApp.stop();

    if (indicator != null)
        indicator.setText("Deleting " + webConfigFilename + "...");
    ftp.deleteFile(ftpRootPath + webConfigFilename);

    if (indicator != null)
        indicator.setText("Turning the App Service into java based...");
    webApp.update().withJavaVersion(JavaVersion.JAVA_8_NEWEST).withWebContainer(webContainer).apply();

    if (indicator != null)
        indicator.setText("Generating " + webConfigFilename + "...");
    String jdkPath = "%HOME%\\site\\wwwroot\\jdk\\" + jdkFolderName;
    String webContainerPath = generateWebContainerPath(webContainer);
    byte[] webConfigData = generateWebConfigForCustomJDK(jdkPath, webContainerPath);

    if (indicator != null)
        indicator.setText("Uploading " + webConfigFilename + "...");
    ftp.storeFile(ftpRootPath + webConfigFilename, new ByteArrayInputStream(webConfigData));

    if (indicator != null)
        indicator.setText("Starting the service...");
    webApp.start();
}

From source file:FTP.Uploader.java

public void uploadFile(String filename) throws IOException {
    FTPClient ftpclient = new FTPClient();
    FileInputStream fis = null;/*from  www .  ja  v  a 2  s .c  o m*/
    boolean result;
    String ftpServerAddress = "shamalmahesh.net78.net";
    String userName = "a9959679";
    String password = "9P3IckDo";

    try {
        ftpclient.connect(ftpServerAddress);
        result = ftpclient.login(userName, password);

        if (result == true) {
            System.out.println("Logged in Successfully !");
        } else {
            System.out.println("Login Fail!");
            return;
        }
        ftpclient.enterLocalPassiveMode();
        ftpclient.setFileType(FTP.BINARY_FILE_TYPE);

        ftpclient.changeWorkingDirectory("/public_html/testing");

        //            File file = new File("D:/jpg/wq.jpg");
        File file = new File(filename);
        String testName = file.getName();
        fis = new FileInputStream(file);
        System.out.println(ftpclient.getBufferSize());
        // Upload file to the ftp server
        result = ftpclient.storeFile(testName, fis);
        if (result == true) {
            System.out.println("File is uploaded successfully");
        } else {
            System.out.println("File uploading failed");
        }
        ftpclient.logout();
    } catch (FTPConnectionClosedException e) {
        e.printStackTrace();
    } finally {
        try {
            ftpclient.disconnect();
        } catch (FTPConnectionClosedException e) {
            System.out.println(e);
        }
    }
}

From source file:facturacion.ftp.FtpServer.java

public static int sendTokenInputStream(String fileNameServer, String hostDirServer, InputStream localFile) {
    FTPClient ftpClient = new FTPClient();
    boolean success = false;
    BufferedInputStream buffIn = null;
    try {//from  w w w.j a v a 2s  .  com
        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.enterLocalPassiveMode();
        /*ftpClient.connect("127.0.0.1", 21);
          ftpClient.login("erpftp", "Tribut@2014");*/
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        int reply = ftpClient.getReplyCode();

        System.out.println("Respuesta recibida de conexin FTP:" + reply);

        if (!FTPReply.isPositiveCompletion(reply)) {
            System.out.println("Imposible conectarse al servidor");
            return -1;
        }

        buffIn = new BufferedInputStream(localFile);//Ruta del archivo para enviar
        ftpClient.enterLocalPassiveMode();
        //crear directorio
        System.out.println(hostDirServer);
        success = ftpClient.makeDirectory(hostDirServer);
        System.out.println("sucess 1133 = " + success);
        //showServerReply(ftpClient);
        success = ftpClient.makeDirectory(hostDirServer + "/token");
        /*
        System.out.println("sucess 1 = "+success);
        success = ftpClient.makeDirectory("casa111");
        System.out.println("sucess 111 = "+success);
        success = ftpClient.makeDirectory("/usr/erp/token/casa");
        System.out.println("sucess 111 = "+success);
        success = ftpClient.makeDirectory("/casa2");
        System.out.println("sucess 1 = "+success);
        */
        success = ftpClient.storeFile(hostDirServer + "/token/" + fileNameServer, buffIn);
        //success = ftpClient.storeFile("prueba", buffIn);
        System.out.println("sucess 2 = " + success);
        //return (success)? 1:0;
    } catch (IOException ex) {

    } finally {
        try {
            if (ftpClient.isConnected()) {
                buffIn.close(); //Cerrar envio de arcivos al FTP
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            return -1;
            //ex.printStackTrace();
        }
    }
    return (success) ? 1 : 0;
}

From source file:com.taurus.compratae.appservice.impl.EnvioArchivoFTPServiceImpl.java

public void conectarFTP(Archivo archivo) {
    FTPClient client = new FTPClient();
    /*String sFTP = "127.0.0.1";
    String sUser = "tae";// w ww . j  a v a 2s .co m
    String sPassword = "tae";*/
    String sFTP = buscarParametros(FTP_SERVER);
    String sUser = buscarParametros(FTP_USER);
    String sPassword = buscarParametros(FTP_PASSWORD);
    ///////////////////////////////////
    //String[] lista;
    try {
        client.connect(sFTP);
        boolean login = client.login(sUser, sPassword);
        System.out.println("1. Directorio de trabajo: " + client.printWorkingDirectory());
        client.setFileType(FTP.BINARY_FILE_TYPE);
        BufferedInputStream buffIn = null;
        buffIn = new BufferedInputStream(new FileInputStream(archivo.getNombre()));
        client.enterLocalPassiveMode();
        StringTokenizer tokens = new StringTokenizer(archivo.getNombre(), "/");//Para separar el nombre de la ruta.
        int i = 0;
        String nombre = "";
        while (tokens.hasMoreTokens()) {
            if (i == 1) {
                nombre = tokens.nextToken();
                i++;
            } else {
                i++;
            }
        }
        client.storeFile(nombre, buffIn);
        buffIn.close();
        /*lista = client.listNames();
        for (String lista1 : lista) {
        System.out.println(lista1);
        }*/
        //client.changeWorkingDirectory("\\done");
        //System.out.println("2. Working Directory: " + client.printWorkingDirectory());
        client.logout();
        client.disconnect();
        System.out.println("Termin de conectarme al FTP!!");
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
}

From source file:com.clickha.nifi.processors.util.FTPTransferV2.java

@Override
public String put(final FlowFile flowFile, final String path, final String filename, final InputStream content)
        throws IOException {
    final FTPClient client = getClient(flowFile);

    final String fullPath;
    if (path == null) {
        fullPath = filename;/*  ww w . ja  va  2 s.  c om*/
    } else {
        final String workingDir = setAndGetWorkingDirectory(path);
        fullPath = workingDir.endsWith("/") ? workingDir + filename : workingDir + "/" + filename;
    }

    String tempFilename = ctx.getProperty(TEMP_FILENAME).evaluateAttributeExpressions(flowFile).getValue();
    if (tempFilename == null) {
        final boolean dotRename = ctx.getProperty(DOT_RENAME).asBoolean();
        tempFilename = dotRename ? "." + filename : filename;
    }

    final boolean storeSuccessful = client.storeFile(tempFilename, content);
    if (!storeSuccessful) {
        throw new IOException("Failed to store file " + tempFilename + " to " + fullPath + " due to: "
                + client.getReplyString());
    }

    final String lastModifiedTime = ctx.getProperty(LAST_MODIFIED_TIME).evaluateAttributeExpressions(flowFile)
            .getValue();
    if (lastModifiedTime != null && !lastModifiedTime.trim().isEmpty()) {
        try {
            final DateFormat informat = new SimpleDateFormat(FILE_MODIFY_DATE_ATTR_FORMAT, Locale.US);
            final Date fileModifyTime = informat.parse(lastModifiedTime);
            final DateFormat outformat = new SimpleDateFormat(FTP_TIMEVAL_FORMAT, Locale.US);
            final String time = outformat.format(fileModifyTime);
            if (!client.setModificationTime(tempFilename, time)) {
                // FTP server probably doesn't support MFMT command
                logger.warn("Could not set lastModifiedTime on {} to {}",
                        new Object[] { flowFile, lastModifiedTime });
            }
        } catch (final Exception e) {
            logger.error("Failed to set lastModifiedTime on {} to {} due to {}",
                    new Object[] { flowFile, lastModifiedTime, e });
        }
    }
    final String permissions = ctx.getProperty(PERMISSIONS).evaluateAttributeExpressions(flowFile).getValue();
    if (permissions != null && !permissions.trim().isEmpty()) {
        try {
            int perms = numberPermissions(permissions);
            if (perms >= 0) {
                if (!client.sendSiteCommand("chmod " + Integer.toOctalString(perms) + " " + tempFilename)) {
                    logger.warn("Could not set permission on {} to {}", new Object[] { flowFile, permissions });
                }
            }
        } catch (final Exception e) {
            logger.error("Failed to set permission on {} to {} due to {}",
                    new Object[] { flowFile, permissions, e });
        }
    }

    if (!filename.equals(tempFilename)) {
        try {
            logger.debug("Renaming remote path from {} to {} for {}",
                    new Object[] { tempFilename, filename, flowFile });
            final boolean renameSuccessful = client.rename(tempFilename, filename);
            if (!renameSuccessful) {
                throw new IOException("Failed to rename temporary file " + tempFilename + " to " + fullPath
                        + " due to: " + client.getReplyString());
            }
        } catch (final IOException e) {
            try {
                client.deleteFile(tempFilename);
                throw e;
            } catch (final IOException e1) {
                throw new IOException("Failed to rename temporary file " + tempFilename + " to " + fullPath
                        + " and failed to delete it when attempting to clean up", e1);
            }
        }
    }

    return fullPath;
}

From source file:lucee.runtime.tag.Ftp.java

/**
 * copy a local file to server//from w  ww  .j  av a 2  s.c o m
 * @return FTPClient
 * @throws IOException
 * @throws PageException
 */
private FTPClient actionPutFile() throws IOException, PageException {
    required("remotefile", remotefile);
    required("localfile", localfile);

    FTPClient client = getClient();
    Resource local = ResourceUtil.toResourceExisting(pageContext, localfile);//new File(localfile);
    //   if(failifexists && local.exists()) throw new ApplicationException("File ["+local+"] already exist, if you want to overwrite, set attribute failIfExists to false");
    InputStream is = null;

    try {
        is = IOUtil.toBufferedInputStream(local.getInputStream());
        client.setFileType(getType(local));
        client.storeFile(remotefile, is);
    } finally {
        IOUtil.closeEL(is);
    }
    writeCfftp(client);

    return client;
}

From source file:com.maxl.java.amikodesk.Emailer.java

private void uploadToFTPServer(Author author, String name, String path) {
    FTPClient ftp_client = new FTPClient();
    try {//  w ww. ja  va 2s . c  o  m
        ftp_client.connect(author.getS(), 21);
        ftp_client.login(author.getL(), author.getP());
        ftp_client.enterLocalPassiveMode();
        ftp_client.changeWorkingDirectory(author.getO());
        ftp_client.setFileType(FTP.BINARY_FILE_TYPE);

        int reply = ftp_client.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp_client.disconnect();
            System.err.println("FTP server refused connection.");
            return;
        }

        File local_file = new File(path);
        String remote_file = name + ".csv";
        InputStream is = new FileInputStream(local_file);
        System.out.print("Uploading file " + name + " to server " + author.getS() + "... ");

        boolean done = ftp_client.storeFile(remote_file, is);
        if (done)
            System.out.println("file uploaded successfully.");
        else
            System.out.println("error.");
        is.close();
    } catch (IOException ex) {
        System.out.println("Error: " + ex.getMessage());
        ex.printStackTrace();
    } finally {
        try {
            if (ftp_client.isConnected()) {
                ftp_client.logout();
                ftp_client.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:fr.acxio.tools.agia.ftp.FTPUploadTasklet.java

@Override
public RepeatStatus execute(StepContribution sContribution, ChunkContext sChunkContext) throws Exception {
    FTPClient aClient = ftpClientFactory.getFtpClient();

    RegexFilenameFilter aFilter = new RegexFilenameFilter();
    aFilter.setRegex(regexFilename);//from w w  w  .j a  va 2s.co m

    try {
        File aLocalDir = new File(localBaseDir);

        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Listing : {} ({}) for upload to [{}]", localBaseDir, regexFilename,
                    aClient.getRemoteAddress().toString());
        }

        File[] aLocalFiles = aLocalDir.listFiles(aFilter);

        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("  {} file(s) found", aLocalFiles.length);
        }

        for (File aLocalFile : aLocalFiles) {

            if (sContribution != null) {
                sContribution.incrementReadCount();
            }

            URI aRemoteFile = new URI(remoteBaseDir).resolve(aLocalFile.getName());
            InputStream aInputStream;
            aInputStream = new FileInputStream(aLocalFile);
            try {

                if (LOGGER.isInfoEnabled()) {
                    LOGGER.info(" Uploading : {} => {}", aLocalFile.getAbsolutePath(),
                            aRemoteFile.toASCIIString());
                }

                aClient.storeFile(aRemoteFile.toASCIIString(), aInputStream);

                if (sContribution != null) {
                    sContribution.incrementWriteCount(1);
                }
            } finally {
                aInputStream.close();
            }
        }
    } finally {
        aClient.logout();
        aClient.disconnect();
    }

    return RepeatStatus.FINISHED;
}

From source file:com.hackengine_er.muslumyusuf.DBOperations.java

private boolean uploadToFTP(String username, String fileName, InputStream inputStream) {
    FTPClient client = new FTPClient();
    try {//from  www .  j a  v a 2  s.c  om
        client.connect(Configuration.FTPClient());
        if (client.login(Configuration.FTPUsername(), Configuration.getPASSWORD())) {
            client.setDefaultTimeout(10000);
            client.setFileType(FTPClient.BINARY_FILE_TYPE);
            if (client.storeFile(Tags.SITE + username + "-" + fileName, inputStream)) {
                return true;
            }
        }
    } catch (IOException e) {
        Logger.getLogger(DBOperations.class.getName()).log(Level.SEVERE, null, e);
    } finally {
        if (client.isConnected()) {
            try {
                client.logout();
                client.disconnect();
            } catch (IOException ex) {
                Logger.getLogger(DBOperations.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    return false;
}

From source file:com.muslumyusuf.DBOperations.java

private boolean uploadToFTP(String username, String fileName, InputStream inputStream) {
    FTPClient client = new FTPClient();
    try {/*  w  w w  . j  av  a2s .c o m*/
        client.connect(Initialize.FTPClient());
        if (client.login(Initialize.FTPUsername(), Initialize.getPASSWORD())) {
            client.setDefaultTimeout(10000);
            client.setFileType(FTPClient.BINARY_FILE_TYPE);
            if (client.storeFile(Tags.SITE + username + "/" + fileName, inputStream)) {
                return true;
            }
        }
    } catch (IOException e) {
        Logger.getLogger(DBOperations.class.getName()).log(Level.SEVERE, null, e);
    } finally {
        if (client.isConnected()) {
            try {
                client.logout();
                client.disconnect();
            } catch (IOException ex) {
                Logger.getLogger(DBOperations.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    return false;
}