List of usage examples for org.apache.commons.net.ftp FTPClient getReplyString
public String getReplyString()
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;// w w w. j a v a 2 s . com } 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:ProtocolRunner.java
private static void handleFTP( FTPClient client, ProtocolRunner runner, //www. j a va 2s . c om String commandString) throws IOException { if(commandString == null) { // means just connected // check if the server response was valid if(!FTPReply.isPositiveCompletion(client.getReplyCode())) { runner.handleDisconnect(); return; } } else { // need to handle a command client.sendCommand(commandString); } runner.getTCPServerResponse().append(client.getReplyString()); }
From source file:com.droid.app.fotobot.FotoBot.java
public boolean files_to_ftp(List<String> FTP_files) { String server;//from w ww.ja va 2s .c om int port; String user; String pass; String FTP_folder = ""; if (FTP_server.contains("/")) { FTP_folder = FTP_server.substring(FTP_server.indexOf("/", 1)); FTP_folder = FTP_folder.substring(1); server = FTP_server.substring(0, FTP_server.indexOf("/", 1)); } else { server = FTP_server; } port = Integer.parseInt(FTP_port); user = FTP_username; pass = FTP_password; SendMessage("FTP user: " + "<br>" + user, MSG_PASS); SendMessage("FTP folder: " + "<br>" + FTP_folder, MSG_PASS); SendMessage("FTP server: " + "<br>" + server, MSG_PASS); FTPClient ftpClient = new FTPClient(); try { int reply; ftpClient.connect(server, port); System.out.println("Connected to " + server + "."); System.out.print(ftpClient.getReplyString()); reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); System.err.println("FTP server refused connection."); SendMessage("FTP ?", MSG_FAIL); return false; } } catch (Exception e) { } try { ftpClient.login(user, pass); ftpClient.enterLocalPassiveMode(); if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } SendMessage( " ? FTP ?, FTP ?.", MSG_FAIL); return false; } } catch (Exception e) { } // chdir if (FTP_folder.length() > 1) { try { ftpClient.changeWorkingDirectory(FTP_folder); if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { ftpClient.disconnect(); try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } System.err.println("FTP chdir error"); SendMessage( "FTP ? <br>" + FTP_folder, MSG_FAIL); return false; } SendMessage("FTP <br>" + FTP_folder, MSG_PASS); System.out.println("Successfully changed working directory."); } catch (Exception e) { try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e1) { e1.printStackTrace(); } SendMessage("FTP ? <br>" + FTP_folder, MSG_FAIL); System.out.println("Failed to change working directory."); return false; } } try { ftpClient.setFileType(FTP.BINARY_FILE_TYPE); } catch (Exception e) { SendMessage("FTP BINARY_FILE_TYPE", MSG_FAIL); System.out.println("Failed to change to BINARY_FILE_TYPE."); return false; } // APPROACH #1: uploads first file using an InputStream for (String str : FTP_files) { File firstLocalFile = new File(str); String firstRemoteFile = firstLocalFile.getName(); try { InputStream inputStream = new FileInputStream(firstLocalFile); SendMessage("? ", MSG_PASS); boolean done = ftpClient.storeFile(firstRemoteFile, inputStream); inputStream.close(); if (done) { SendMessage(" " + "<br>" + str + "<br>" + " ", MSG_PASS); } } catch (IOException ex) { try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } SendMessage(" ? " + "<br>" + str + "<br>" + ftpClient.getReplyCode() + "\n" + ftpClient.getReplyString() + "\n" + ex.getMessage() + "<br>" + " FTP ?.", MSG_FAIL); ex.printStackTrace(); } } try { if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); SendMessage("FTP ???? ", MSG_PASS); fbpause(h, 3); return true; } } catch (IOException ex) { ex.printStackTrace(); SendMessage("FTP ???? ", MSG_FAIL); } return false; }
From source file:com.cws.esolutions.core.utils.NetworkUtils.java
/** * Creates a connection to a target host and then executes an FTP * request to send or receive a file to or from the target. This is fully * key-based, as a result, a keyfile is required for the connection to * successfully authenticate.//from w ww . jav a2s . c o m * * @param sourceFile - The full path to the source file to transfer * @param targetFile - The full path (including file name) of the desired target file * @param targetHost - The target server to perform the transfer to * @param isUpload - <code>true</code> is the transfer is an upload, <code>false</code> if it * is a download * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing */ public static final synchronized void executeFtpConnection(final String sourceFile, final String targetFile, final String targetHost, final boolean isUpload) throws UtilityException { final String methodName = NetworkUtils.CNAME + "#executeFtpConnection(final String sourceFile, final String targetFile, final String targetHost, final boolean isUpload) throws UtilityException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", sourceFile); DEBUGGER.debug("Value: {}", targetFile); DEBUGGER.debug("Value: {}", targetHost); DEBUGGER.debug("Value: {}", isUpload); } final FTPClient client = new FTPClient(); final FTPConfig ftpConfig = appBean.getConfigData().getFtpConfig(); if (DEBUG) { DEBUGGER.debug("FTPClient: {}", client); DEBUGGER.debug("FTPConfig: {}", ftpConfig); } try { client.connect(targetHost); if (DEBUG) { DEBUGGER.debug("FTPClient: {}", client); } if (!(client.isConnected())) { throw new IOException("Failed to authenticate to remote host with the provided information"); } boolean isAuthenticated = false; if (StringUtils.isNotBlank(ftpConfig.getFtpAccount())) { isAuthenticated = client.login( (StringUtils.isNotEmpty(ftpConfig.getFtpAccount())) ? ftpConfig.getFtpAccount() : System.getProperty("user.name"), PasswordUtils.decryptText(ftpConfig.getFtpPassword(), ftpConfig.getFtpSalt(), secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(), secBean.getConfigData().getSecurityConfig().getIterations(), secBean.getConfigData().getSecurityConfig().getKeyBits(), secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(), secBean.getConfigData().getSecurityConfig().getEncryptionInstance(), appBean.getConfigData().getSystemConfig().getEncoding())); } else { isAuthenticated = client.login(ftpConfig.getFtpAccount(), null); } if (DEBUG) { DEBUGGER.debug("isAuthenticated: {}", isAuthenticated); } if (!(isAuthenticated)) { throw new IOException("Failed to connect to FTP server: " + targetHost); } client.enterLocalPassiveMode(); if (!(FileUtils.getFile(sourceFile).exists())) { throw new IOException("File " + sourceFile + " does not exist. Skipping"); } if (isUpload) { client.storeFile(targetFile, new FileInputStream(FileUtils.getFile(sourceFile))); } else { client.retrieveFile(sourceFile, new FileOutputStream(targetFile)); } if (DEBUG) { DEBUGGER.debug("Reply: {}", client.getReplyCode()); DEBUGGER.debug("Reply: {}", client.getReplyString()); } } catch (IOException iox) { throw new UtilityException(iox.getMessage(), iox); } finally { try { if (client.isConnected()) { client.completePendingCommand(); client.disconnect(); } } catch (IOException iox) { ERROR_RECORDER.error(iox.getMessage(), iox); } } }
From source file:com.github.carlosrubio.org.apache.tools.ant.taskdefs.optional.net.FTP.java
/** * Delete a file from the remote host./*www. j ava2s. c o m*/ * @param ftp ftp client * @param filename file to delete * @throws IOException in unknown circumstances * @throws BuildException if skipFailedTransfers is set to false * and the deletion could not be done */ protected void delFile(FTPClient ftp, String filename) throws IOException, BuildException { if (verbose) { log("deleting " + filename); } if (!ftp.deleteFile(resolveFile(filename))) { String s = "could not delete file: " + ftp.getReplyString(); if (skipFailedTransfers) { log(s, Project.MSG_WARN); skipped++; } else { throw new BuildException(s); } } else { log("File " + filename + " deleted from " + server, Project.MSG_VERBOSE); transferred++; } }
From source file:com.github.carlosrubio.org.apache.tools.ant.taskdefs.optional.net.FTP.java
/** * look at the response for a failed mkdir action, decide whether * it matters or not. If it does, we throw an exception * @param ftp current ftp connection// ww w. j ava 2 s . c o m * @throws BuildException if this is an error to signal */ private void handleMkDirFailure(FTPClient ftp) throws BuildException { int rc = ftp.getReplyCode(); if (!(ignoreNoncriticalErrors && (rc == FTPReply.CODE_550 || rc == FTPReply.CODE_553 || rc == CODE_521))) { throw new BuildException("could not create directory: " + ftp.getReplyString()); } }
From source file:com.github.carlosrubio.org.apache.tools.ant.taskdefs.optional.net.FTP.java
/** * Delete a directory, if empty, from the remote host. * @param ftp ftp client//from w w w. j av a 2 s.c o m * @param dirname directory to delete * @throws IOException in unknown circumstances * @throws BuildException if skipFailedTransfers is set to false * and the deletion could not be done */ protected void rmDir(FTPClient ftp, String dirname) throws IOException, BuildException { if (verbose) { log("removing " + dirname); } if (!ftp.removeDirectory(resolveFile(dirname))) { String s = "could not remove directory: " + ftp.getReplyString(); if (skipFailedTransfers) { log(s, Project.MSG_WARN); skipped++; } else { throw new BuildException(s); } } else { log("Directory " + dirname + " removed from " + server, Project.MSG_VERBOSE); transferred++; } }
From source file:base.BasePlayer.AddGenome.java
static void updateEnsemblList() { try {/*from www . j a v a 2 s . co m*/ menu = new JPopupMenu(); area = new JTextArea(); menuscroll = new JScrollPane(); area.setFont(Main.menuFont); menu.add(menuscroll); //menu.setPreferredSize(new Dimension(menu.getFontMetrics(Main.menuFont).stringWidth("0000000000000000000000000000000000000000000000000")+Main.defaultFontSize*10, (int)menu.getFontMetrics(Main.menuFont).getHeight()*4)); menu.setPreferredSize(new Dimension(300, 200)); //area.setMaximumSize(new Dimension(300, 600)); //area.setLineWrap(true); //area.setWrapStyleWord(true); //area.setPreferredSize(new Dimension(300,200)); area.revalidate(); menuscroll.getViewport().add(area); menu.pack(); menu.show(AddGenome.treescroll, 0, 0); /* area.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent arg0) { StringBuffer buf = new StringBuffer(""); for(int i= 0; i<(int)(Math.random()*100); i++) { buf.append("O"); } AddGenome.area.append(buf.toString() +"\n"); AddGenome.area.setCaretPosition(AddGenome.area.getText().length()); AddGenome.area.revalidate(); } @Override public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } });*/ FTPClient f = new FTPClient(); news = new ArrayList<String[]>(); area.append("Connecting to Ensembl...\n"); //System.out.println("Connecting to Ensembl..."); f.connect("ftp.ensembl.org"); f.enterLocalPassiveMode(); f.login("anonymous", ""); //System.out.println("Connected."); area.append("Connected.\n"); FTPFile[] files = f.listFiles("pub"); String releasedir = ""; String releasenro; for (int i = 0; i < files.length; i++) { if (files[i].isDirectory() && files[i].getName().contains("release")) { releasedir = files[i].getName(); } } files = f.listFiles("pub/" + releasedir + "/fasta/"); releasenro = releasedir.substring(releasedir.indexOf("-") + 1); area.append("Searching for new genomes"); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { FTPFile[] fastafiles = f .listFiles("pub/" + releasedir + "/fasta/" + files[i].getName() + "/dna/"); String[] urls = new String[5]; for (int j = 0; j < fastafiles.length; j++) { if (fastafiles[j].getName().contains(".dna.toplevel.")) { urls[0] = "ftp://ftp.ensembl.org/pub/" + releasedir + "/fasta/" + files[i].getName() + "/dna/" + fastafiles[j].getName(); String filePath = "/pub/" + releasedir + "/fasta/" + files[i].getName() + "/dna/" + fastafiles[j].getName(); f.sendCommand("SIZE", filePath); String reply = f.getReplyString().split("\\s+")[1]; urls[1] = reply; break; } } if (urls[0] == null) { continue; } FTPFile[] annofiles = f.listFiles("pub/" + releasedir + "/gff3/" + files[i].getName()); for (int j = 0; j < annofiles.length; j++) { if (annofiles[j].getName().contains("." + releasenro + ".gff3.gz")) { urls[2] = "ftp://ftp.ensembl.org/pub/" + releasedir + "/gff3/" + files[i].getName() + "/" + annofiles[j].getName(); String filePath = "/pub/" + releasedir + "/gff3/" + files[i].getName() + "/" + annofiles[j].getName(); f.sendCommand("SIZE", filePath); String reply = f.getReplyString().split("\\s+")[1]; urls[3] = reply; break; } } if (urls[2] == null) { continue; } if (files[i].getName().contains("homo_sapiens")) { urls[4] = "http://hgdownload.cse.ucsc.edu/goldenPath/hg19/database/cytoBand.txt.gz"; } else if (files[i].getName().contains("mus_musculus")) { urls[4] = "http://hgdownload.cse.ucsc.edu/goldenPath/mm10/database/cytoBand.txt.gz"; } String name = urls[0].substring(urls[0].lastIndexOf("/") + 1, urls[0].indexOf(".dna.")); //System.out.print(urls[0]+"\t" +urls[1] +"\t" +urls[2] +"\t" +urls[3]); if (genomeHash.containsKey(name) || AddGenome.removables.contains(name)) { //System.out.println(name +" already in the list."); area.append("."); } else { area.append("\nNew genome " + name + " added.\n"); AddGenome.area.setCaretPosition(AddGenome.area.getText().length()); AddGenome.area.revalidate(); //System.out.println("New reference " +name +" found."); organisms.add(name); news.add(urls); if (urls[4] != null) { //System.out.println(urls[0] +" " + urls[2] +" " +urls[4]); URL[] newurls = { new URL(urls[0]), new URL(urls[2]), new URL(urls[4]) }; genomeHash.put(name, newurls); } else { URL[] newurls = { new URL(urls[0]), new URL(urls[2]) }; genomeHash.put(name, newurls); } Integer[] sizes = { Integer.parseInt(urls[1]), Integer.parseInt(urls[3]) }; sizeHash.put(name, sizes); } /*if(urls[4] != null) { System.out.print("\t" +urls[4]); } System.out.println(); */ } } checkGenomes(); if (news.size() > 0) { try { //File file = new File(); FileWriter fw = new FileWriter(Main.genomeDir.getCanonicalPath() + "/ensembl_fetched.txt"); BufferedWriter bw = new BufferedWriter(fw); for (int i = 0; i < news.size(); i++) { for (int j = 0; j < news.get(i).length; j++) { if (news.get(i)[j] == null) { break; } if (j > 0) { bw.write("\t"); } bw.write(news.get(i)[j]); } bw.write("\n"); } bw.close(); fw.close(); } catch (IOException e) { e.printStackTrace(); } } } catch (Exception e) { Main.showError(e.getMessage(), "Error"); e.printStackTrace(); } }
From source file:convcao.com.caoAgent.convcaoNeptusInteraction.java
private void connectButtonActionPerformed(java.awt.event.ActionEvent evt) throws SocketException, IOException { String[] vehicles = controlledVehicles.split(","); jTextArea1.setText(""); jTextArea1.repaint();/*from w w w.j av a 2 s .co m*/ showText("Initializing Control Structures"); try { startLocalStructures(vehicles); } catch (Exception e) { GuiUtils.errorMessage(getConsole(), e); return; } AUVS = positions.keySet().size(); showText("Initializing server connection"); FTPClient client = new FTPClient(); boolean PathNameCreated = false; try { client.connect("www.convcao.com", 21); client.login(jTextField1.getText(), new String(jPasswordField1.getPassword())); PathNameCreated = client.makeDirectory("/NEPTUS/" + SessionID); client.logout(); } catch (IOException e) { jLabel6.setText("Connection Error"); throw e; } showText("Sending session data"); InputData initialState = new InputData(); initialState.DateTime = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date()); initialState.SessionID = SessionID; initialState.DemoMode = "1"; initialState.AUVs = "" + positions.keySet().size(); String fileName = SessionID + ".txt"; Gson gson = new Gson(); String json = gson.toJson(initialState); PrintWriter writer = new PrintWriter(fileName, "UTF-8"); writer.write(json); writer.close(); if (PathNameCreated) { jLabel6.setText("Connection Established"); jLabel1.setVisible(true); System.out.println("Uploading first file"); Upload("www.convcao.com", "NEPTUS", "", jTextField1.getText(), new String(jPasswordField1.getPassword()), fileName); //send first file System.out.println("Uploading second file"); Upload("www.convcao.com", "NEPTUS/" + SessionID, "plugins-dev/caoAgent/convcao/com/caoAgent/", jTextField1.getText(), new String(jPasswordField1.getPassword()), "mapPortoSparse.txt"); //send sparse map System.out.println("Both files uploaded"); jButton1.setEnabled(true); jButton2.setEnabled(true); jTextPane1.setEditable(false); jTextField1.setEditable(false); jPasswordField1.setEditable(false); connectButton.setEnabled(false); renewButton.setEnabled(false); } else { jLabel6.setText(client.getReplyString()); jLabel1.setVisible(false); } myDeleteFile(fileName); showText("ConvCAO control has started"); }
From source file:convcao.com.agent.ConvcaoNeptusInteraction.java
private void connectButtonActionPerformed(ActionEvent evt) throws SocketException, IOException { String[] vehicles = controlledVehicles.split(","); jTextArea1.setText(""); jTextArea1.repaint();//from w w w . j a v a 2 s .co m showText("Initializing Control Structures"); try { startLocalStructures(vehicles); } catch (Exception e) { GuiUtils.errorMessage(getConsole(), e); return; } auvs = positions.keySet().size(); showText("Initializing server connection"); FTPClient client = new FTPClient(); boolean PathNameCreated = false; try { client.connect("www.convcao.com", 21); client.login(jTextField1.getText(), new String(jPasswordField1.getPassword())); PathNameCreated = client.makeDirectory("/NEPTUS/" + sessionID); client.logout(); } catch (IOException e) { jLabel6.setText("Connection Error"); throw e; } showText("Sending session data"); InputData initialState = new InputData(); initialState.DateTime = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date()); initialState.SessionID = sessionID; initialState.DemoMode = "1"; initialState.AUVs = "" + positions.keySet().size(); String fileName = sessionID + ".txt"; Gson gson = new Gson(); String json = gson.toJson(initialState); PrintWriter writer = new PrintWriter(fileName, "UTF-8"); writer.write(json); writer.close(); if (PathNameCreated) { jLabel6.setText("Connection Established"); jLabel1.setVisible(true); System.out.println("Uploading first file"); upload("www.convcao.com", "NEPTUS", "", jTextField1.getText(), new String(jPasswordField1.getPassword()), fileName); // send first file System.out.println("Uploading second file"); String mapFxStr = FileUtil.getResourceAsFileKeepName("convcao/com/caoAgent/mapPortoSparse.txt"); File mapFx = new File(mapFxStr); upload("www.convcao.com", "NEPTUS/" + sessionID, mapFx.getParent(), jTextField1.getText(), new String(jPasswordField1.getPassword()), "mapPortoSparse.txt"); // send sparse map System.out.println("Both files uploaded"); jButton1.setEnabled(true); jButton2.setEnabled(true); jTextPane1.setEditable(false); jTextField1.setEditable(false); jPasswordField1.setEditable(false); connectButton.setEnabled(false); renewButton.setEnabled(false); } else { jLabel6.setText(client.getReplyString()); jLabel1.setVisible(false); } myDeleteFile(fileName); showText("ConvCAO control has started"); }