List of usage examples for org.apache.commons.net.ftp FTPReply isPositiveCompletion
public static boolean isPositiveCompletion(int reply)
From source file:com.bbytes.jfilesync.sync.ftp.FTPClientFactory.java
/** * Get {@link FTPClient} with initialized connects to server given in properties file * @return/*from ww w . j av a 2 s . c o m*/ */ public FTPClient getClientInstance() { ExecutorService ftpclientConnThreadPool = Executors.newSingleThreadExecutor(); Future<FTPClient> future = ftpclientConnThreadPool.submit(new Callable<FTPClient>() { FTPClient ftpClient = new FTPClient(); boolean connected; public FTPClient call() throws Exception { try { while (!connected) { try { ftpClient.connect(host, port); if (!ftpClient.login(username, password)) { ftpClient.logout(); } connected = true; return ftpClient; } catch (Exception e) { connected = false; } } int reply = ftpClient.getReplyCode(); // FTPReply stores a set of constants for FTP reply codes. if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); } catch (Exception e) { log.error(e.getMessage(), e); } return ftpClient; } }); FTPClient ftpClient = new FTPClient(); try { // wait for 100 secs for acquiring conn else terminate ftpClient = future.get(100, TimeUnit.SECONDS); } catch (TimeoutException e) { log.info("FTP client Conn wait thread terminated!"); } catch (InterruptedException e) { log.error(e.getMessage(), e); } catch (ExecutionException e) { log.error(e.getMessage(), e); } ftpclientConnThreadPool.shutdownNow(); return ftpClient; }
From source file:eu.prestoprime.p4gui.ingest.UploadMasterFileServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { User user = Tools.getSessionAttribute(request.getSession(), P4GUI.USER_BEAN_NAME, User.class); RoleManager.checkRequestedRole(USER_ROLE.producer, user.getCurrentP4Service().getRole(), response); // prepare dynamic variables Part masterQualityPart = request.getPart("masterFile"); String targetName = new SimpleDateFormat("yyyyMMdd-HHmm").format(new Date()) + ".mxf"; // prepare static variables String host = "p4.eurixgroup.com"; int port = 21; String username = "pprime"; String password = "pprime09"; FTPClient client = new FTPClient(); try {//w w w. j a va2s .c o m client.connect(host, port); if (FTPReply.isPositiveCompletion(client.getReplyCode())) { if (client.login(username, password)) { client.setFileType(FTP.BINARY_FILE_TYPE); // TODO add behavior if file name is already present in // remote ftp folder // now OVERWRITES if (client.storeFile(targetName, masterQualityPart.getInputStream())) { logger.info("Stored file on remote FTP server " + host + ":" + port); request.setAttribute("masterfileName", targetName); } else { logger.error("Unable to store file on remote FTP server"); } } else { logger.error("Unable to login on remote FTP server"); } } else { logger.error("Unable to connect to remote FTP server"); } } catch (IOException e) { e.printStackTrace(); logger.fatal("General exception with FTPClient"); } Tools.servletInclude(this, request, response, "/body/ingest/masterfile/listfiles.jsp"); }
From source file:com.microsoft.azuretools.utils.WebAppUtils.java
public static FTPClient getFtpConnection(PublishingProfile pp) throws IOException { FTPClient ftp = new FTPClient(); System.out.println("\t\t" + pp.ftpUrl()); System.out.println("\t\t" + pp.ftpUsername()); System.out.println("\t\t" + pp.ftpPassword()); URI uri = URI.create("ftp://" + pp.ftpUrl()); ftp.connect(uri.getHost(), 21);/*from w ww . j a va 2 s . com*/ final int replyCode = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { ftp.disconnect(); throw new ConnectException("Unable to connect to FTP server"); } if (!ftp.login(pp.ftpUsername(), pp.ftpPassword())) { throw new ConnectException("Unable to login to FTP server"); } ftp.setControlKeepAliveTimeout(Constants.connection_read_timeout_ms); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode();//Switch to passive mode return ftp; }
From source file:com.clican.pluto.cms.core.service.impl.SiteServiceImpl.java
public FTPClient getFTPClient(ISite site) throws IOException { String url = site.getUrl();// w ww. ja v a2s . com if (url == null) { return null; } if (url.startsWith("ftp://")) { int port = 21; String hostname = null; try { url = url.substring(6); if (url.indexOf(":") != -1) { hostname = url.substring(0, url.indexOf(":")); if (url.endsWith("/")) { port = Integer.parseInt(url.substring(url.indexOf(":") + 1, url.length() - 1)); } else { port = Integer.parseInt(url.substring(url.indexOf(":") + 1)); } } else { if (url.endsWith("/")) { hostname = url.substring(0, url.length() - 1); } else { hostname = url; } } } catch (Exception e) { throw new UnknownHostException(url); } FTPClient client = new FTPClient(); client.connect(hostname, port); if (log.isDebugEnabled()) { log.debug("Connected to " + url + "."); log.debug(client.getReplyString()); } int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { client.disconnect(); log.warn("FTP server " + url + " refused connection."); return null; } if (StringUtils.isNotEmpty(site.getUsername())) { boolean login = client.login(site.getUsername(), site.getPassword()); if (!login) { client.disconnect(); return null; } } return client; } return null; }
From source file:com.hibo.bas.fileplugin.file.FtpPlugin.java
@Override public void upload(String path, File file, String contentType) { Map<String, String> ftpInfo = getFtpInfo(contentType); if (!"".equals(ftpInfo.get("host")) && !"".equals(ftpInfo.get("username")) && !"".equals(ftpInfo.get("password"))) { FTPClient ftpClient = new FTPClient(); InputStream inputStream = null; try {/* www. jav a 2s . c om*/ inputStream = new FileInputStream(file); ftpClient.connect(ftpInfo.get("host"), 21); ftpClient.login(ftpInfo.get("username"), ftpInfo.get("password")); ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); path = ftpInfo.get("path") + path; if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { String directory = StringUtils.substringBeforeLast(path, "/"); String filename = StringUtils.substringAfterLast(path, "/"); if (!ftpClient.changeWorkingDirectory(directory)) { String[] paths = StringUtils.split(directory, "/"); String p = "/"; ftpClient.changeWorkingDirectory(p); for (String s : paths) { p += s + "/"; if (!ftpClient.changeWorkingDirectory(p)) { ftpClient.makeDirectory(s); ftpClient.changeWorkingDirectory(p); } } } ftpClient.storeFile(filename, inputStream); ftpClient.logout(); } } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(inputStream); if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException e) { } } } } }
From source file:au.org.intersect.dms.wn.transports.impl.FtpConnection.java
public FtpConnection(String server, String username, String password) { LOGGER.debug("ftp connect to server:{} using username:{} and password:{}", new String[] { server, username, password }); boolean ok = false; params = new ConnectionParams("ftp", server, username, null); try {//w ww . j a v a2 s. c om client = new FTPClient(); client.connect(server); client.enterLocalPassiveMode(); if (!FTPReply.isPositiveCompletion(client.getReplyCode())) { throw new TransportError(); } if (!client.login(username, password)) { throw new NotAuthorizedError(); } client.setFileType(FTP.BINARY_FILE_TYPE); ok = true; } catch (SocketException e) { throw new TransportError(e); } catch (IOException e) { throw new TransportError(e); } finally { if (!ok && client != null) { try { client.disconnect(); } catch (IOException e) { // swallows exception } } } }
From source file:com.clustercontrol.port.protocol.ReachAddressFTP.java
/** * FTP????????//from w w w . jav a2 s . c o m * * @param addressText * @return FTP */ @Override protected boolean isRunning(String addressText) { m_message = ""; m_messageOrg = ""; m_response = -1; boolean isReachable = false; try { long start = 0; // long end = 0; // boolean retry = true; // ????(true:??false:???) StringBuffer bufferOrg = new StringBuffer(); // String result = ""; InetAddress address = InetAddress.getByName(addressText); bufferOrg.append("Monitoring the FTP Service of " + address.getHostName() + "[" + address.getHostAddress() + "]:" + m_portNo + ".\n\n"); FTPClient client = new FTPClient(); for (int i = 0; i < m_sentCount && retry; i++) { try { bufferOrg.append(HinemosTime.getDateString() + " Tried to Connect: "); client.setDefaultTimeout(m_timeout); start = HinemosTime.currentTimeMillis(); client.connect(address, m_portNo); end = HinemosTime.currentTimeMillis(); m_response = end - start; result = client.getReplyString(); int reply = client.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { if (m_response > 0) { if (m_response < m_timeout) { result = result + ("\n" + "Response Time = " + m_response + "ms"); } else { m_response = m_timeout; result = result + ("\n" + "Response Time = " + m_response + "ms"); } } else { result = result + ("\n" + "Response Time < 1ms"); } retry = false; isReachable = true; } else { retry = false; isReachable = false; } } catch (SocketException e) { result = (e.getMessage() + "[SocketException]"); retry = true; isReachable = false; } catch (IOException e) { result = (e.getMessage() + "[IOException]"); retry = true; isReachable = false; } finally { bufferOrg.append(result + "\n"); if (client.isConnected()) { try { client.disconnect(); } catch (IOException e) { m_log.warn("isRunning(): " + "socket disconnect failed: " + e.getMessage(), e); } } } if (i < m_sentCount - 1 && retry) { try { Thread.sleep(m_sentInterval); } catch (InterruptedException e) { break; } } } m_message = result + "(FTP/" + m_portNo + ")"; m_messageOrg = bufferOrg.toString(); return isReachable; } catch (UnknownHostException e) { m_log.debug("isRunning(): " + MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + e.getMessage()); m_message = MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + " (" + e.getMessage() + ")"; return false; } }
From source file:com.seajas.search.contender.service.modifier.AbstractModifierService.java
/** * Retrieve the FTP client belonging to the given URI. * // ww w . jav a 2 s .c om * @param uri * @return FTPClient */ protected FTPClient retrieveFtpClient(final URI uri) { // Create the FTP client FTPClient ftpClient = uri.getScheme().equalsIgnoreCase("ftps") ? new FTPSClient() : new FTPClient(); try { ftpClient.connect(uri.getHost(), uri.getPort() != -1 ? uri.getPort() : 21); if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { ftpClient.disconnect(); logger.error("Could not connect to the given FTP server " + uri.getHost() + (uri.getPort() != -1 ? ":" + uri.getPort() : "") + " - " + ftpClient.getReplyString()); return null; } if (StringUtils.hasText(uri.getUserInfo())) { if (uri.getUserInfo().contains(":")) ftpClient.login(uri.getUserInfo().substring(0, uri.getUserInfo().indexOf(":")), uri.getUserInfo().substring(uri.getUserInfo().indexOf(":") + 1)); else ftpClient.login(uri.getUserInfo(), ""); } if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { ftpClient.disconnect(); logger.error("Could not login to the given FTP server " + uri.getHost() + (uri.getPort() != -1 ? ":" + uri.getPort() : "") + " - " + ftpClient.getReplyString()); return null; } // Switch to PASV and BINARY mode ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); return ftpClient; } catch (IOException e) { logger.error("Could not close input stream during archive processing", e); } return null; }
From source file:net.sourceforge.dvb.projectx.xinput.ftp.FtpServer.java
public boolean open() { boolean isSuccessful = false; if (isOpen) { throw new IllegalStateException("Is already open, must be closed before!"); }//from w ww . j ava 2 s .com try { int reply; ftpClient.connect(ftpVO.getServer(), ftpVO.getPortasInteger()); reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); throw new IOException("Can't connect!"); } if (!ftpClient.login(ftpVO.getUser(), ftpVO.getPassword())) { ftpClient.logout(); throw new IOException("Can't login!"); } if (!ftpClient.changeWorkingDirectory(ftpVO.getDirectory())) { ftpClient.logout(); throw new IOException("Can't change directory!"); } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); isSuccessful = true; } catch (Exception e) { if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException f) { // do nothing } } isSuccessful = false; } isOpen = isSuccessful; return isSuccessful; }
From source file:gr.interamerican.bo2.utils.ftp.FtpSession.java
/** * Connects.// www . j a v a 2s . c o m * * @throws FtpException */ public void connect() throws FtpException { try { ftp = newFtpClient(); ftp.connect(host, port); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { disconnectOnFailure(); throw new FtpException(COULD_NOT_CONNECT); } boolean loggedIn = ftp.login(userid, password); if (!loggedIn) { disconnectOnFailure(); throw new FtpException(LOGIN_FAILED); } } catch (SocketException se) { disconnectOnFailure(); throw new FtpException(COULD_NOT_CONNECT, se); } catch (IOException ioe) { disconnectOnFailure(); throw new FtpException(ioe); } }