Example usage for org.apache.commons.net.ftp FTPClientConfig SYST_NT

List of usage examples for org.apache.commons.net.ftp FTPClientConfig SYST_NT

Introduction

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

Prototype

String SYST_NT

To view the source code for org.apache.commons.net.ftp FTPClientConfig SYST_NT.

Click Source Link

Document

Identifier by which a WindowsNT-based ftp server is known throughout the commons-net ftp system.

Usage

From source file:Main.java

private static FTPClientConfig getFTPClientConfig() {
    FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
    conf.setServerLanguageCode("zh");

    return conf;/*w  ww  .  j a v  a  2s.co  m*/
}

From source file:com.usefullc.platform.common.utils.FtpUtils.java

/**
 * //from   w ww  .  j  av  a 2  s  . com
 * 
 * @param oppositePath 
 * @param downFileName  ??
 * @return
 */
public static InputStream download(String oppositePath, String downFileName) {
    InputStream is = null;
    try {
        // // 
        ftpClient.connect(host, port);

        // 
        ftpClient.login(user, password);

        // ??
        int reply = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            log.error("FTP server refused connection,host=" + host + ",user=" + user + "," + password);
            return is;
        }

        FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
        conf.setServerLanguageCode("zh");
        String sep = "/";
        String workRemoteDir = StrUtils.joinEmpty(remoteDir, sep, oppositePath);
        FTPFile[] remoteFiles = ftpClient.listFiles(workRemoteDir);
        if (remoteFiles != null) {
            for (int i = 0; i < remoteFiles.length; i++) {
                String name = remoteFiles[i].getName();
                if (!name.equals(downFileName)) {
                    continue;
                }
                //                    String sep = File.separator;
                String fileName = StrUtils.joinEmpty(remoteDir, sep, oppositePath, sep, name);
                is = ftpClient.retrieveFileStream(fileName);
            }
        }
        ftpClient.logout();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            ftpClient.disconnect();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
    return is;
}

From source file:ch.cyberduck.core.ftp.FTPParserFactory.java

public CompositeFileEntryParser createFileEntryParser(final String system, final TimeZone timezone)
        throws ParserInitializationException {
    if (null != system) {
        String ukey = system.toUpperCase(Locale.ROOT);
        if (ukey.contains(FTPClientConfig.SYST_UNIX)) {
            return this.createUnixFTPEntryParser(timezone);
        } else if (ukey.contains(FTPClientConfig.SYST_VMS)) {
            throw new ParserInitializationException(
                    String.format("\"%s\" is not currently a supported system.", system));
        } else if (ukey.contains(FTPClientConfig.SYST_NETWARE)) {
            return this.createNetwareFTPEntryParser(timezone);
        } else if (ukey.contains(FTPClientConfig.SYST_NT)) {
            return this.createNTFTPEntryParser(timezone);
        } else if (ukey.contains(FTPClientConfig.SYST_OS2)) {
            return this.createOS2FTPEntryParser(timezone);
        } else if (ukey.contains(FTPClientConfig.SYST_OS400)) {
            return this.createOS400FTPEntryParser(timezone);
        } else if (ukey.contains(FTPClientConfig.SYST_MVS)) {
            return this.createUnixFTPEntryParser(timezone);
        }//from  w ww. j a v a2s .  co m
    }
    // Defaulting to UNIX parser
    return this.createUnixFTPEntryParser(timezone);
}

From source file:ch.cyberduck.core.ftp.FTPListService.java

public FTPListService(final FTPSession session, final HostPasswordStore keychain, final LoginCallback prompt,
        final String system, final TimeZone zone) {
    this.session = session;
    // Directory listing parser depending on response for SYST command
    final CompositeFileEntryParser parser = new FTPParserSelector().getParser(system, zone);
    this.implementations.put(Command.list,
            new FTPDefaultListService(session, keychain, prompt, parser, Command.list));
    if (PreferencesFactory.get().getBoolean("ftp.command.stat")) {
        if (StringUtils.isNotBlank(system)) {
            if (!system.toUpperCase(Locale.ROOT).contains(FTPClientConfig.SYST_NT)) {
                // Workaround for #5572.
                this.implementations.put(Command.stat, new FTPStatListService(session, parser));
            }//from   w w w  .  j  a v  a2s.c  om
        } else {
            this.implementations.put(Command.stat, new FTPStatListService(session, parser));
        }
    }
    if (PreferencesFactory.get().getBoolean("ftp.command.mlsd")) {
        this.implementations.put(Command.mlsd, new FTPMlsdListService(session, keychain, prompt));
    }
    if (PreferencesFactory.get().getBoolean("ftp.command.lista")) {
        this.implementations.put(Command.lista,
                new FTPDefaultListService(session, keychain, prompt, parser, Command.lista));
    }
}

From source file:com.usefullc.platform.common.utils.FtpUtils.java

/**
 * /*from  www .j ava2 s .  c  om*/
 * 
 * @param oppositePath 
 * @param uploadFileName ??
 * @param is ?
 */
public static void upload(String oppositePath, String uploadFileName, InputStream is) {
    try {
        // 
        ftpClient.connect(host, port);

        // 
        ftpClient.login(user, password);

        // ??
        int reply = ftpClient.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            log.error("FTP server refused connection,host=" + host + ",user=" + user + "," + password);
            return;
        }

        String sep = "/";
        String workRemoteDir = StrUtils.joinEmpty(remoteDir, sep, oppositePath);
        // 
        try {
            int n = workRemoteDir.indexOf("/", 1);
            String subRemoteDir = null;
            while (n != -1) {
                subRemoteDir = workRemoteDir.substring(0, n);
                if (!ftpClient.changeWorkingDirectory(subRemoteDir)) {
                    ftpClient.makeDirectory(subRemoteDir);
                }
                n = workRemoteDir.indexOf("/", n + 1);
            }
            ftpClient.makeDirectory(workRemoteDir);
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);

        conf.setServerLanguageCode("zh");

        // 
        ftpClient.changeWorkingDirectory(workRemoteDir);

        ftpClient.setBufferSize(1024);

        ftpClient.setControlEncoding("GBK");

        // 
        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);

        // 
        boolean state = ftpClient.storeFile(uploadFileName, is);

        log.debug("storeFile state = " + state);

        ftpClient.logout();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(is);
        try {
            ftpClient.disconnect();
        } catch (IOException e) {
            e.printStackTrace();

        }
    }

}

From source file:it.greenvulcano.util.remotefs.ftp.FTPManager.java

/**
 * @see it.greenvulcano.util.remotefs.RemoteManager#init(Node)
 *//*from  ww w  . j  a v  a  2s . c o m*/
@Override
public void init(Node node) throws RemoteManagerException {
    super.init(node);
    try {
        hostType = TargetType.valueOf(XMLConfig.get(node, "@hostType"));
        logger.debug("host-type          : " + hostType);

        FTPClientConfig conf = null;

        switch (hostType) {
        case MVS: {
            conf = new FTPClientConfig(FTPClientConfig.SYST_MVS);
            break;
        }
        case NT: {
            conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
            break;
        }
        case OS2: {
            conf = new FTPClientConfig(FTPClientConfig.SYST_OS2);
            break;
        }
        case OS400: {
            conf = new FTPClientConfig(FTPClientConfig.SYST_OS400);
            break;
        }
        case UNIX: {
            conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
            break;
        }
        case VMS: {
            conf = new FTPClientConfig(FTPClientConfig.SYST_VMS);
            break;
        }
        }

        ftpClient.configure(conf);
        ftpClient.setDefaultTimeout(connectTimeout);
        ftpClient.setDataTimeout(dataTimeout);
    } catch (Exception exc) {
        throw new RemoteManagerException("Initialization error", exc);
    }
}

From source file:net.sf.webphotos.sync.FTP.SyncObject.java

/**
 * Conecta ao servidor FTP. Retorna uma confirmao da conexo atravs de um
 * boolean. TODO: remontar a funo para que use somente dados externos a
 * classe//  w w w. j ava 2  s  . c o m
 *
 * @return Valor lgico que confirma a conexo.
 */
@Override
public boolean connect() {
    boolean conectado = false;

    ftpHost = Util.getProperty("servidorFTP");
    ftpPort = Util.getConfig().getInt("FTPport");

    String ftpProxyHost = Util.getProperty("FTPproxyHost");
    int ftpProxyPort;
    try {
        ftpProxyPort = Util.getConfig().getInt("FTPproxyPort");
    } catch (Exception e) {
        ftpProxyPort = 0;
    }

    Util.log("Iniciando conexo com " + ftpHost);
    try {
        //TODO: Preparar o suporte a mltiplas lnguas
        FTPClientConfig auxConfig = new FTPClientConfig(FTPClientConfig.SYST_NT);
        configure(auxConfig);
        Util.out.println("Timeout (antes): " + getDefaultTimeout());
        setDefaultTimeout(25000);
        Util.out.println("Timeout (depois): " + getDefaultTimeout());

        //TODO: Testar o acesso via Proxy
        //      usando System.getProperties().put()
        //      http://java.sun.com/j2se/1.5.0/docs/guide/net/properties.html
        if (ftpProxyHost == null && ftpProxyPort != 0) {
            System.getProperties().put("ftp.proxyHost", ftpProxyHost);
            System.getProperties().put("ftp.proxyPort", ftpProxyPort);
        }

        super.connect(ftpHost, ftpPort);
        reply = getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            disconnect("[FtpClient.connect]/ERRO: no foi possivel conectar");
            return false;
        }
        Util.log("ok " + ftpHost + " encontrado.. autenticando..");

        SyncEvent ev = null;
        if (syncListener != null) {
            ev = new SyncEvent(this);
        }
        reply = FTPReply.NOT_LOGGED_IN;
        do {

            if (syncListener != null && ev != null) {
                syncListener.logonStarted(ev);
            }
            Util.log("servidor: " + ftpHost + " em " + ftpRoot + "\nsolicitando conexo...");

            login(usuario, new String(senha));
            Util.log("usurio: " + usuario + " senha: ***");
            reply = getReplyCode();
            retry--;

        } while (reply != FTPReply.USER_LOGGED_IN && retry >= 0);

        if (reply != FTPReply.USER_LOGGED_IN) {
            disconnect("[FtpClient.connect]/ERRO: login/senha incorreto.");
            return conectado;
        } else {
            // conexo bem sucedida... armazenamos o nome/login
            BancoImagem.getBancoImagem().setUserFTP(getUsuario());
            BancoImagem.getBancoImagem().setPasswordFTP(getSenha());
        }

        Util.log("ok conexo aceita..");
        // autenticao ok..

        setFileType(FTPClient.BINARY_FILE_TYPE);
        //ftp.enterRemotePassiveMode();
        // TODO: Achar uma alternativa para realizar o logging do FTP
        //ftp.setLogFile("ftp.log");

        // tenta ir ao diretrio FTPRoot... caso no consiga, tenta criar
        changeWorkingDirectory(ftpRoot);
        if (getReplyCode() != FTPReply.CODE_250) {
            Util.log(ftpRoot + " no existe..criando");
            if (makeDirectory(ftpRoot)) {
                Util.log("[FtpClient.connect]/ERRO: no foi possvel criar diretrio " + ftpRoot + " Retorno: "
                        + reply);
                disconnect("no foi possvel criar diretrio");
                return conectado;
            }
            changeWorkingDirectory(ftpRoot);
            reply = getReplyCode();
            if (reply != FTPReply.CODE_250) {
                disconnect("[FtpClient.connect]/ERRO: no foi possvel entrar no diretrio " + ftpRoot
                        + " que foi recm criado.");
                return conectado;
            }
        }
        conectado = true;
        getSyncListener().connected(new SyncEvent(this));
    } catch (Exception e) {
        conectado = false;
        log.error(e);
        disconnect("[FtpClient.connect]/ERRO: no foi possivel manter esta conexo");
    }

    return conectado;

}

From source file:ch.cyberduck.core.ftp.FTPSession.java

@Override
public void login(final HostPasswordStore keychain, final LoginCallback prompt, final CancelCallback cancel)
        throws BackgroundException {
    try {/*from   www. j a  v  a2  s. c om*/
        if (client.login(host.getCredentials().getUsername(), host.getCredentials().getPassword())) {
            if (host.getProtocol().isSecure()) {
                client.execPBSZ(0);
                // Negotiate data connection security
                client.execPROT(preferences.getProperty("ftp.tls.datachannel"));
            }
            if ("UTF-8".equals(host.getEncoding())) {
                if (client.hasFeature("UTF8")) {
                    if (!FTPReply.isPositiveCompletion(client.sendCommand("OPTS UTF8 ON"))) {
                        log.warn(
                                String.format("Failed to negotiate UTF-8 charset %s", client.getReplyString()));
                    }
                }
            }
            final TimeZone zone = host.getTimezone();
            if (log.isInfoEnabled()) {
                log.info(String.format("Reset parser to timezone %s", zone));
            }
            String system = null; //Unknown
            try {
                system = client.getSystemType();
                if (system.toUpperCase(Locale.ROOT).contains(FTPClientConfig.SYST_NT)) {
                    casesensitivity = Case.insensitive;
                }
            } catch (IOException e) {
                log.warn(String.format("SYST command failed %s", e.getMessage()));
            }
            listService = new FTPListService(this, keychain, prompt, system, zone);
            if (client.hasFeature(FTPCmd.MFMT.getCommand())) {
                timestamp = new FTPMFMTTimestampFeature(this);
            } else {
                timestamp = new FTPUTIMETimestampFeature(this);
            }
            permission = new FTPUnixPermissionFeature(this);
            if (client.hasFeature("SITE", "SYMLINK")) {
                symlink = new FTPSymlinkFeature(this);
            }
        } else {
            throw new FTPExceptionMappingService()
                    .map(new FTPException(this.getClient().getReplyCode(), this.getClient().getReplyString()));
        }
    } catch (IOException e) {
        throw new FTPExceptionMappingService().map(e);
    }
}

From source file:org.openo.nfvo.emsdriver.commons.ftp.ExtendsDefaultFTPFileEntryParserFactory.java

/**
* This default implementation of the FTPFileEntryParserFactory
* interface works according to the following logic:
* First it attempts to interpret the supplied key as a fully
* qualified classname of a class implementing the
* FTPFileEntryParser interface.  If that succeeds, a parser
* object of this class is instantiated and is returned; 
* otherwise it attempts to interpret the key as an identirier
* commonly used by the FTP SYST command to identify systems.
* <p/>//from   w  w w .  j a v a 2  s .c o m
* If <code>key</code> is not recognized as a fully qualified
* classname known to the system, this method will then attempt
* to see whether it <b>contains</b> a string identifying one of
* the known parsers.  This comparison is <b>case-insensitive</b>.
* The intent here is where possible, to select as keys strings
* which are returned by the SYST command on the systems which
* the corresponding parser successfully parses.  This enables
* this factory to be used in the auto-detection system.
* <p/>
*
* @param key    should be a fully qualified classname corresponding to
*               a class implementing the FTPFileEntryParser interface<br/>
*               OR<br/>
*               a string containing (case-insensitively) one of the
*               following keywords:
*               <ul>
*               <li>{@link FTPClientConfig#SYST_UNIX UNIX}</li>
*               <li>{@link FTPClientConfig#SYST_NT WINDOWS}</li>
*               <li>{@link FTPClientConfig#SYST_OS2 OS/2}</li>
*               <li>{@link FTPClientConfig#SYST_OS400 OS/400}</li>
*               <li>{@link FTPClientConfig#SYST_VMS VMS}</li>
*               <li>{@link FTPClientConfig#SYST_MVS MVS}</li>
*               </ul>
* @return the FTPFileEntryParser corresponding to the supplied key.
* @throws ParserInitializationException thrown if for any reason the factory cannot resolve
*                   the supplied key into an FTPFileEntryParser.
* @see FTPFileEntryParser
*/
public FTPFileEntryParser createFileEntryParser(String key) {
    @SuppressWarnings("rawtypes")
    Class parserClass = null;
    FTPFileEntryParser parser = null;
    try {
        parserClass = Class.forName(key);
        parser = (FTPFileEntryParser) parserClass.newInstance();
    } catch (ClassNotFoundException e) {
        String ukey = null;
        if (null != key) {
            ukey = key.toUpperCase();
        }
        if (ukey.indexOf(FTPClientConfig.SYST_UNIX) >= 0) {
            parser = createUnixFTPEntryParser();
        } else if (ukey.indexOf(FTPClientConfig.SYST_VMS) >= 0) {
            parser = createVMSVersioningFTPEntryParser();
        } else if (ukey.indexOf(FTPClientConfig.SYST_NT) >= 0 || ukey.indexOf("DOPRA") >= 0
                || ukey.indexOf("MSDOS") >= 0) {
            parser = createNTFTPEntryParser();
        } else if (ukey.indexOf(FTPClientConfig.SYST_OS2) >= 0) {
            parser = createOS2FTPEntryParser();
        } else if (ukey.indexOf(FTPClientConfig.SYST_OS400) >= 0) {
            parser = createOS400FTPEntryParser();
        } else if (ukey.indexOf(FTPClientConfig.SYST_MVS) >= 0) {
            parser = createMVSEntryParser();
        } else {
            throw new ParserInitializationException("Unknown parser type: " + key);
        }
    } catch (ClassCastException e) {
        throw new ParserInitializationException(parserClass.getName() + " does not implement the interface "
                + "org.apache.commons.net.ftp.FTPFileEntryParser.", e);
    } catch (Throwable e) {
        throw new ParserInitializationException("Error initializing parser", e);
    }

    if (parser instanceof Configurable) {
        ((Configurable) parser).configure(this.config);
    }
    return parser;
}

From source file:org.openo.nfvo.emsdriver.commons.ftp.ExtendsDefaultFTPFileEntryParserFactory.java

public FTPFileEntryParser createNTFTPEntryParser() {
    if (config != null && FTPClientConfig.SYST_NT.equals(config.getServerSystemKey())) {
        return new NTFTPEntryParser();
    } else {//from ww  w . j  av a 2  s .c  o m
        return new CompositeFileEntryParser(
                new FTPFileEntryParser[] { new NTFTPEntryParser(), new UnixFTPEntryParser() });
    }
}