├── .gitignore ├── LICENSE-2.0.txt ├── README.md ├── pom.xml └── src ├── main └── java │ └── io │ └── github │ └── bckfnn │ └── ftp │ ├── FtpClient.java │ ├── FtpFile.java │ ├── Progress.java │ ├── ProgressPump.java │ ├── Response.java │ └── package-info.java └── test └── java └── io └── github └── bckfnn └── ftp ├── FtpClientTele2Test.java └── HandlerLatch.java /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | /.project 3 | /.classpath 4 | /.settings 5 | *.swp 6 | *~ 7 | -------------------------------------------------------------------------------- /LICENSE-2.0.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2016 Finn Bock 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # actioner 2 | 3 | [ ![Download](https://api.bintray.com/packages/bckfnn/maven/vertx-ftp-client/images/download.svg) ](https://bintray.com/bckfnn/maven/vertx-ftp-client/_latestVersion) 4 | 5 | __vertx-ftp-client__ is a simple limited async ftp client which works with vert.x 6 | 7 | ## Release 8 | 9 | Releases management are done with [jgit-flow](https://bitbucket.org/atlassian/jgit-flow/wiki/Home) and deployment to done to bintray's jcenter. 10 | 11 | Step to perform a release: 12 | 13 | 1. develop new features on the `develop` branch 14 | 2. `mvn jgitflow:release-start` 15 | 3. `mvn jgitflow:release-finish` 16 | 4. In eclipse do `Team/Remote/Push`, `Next`, `Next`, `Finish` 17 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 4.0.0 5 | io.github.bckfnn 6 | vertx-ftp-client 7 | 0.0.3-SNAPSHOT 8 | jar 9 | 10 | FTP client for vertx 11 | 12 | 13 | UTF-8 14 | 3.2.1 15 | 16 | 1.7.21 17 | 1.1.7 18 | 19 | 20 | 21 | 22 | bintray-bckfnn-maven 23 | bckfnn-maven 24 | https://api.bintray.com/maven/bckfnn/maven/vertx-ftp-client/;publish=1 25 | 26 | 27 | 28 | 29 | 30 | io.vertx 31 | vertx-core 32 | ${vertx.version} 33 | 34 | 35 | 36 | io.vertx 37 | vertx-codegen 38 | ${vertx.version} 39 | 40 | 41 | 42 | 43 | io.vertx 44 | vertx-core 45 | ${vertx.version} 46 | test-jar 47 | test 48 | 49 | 50 | 51 | io.vertx 52 | vertx-unit 53 | ${vertx.version} 54 | test 55 | 56 | 57 | 58 | org.slf4j 59 | slf4j-api 60 | ${slf4.version} 61 | 62 | 63 | ch.qos.logback 64 | logback-classic 65 | ${logback.version} 66 | 67 | 68 | 69 | junit 70 | junit 71 | 4.12 72 | test 73 | 74 | 75 | 76 | 77 | 78 | 79 | maven-compiler-plugin 80 | 3.5.1 81 | 82 | 1.8 83 | 1.8 84 | 85 | 86 | 87 | 88 | external.atlassian.jgitflow 89 | jgitflow-maven-plugin 90 | 1.0-m5.1 91 | 92 | 93 | true 94 | 95 | 96 | 97 | 98 | 99 | org.apache.maven.plugins 100 | maven-source-plugin 101 | 3.0.0 102 | 103 | 104 | attach-sources 105 | 106 | jar 107 | 108 | 109 | 110 | 111 | 112 | 113 | org.apache.maven.plugins 114 | maven-javadoc-plugin 115 | 2.10.3 116 | 117 | 118 | attach-javadocs 119 | 120 | jar 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | -------------------------------------------------------------------------------- /src/main/java/io/github/bckfnn/ftp/FtpClient.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Finn Bock 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.bckfnn.ftp; 17 | 18 | import java.util.concurrent.atomic.AtomicInteger; 19 | import java.util.function.Consumer; 20 | import java.util.regex.Matcher; 21 | import java.util.regex.Pattern; 22 | 23 | import org.slf4j.Logger; 24 | import org.slf4j.LoggerFactory; 25 | 26 | import io.vertx.core.AsyncResult; 27 | import io.vertx.core.Future; 28 | import io.vertx.core.Handler; 29 | import io.vertx.core.Vertx; 30 | import io.vertx.core.buffer.Buffer; 31 | import io.vertx.core.net.NetClient; 32 | import io.vertx.core.net.NetSocket; 33 | import io.vertx.core.parsetools.RecordParser; 34 | import io.vertx.core.streams.ReadStream; 35 | import io.vertx.core.streams.WriteStream; 36 | 37 | /** 38 | * Main FtpClient class to use when sending commands to a FTP server. 39 | * 40 | * @see FTP RFC 41 | */ 42 | public class FtpClient { 43 | private static Logger log = LoggerFactory.getLogger(FtpClient.class); 44 | 45 | private Vertx vertx; 46 | private String host; 47 | private int port; 48 | private NetClient client; 49 | private NetSocket socket; 50 | private Handler endHandler = $ -> {}; 51 | 52 | private Response response = null; 53 | private Handler> next; 54 | 55 | /** 56 | * Create a ftp client which connects to the specified host and port. 57 | * @param vertx the vertx instance to use for creating connections. 58 | * @param host the host where the FTP server is running. 59 | * @param port the port on the FTP server. 60 | */ 61 | public FtpClient(Vertx vertx, String host, int port) { 62 | this.vertx = vertx; 63 | this.host = host; 64 | this.port = port; 65 | } 66 | 67 | /** 68 | * Connect to the server. 69 | * @param handler callback handler that is called when the connection is completed. 70 | */ 71 | public void connect(Handler> handler) { 72 | next = resp(handler, when("220", c -> { 73 | handler.handle(Future.succeededFuture()); 74 | })); 75 | 76 | client = vertx.createNetClient(); 77 | client.connect(port, host, res -> { 78 | socket = res.result(); 79 | 80 | if (res.failed()) { 81 | handler.handle(Future.failedFuture(res.cause())); 82 | } else { 83 | RecordParser parser = RecordParser.newDelimited("\n", this::output); 84 | socket.handler(parser); 85 | } 86 | }); 87 | } 88 | 89 | /** 90 | * Perform a login on the FTP server using the specified user name and password. 91 | * @param user the user name 92 | * @param passwd the password 93 | * @param handler callback handler that is called when the login is completed. 94 | */ 95 | public void login(String user, String passwd, Handler> handler) { 96 | write("USER " + user, resp(handler, 97 | when("230", u -> { 98 | handler.handle(Future.succeededFuture()); 99 | }), 100 | when("331", "332", u -> { 101 | write("PASS " + passwd, resp(handler, 102 | when("230", "202", p -> { 103 | handler.handle(Future.succeededFuture()); 104 | }))); 105 | }))); 106 | } 107 | 108 | /** 109 | * Perform a list file and directories of the current working directory. 110 | * @param handler callback handler that is called when the list is completed. 111 | */ 112 | public void list(Handler> handler) { 113 | list(null, handler); 114 | } 115 | 116 | /** 117 | * Perform a list of the file or directories specifed by path. 118 | * @param path the path to list. 119 | * @param handler callback handler that is called when the list is completed. 120 | */ 121 | public void list(String path, Handler> handler) { 122 | Buffer data = Buffer.buffer(); 123 | 124 | pasv(handler, datasocket -> { 125 | datasocket.handler(b -> { 126 | data.appendBuffer(b); 127 | }); 128 | }, $ -> { 129 | write("LIST" + (path != null ? " " +path :""), resp(handler, 130 | when("125", "150", list -> { 131 | handle(resp(handler, 132 | when("226", "250", listdone -> { 133 | handler.handle(Future.succeededFuture(data)); 134 | }))); 135 | }))); 136 | }); 137 | } 138 | 139 | /** 140 | * Perform a retrive (download) of the file by path. 141 | * @param path the path to list. 142 | * @param localFile an asyncFile where the download file will be written 143 | * @param progress a progress handler that is called for each part that is recieved. 144 | * @param handler callback handler that is called when the list is completed. 145 | */ 146 | public void retr(String path, WriteStream localFile, Handler progress, Handler> handler) { 147 | AtomicInteger ends = new AtomicInteger(0); 148 | pasv(handler, datasocket -> { 149 | datasocket.endHandler($ -> { 150 | if (ends.incrementAndGet() == 2) { 151 | handler.handle(Future.succeededFuture()); 152 | } 153 | }); 154 | new ProgressPump(datasocket, localFile, pumped -> { 155 | progress.handle(new Progress(this, pumped)); 156 | }).start(); 157 | }, $ -> { 158 | write("RETR " + path, resp(handler, 159 | when("125", "150", retr -> { 160 | handle(resp(handler, 161 | when("226", "250", listdone -> { 162 | if (ends.incrementAndGet() == 2) { 163 | handler.handle(Future.succeededFuture()); 164 | } 165 | }))); 166 | }))); 167 | }); 168 | } 169 | 170 | /** 171 | * Perform a store (upload) to the file of path. 172 | * @param path the path to upload to. 173 | * @param localFile an asyncFile where the download file will be written 174 | * @param progress a progress handler that is called for each part that is recieved. 175 | * @param handler callback handler that is called when the list is completed. 176 | */ 177 | public void stor(String path, ReadStream localFile, Handler progress, Handler> handler) { 178 | AtomicInteger ends = new AtomicInteger(0); 179 | pasv(handler, datasocket -> { 180 | localFile.endHandler($ -> { 181 | datasocket.close(); 182 | if (ends.incrementAndGet() == 2) { 183 | handler.handle(Future.succeededFuture()); 184 | } 185 | }); 186 | new ProgressPump(localFile, datasocket, pumped -> { 187 | progress.handle(new Progress(this, pumped)); 188 | }).start(); 189 | }, $ -> { 190 | write("STOR " + path, resp(handler, 191 | when("125", "150", retr -> { 192 | handle(resp(handler, 193 | when("226", "250", listdone -> { 194 | if (ends.incrementAndGet() == 2) { 195 | handler.handle(Future.succeededFuture()); 196 | } 197 | }))); 198 | }))); 199 | }); 200 | } 201 | 202 | /** 203 | * Perform a delete on the server. 204 | * @param path the path to upload to. 205 | * @param handler callback handler that is called when the list is completed. 206 | */ 207 | public void dele(String path, Handler> handler) { 208 | write("DELE " + path, resp(handler, 209 | when("250", pasv -> { 210 | handler.handle(Future.succeededFuture()); 211 | }))); 212 | } 213 | 214 | /** 215 | * Perform a change directory on the server. 216 | * @param dir the directory to change into. 217 | * @param handler callback handler that is called when the list is completed. 218 | */ 219 | public void cwd(String dir, Handler> handler) { 220 | write("CWD " + dir, resp(handler, 221 | when("250", pasv -> { 222 | handler.handle(Future.succeededFuture()); 223 | }))); 224 | } 225 | 226 | public void cdup(Handler> handler) { 227 | write("CDUP", resp(handler, 228 | when("200", pasv -> { 229 | handler.handle(Future.succeededFuture()); 230 | }))); 231 | } 232 | 233 | public void rmd(String dir, Handler> handler) { 234 | write("RMD " + dir, resp(handler, 235 | when("250", pasv -> { 236 | handler.handle(Future.succeededFuture()); 237 | }))); 238 | } 239 | 240 | public void mkd(String dir, Handler> handler) { 241 | write("MKD " + dir, resp(handler, 242 | when("257", pasv -> { 243 | handler.handle(Future.succeededFuture()); 244 | }))); 245 | } 246 | 247 | public void quit(Handler> handler) { 248 | write("QUIT", resp(handler, 249 | when("200", pasv -> { 250 | handler.handle(Future.succeededFuture()); 251 | }))); 252 | } 253 | 254 | private void write(String cmd, Handler> handler) { 255 | this.next = handler; 256 | write(cmd); 257 | } 258 | 259 | private void handle(Handler> handler) { 260 | this.next = handler; 261 | } 262 | 263 | private void write(String line) { 264 | log.debug(">{}", line); 265 | socket.write(line + "\r\n"); 266 | } 267 | 268 | private void pasv(Handler> handler, Handler dataConnection, Handler cmd) { 269 | write("PASV", resp(handler, 270 | when("227", pasv -> { 271 | int port = pasvPort(pasv); 272 | client.connect(port, host, res -> { 273 | NetSocket datasocket = res.result(); 274 | dataConnection.handle(datasocket); 275 | }); 276 | cmd.handle(null); 277 | }))); 278 | } 279 | 280 | private void fail(String msg) { 281 | throw new RuntimeException(msg); 282 | } 283 | 284 | private void output(Buffer buf) { 285 | if (response == null) { 286 | response = new Response(next); 287 | } 288 | Pattern p = Pattern.compile("(\\d\\d\\d)([ -])(.*)"); 289 | Matcher m = p.matcher(buf.toString().trim()); 290 | 291 | if (m.matches()) { 292 | String code = m.group(1); 293 | log.debug(code + " " + m.group(2) + " " + m.group(3)); 294 | if (code.equals("421")) { 295 | socket.close(); 296 | endHandler.handle(null); 297 | return; 298 | } 299 | if (response == null) { 300 | fail("unexpected response " + buf); 301 | return; 302 | } 303 | response.setCode(m.group(1)); 304 | response.addMessage(m.group(3)); 305 | 306 | if (m.group(2).equals(" ")) { 307 | Response response = this.response; 308 | this.response = null; 309 | log.trace("handling {}", response); 310 | next.handle(Future.succeededFuture(response)); 311 | } else if (m.group(2).equals("-")) { 312 | log.info("waiting for more"); 313 | } 314 | } 315 | } 316 | 317 | private int pasvPort(Response resp) { 318 | Pattern p = Pattern.compile(".*\\((\\d+),(\\d+),(\\d+),(\\d+),(\\d+),(\\d+)\\).*"); 319 | Matcher m = p.matcher(resp.messages.get(0)); 320 | if (m.matches()) { 321 | return Integer.parseInt(m.group(5)) * 256 + Integer.parseInt(m.group(6)); 322 | } 323 | throw new RuntimeException("xx"); 324 | } 325 | 326 | 327 | public static Handler> resp(Handler> handler, When... whens) { 328 | return ar -> { 329 | if (ar.succeeded()) { 330 | Response r = ar.result(); 331 | for (When w : whens) { 332 | if (w.match(r)) { 333 | return; 334 | } 335 | } 336 | handler.handle(Future.failedFuture(r.code + " " + r.messages.get(0))); 337 | } else { 338 | handler.handle(Future.failedFuture(ar.cause())); 339 | } 340 | }; 341 | } 342 | 343 | public static When when(String code, Consumer func) { 344 | return new When(func, code); 345 | } 346 | 347 | public static When when(String code1, String code2, Consumer func) { 348 | return new When(func, code1, code2); 349 | } 350 | 351 | private static class When { 352 | String[] codes; 353 | Consumer func; 354 | 355 | public When(Consumer func, String... codes) { 356 | this.codes = codes; 357 | this.func = func; 358 | } 359 | public boolean match(Response r) { 360 | for (String code : codes) { 361 | if (r.getCode().equals(code)) { 362 | func.accept(r); 363 | return true; 364 | } 365 | } 366 | return false; 367 | } 368 | } 369 | } 370 | -------------------------------------------------------------------------------- /src/main/java/io/github/bckfnn/ftp/FtpFile.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Finn Bock 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.github.bckfnn.ftp; 18 | 19 | import java.io.File; 20 | import java.util.ArrayList; 21 | import java.util.List; 22 | import java.util.regex.Matcher; 23 | import java.util.regex.Pattern; 24 | 25 | import org.slf4j.Logger; 26 | import org.slf4j.LoggerFactory; 27 | 28 | public class FtpFile { 29 | private static Logger log = LoggerFactory.getLogger(File.class); 30 | 31 | private static Pattern filere = Pattern.compile("(.)......... +\\d+ +\\d+ +\\d+ +(\\d+) ([A-Z][a-z][a-z] +\\d+ +(?:(?:\\d\\d:\\d\\d)|(?:\\d+))) (.*)"); 32 | 33 | private String type; 34 | private String name; 35 | private long size; 36 | private String date; 37 | 38 | 39 | public String getType() { 40 | return type; 41 | } 42 | 43 | public String getName() { 44 | return name; 45 | } 46 | 47 | public long getSize() { 48 | return size; 49 | } 50 | 51 | public String getDate() { 52 | return date; 53 | } 54 | 55 | public boolean isDirectory() { 56 | return type.equals("d"); 57 | } 58 | 59 | public static FtpFile from(String line) { 60 | Matcher m = filere.matcher(line); 61 | //log.info("file:" + f.toString()); 62 | if (!m.matches()) { 63 | log.error("line " + line + " does not match dir re"); 64 | return null; 65 | } else { 66 | String size = m.group(2); 67 | String date = m.group(3); 68 | String fname = m.group(4); 69 | 70 | FtpFile f = new FtpFile(); 71 | f.type = m.group(1); 72 | f.size = Long.parseLong(size); 73 | f.name = fname; 74 | f.date = date; 75 | return f; 76 | } 77 | } 78 | 79 | public static List listing(String listing) { 80 | List ret = new ArrayList<>(); 81 | 82 | for (String f : listing.split("\n")) { 83 | if (f.endsWith("\r")) { 84 | f = f.substring(0, f.length() - 1); 85 | } 86 | FtpFile file = FtpFile.from(f.toString()); 87 | 88 | if (file == null) { 89 | continue; 90 | } 91 | if (file.name.equals(".") || file.name.equals("..")) { 92 | continue; 93 | } 94 | 95 | ret.add(file); 96 | } 97 | return ret; 98 | } 99 | 100 | @Override 101 | public String toString() { 102 | return "FtpFile [type=" + type + ", name=" + name + ", size=" + size + ", date=" + date + "]"; 103 | } 104 | } -------------------------------------------------------------------------------- /src/main/java/io/github/bckfnn/ftp/Progress.java: -------------------------------------------------------------------------------- 1 | package io.github.bckfnn.ftp; 2 | 3 | public class Progress { 4 | private FtpClient client; 5 | private int count; 6 | 7 | 8 | public Progress(FtpClient client, int count) { 9 | super(); 10 | this.client = client; 11 | this.count = count; 12 | } 13 | 14 | public FtpClient client() { 15 | return client; 16 | } 17 | 18 | public int count() { 19 | return count; 20 | }; 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/io/github/bckfnn/ftp/ProgressPump.java: -------------------------------------------------------------------------------- 1 | package io.github.bckfnn.ftp; 2 | 3 | import io.vertx.core.Handler; 4 | import io.vertx.core.buffer.Buffer; 5 | import io.vertx.core.streams.Pump; 6 | import io.vertx.core.streams.ReadStream; 7 | import io.vertx.core.streams.WriteStream; 8 | 9 | /** 10 | * Pumps data from a {@link io.vertx.core.streams.ReadStream} to a {@link io.vertx.core.streams.WriteStream} and performs flow control where necessary to 11 | * prevent the write stream buffer from getting overfull.

12 | * Instances of this class read bytes from a {@link io.vertx.core.streams.ReadStream} and write them to a {@link io.vertx.core.streams.WriteStream}. If data 13 | * can be read faster than it can be written this could result in the write queue of the {@link io.vertx.core.streams.WriteStream} growing 14 | * without bound, eventually causing it to exhaust all available RAM.

15 | * To prevent this, after each write, instances of this class check whether the write queue of the {@link 16 | * io.vertx.core.streams.WriteStream} is full, and if so, the {@link io.vertx.core.streams.ReadStream} is paused, and a {@code drainHandler} is set on the 17 | * {@link io.vertx.core.streams.WriteStream}. When the {@link io.vertx.core.streams.WriteStream} has processed half of its backlog, the {@code drainHandler} will be 18 | * called, which results in the pump resuming the {@link io.vertx.core.streams.ReadStream}.

19 | * This class can be used to pump from any {@link io.vertx.core.streams.ReadStream} to any {@link io.vertx.core.streams.WriteStream}, 20 | * e.g. from an {@link io.vertx.core.http.HttpServerRequest} to an {@link io.vertx.core.file.AsyncFile}, 21 | * or from {@link io.vertx.core.net.NetSocket} to a {@link io.vertx.core.http.WebSocket}.

22 | * 23 | * Instances of this class are not thread-safe.

24 | * 25 | * @author Tim Fox 26 | */ 27 | public class ProgressPump implements Pump { 28 | 29 | private final ReadStream readStream; 30 | private final WriteStream writeStream; 31 | private final Handler dataHandler; 32 | private final Handler drainHandler; 33 | private int pumped; 34 | private Handler progress; 35 | 36 | /** 37 | * Create a new {@code Pump} with the given {@code ReadStream} and {@code WriteStream}. Set the write queue max size 38 | * of the write stream to {@code maxWriteQueueSize} 39 | */ 40 | ProgressPump(ReadStream rs, WriteStream ws, Handler progress, int maxWriteQueueSize) { 41 | this(rs, ws, progress); 42 | this.writeStream.setWriteQueueMaxSize(maxWriteQueueSize); 43 | } 44 | 45 | ProgressPump(ReadStream rs, WriteStream ws, Handler progress) { 46 | this.readStream = rs; 47 | this.writeStream = ws; 48 | this.progress = progress; 49 | drainHandler = v-> readStream.resume(); 50 | dataHandler = data -> { 51 | writeStream.write(data); 52 | incPumped(data); 53 | if (writeStream.writeQueueFull()) { 54 | readStream.pause(); 55 | writeStream.drainHandler(drainHandler); 56 | } 57 | }; 58 | } 59 | 60 | /** 61 | * Set the write queue max size to {@code maxSize} 62 | */ 63 | @Override 64 | public ProgressPump setWriteQueueMaxSize(int maxSize) { 65 | writeStream.setWriteQueueMaxSize(maxSize); 66 | return this; 67 | } 68 | 69 | /** 70 | * Start the Pump. The Pump can be started and stopped multiple times. 71 | */ 72 | @Override 73 | public ProgressPump start() { 74 | readStream.handler(dataHandler); 75 | return this; 76 | } 77 | 78 | /** 79 | * Stop the Pump. The Pump can be started and stopped multiple times. 80 | */ 81 | @Override 82 | public ProgressPump stop() { 83 | writeStream.drainHandler(null); 84 | readStream.handler(null); 85 | return this; 86 | } 87 | 88 | /** 89 | * Return the total number of elements pumped by this pump. 90 | */ 91 | @Override 92 | public synchronized int numberPumped() { 93 | return pumped; 94 | } 95 | 96 | // Note we synchronize as numberPumped can be called from a different thread however incPumped will always 97 | // be called from the same thread so we benefit from bias locked optimisation which should give a very low 98 | // overhead 99 | private synchronized void incPumped(Buffer buf) { 100 | pumped += buf.length(); 101 | progress.handle(pumped); 102 | } 103 | 104 | 105 | } 106 | -------------------------------------------------------------------------------- /src/main/java/io/github/bckfnn/ftp/Response.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Finn Bock 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.bckfnn.ftp; 17 | 18 | import java.util.ArrayList; 19 | import java.util.List; 20 | 21 | import io.vertx.core.AsyncResult; 22 | import io.vertx.core.Future; 23 | import io.vertx.core.Handler; 24 | 25 | public class Response { 26 | protected String code; 27 | protected List messages = new ArrayList<>(); 28 | Handler> handler; 29 | 30 | public Response(Handler> handler) { 31 | this.handler = handler; 32 | } 33 | 34 | public void setCode(String code) { 35 | this.code = code; 36 | } 37 | 38 | public String getCode() { 39 | return code; 40 | } 41 | 42 | public void addMessage(String message) { 43 | this.messages.add(message); 44 | } 45 | 46 | public boolean codeIs(String value) { 47 | return code.equals(value); 48 | } 49 | 50 | public void fail(String msg) { 51 | handler.handle(Future.failedFuture(new RuntimeException(msg))); 52 | } 53 | 54 | public void fail() { 55 | handler.handle(Future.failedFuture(new RuntimeException(code + " " + messages.get(0)))); 56 | } 57 | 58 | public void succes() { 59 | handler.handle(Future.succeededFuture(this)); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/io/github/bckfnn/ftp/package-info.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Finn Bock 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | /** 18 | * A simple ftp client for vertx. 19 | */ 20 | package io.github.bckfnn.ftp; -------------------------------------------------------------------------------- /src/test/java/io/github/bckfnn/ftp/FtpClientTele2Test.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Finn Bock 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.bckfnn.ftp; 17 | 18 | import java.util.UUID; 19 | import java.util.function.BiConsumer; 20 | 21 | import org.junit.AfterClass; 22 | import org.junit.BeforeClass; 23 | import org.junit.Test; 24 | 25 | import io.vertx.core.Vertx; 26 | import io.vertx.core.file.OpenOptions; 27 | 28 | public class FtpClientTele2Test { 29 | static Vertx vertx; 30 | 31 | @BeforeClass 32 | public static void setup() { 33 | vertx = Vertx.vertx(); 34 | } 35 | 36 | @AfterClass 37 | public static void teardown() { 38 | vertx.close(); 39 | } 40 | 41 | @Test 42 | public void testLogin() { 43 | login("speedtest.tele2.net", "anonymous", "passwd", (client, latch) -> { 44 | latch.countDown(); 45 | }); 46 | } 47 | 48 | @Test 49 | public void testList() { 50 | login("speedtest.tele2.net", "anonymous", "passwd", (client, latch) -> { 51 | client.list(list -> { 52 | if (latch.failed(list)) { 53 | return; 54 | } 55 | System.out.println("list " + list.result()); 56 | latch.countDown(); 57 | }); 58 | }); 59 | } 60 | 61 | 62 | @Test 63 | public void testListParsed() { 64 | login("speedtest.tele2.net", "anonymous", "passwd", (client, latch) -> { 65 | client.list(list -> { 66 | if (latch.failed(list)) { 67 | return; 68 | } 69 | for (FtpFile f : FtpFile.listing(list.result().toString())) { 70 | System.out.println(f); 71 | } 72 | 73 | latch.countDown(); 74 | }); 75 | }); 76 | } 77 | 78 | @Test 79 | public void testRetr() { 80 | login("speedtest.tele2.net", "anonymous", "passwd", (client, latch) -> { 81 | vertx.fileSystem().open("target/tmp.zip", new OpenOptions().setWrite(true).setTruncateExisting(true), arfile -> { 82 | if (latch.failed(arfile)) { 83 | return; 84 | } 85 | client.retr("512KB.zip", arfile.result(), progress -> {}, retr -> { 86 | if (latch.failed(retr)) { 87 | return; 88 | } 89 | arfile.result().close(close -> { 90 | if (latch.failed(close)) { 91 | return; 92 | } 93 | latch.countDown(); 94 | }); 95 | }); 96 | 97 | }); 98 | }); 99 | } 100 | 101 | 102 | @Test 103 | public void testStor() { 104 | login("speedtest.tele2.net", "anonymous", "passwd", (client, latch) -> { 105 | vertx.fileSystem().open("LICENSE-2.0.txt", new OpenOptions().setRead(true), arfile -> { 106 | if (latch.failed(arfile)) { 107 | return; 108 | } 109 | client.stor("upload/LICENSE-2.0.txt-" + UUID.randomUUID().toString(), arfile.result(), progress -> {}, retr -> { 110 | if (latch.failed(retr)) { 111 | return; 112 | } 113 | arfile.result().close(close -> { 114 | if (latch.failed(close)) { 115 | return; 116 | } 117 | latch.countDown(); 118 | }); 119 | }); 120 | 121 | }); 122 | }); 123 | } 124 | 125 | private void login(String host, String user, String pass, BiConsumer> handler) { 126 | HandlerLatch latch = new HandlerLatch<>(); 127 | 128 | FtpClient client = new FtpClient(vertx, host, 21); 129 | client.connect(connect -> { 130 | if (latch.failed(connect)) { 131 | return; 132 | } 133 | client.login(user, pass, login -> { 134 | if (latch.failed(login)) { 135 | return; 136 | } 137 | handler.accept(client, latch); 138 | }); 139 | }); 140 | latch.await(); 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /src/test/java/io/github/bckfnn/ftp/HandlerLatch.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Finn Bock 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.bckfnn.ftp; 17 | 18 | import java.util.concurrent.CountDownLatch; 19 | 20 | import org.junit.Assert; 21 | import org.slf4j.Logger; 22 | import org.slf4j.LoggerFactory; 23 | 24 | import io.vertx.core.AsyncResult; 25 | import io.vertx.core.AsyncResultHandler; 26 | 27 | public class HandlerLatch implements AsyncResultHandler { 28 | static Logger log = LoggerFactory.getLogger(HandlerLatch.class); 29 | 30 | private CountDownLatch latch = new CountDownLatch(1); 31 | private Throwable error; 32 | 33 | @Override 34 | public void handle(AsyncResult event) { 35 | System.out.println(event.succeeded() + " " + event.result() + " " + event.cause()); 36 | if (event.failed()) { 37 | log.error("caugth", event.cause()); 38 | latch.countDown(); 39 | } 40 | } 41 | 42 | public void countDown() { 43 | latch.countDown(); 44 | log.debug("countDown"); 45 | } 46 | 47 | public Void fail(Throwable error) { 48 | this.error = error; 49 | latch.countDown(); 50 | return null; 51 | } 52 | 53 | public boolean failed(AsyncResult asyncResult) { 54 | if (asyncResult.failed()) { 55 | this.error = asyncResult.cause(); 56 | latch.countDown(); 57 | return true; 58 | } 59 | return false; 60 | } 61 | 62 | public void await() { 63 | try { 64 | latch.await(); 65 | } catch (InterruptedException e) { 66 | e.printStackTrace(); 67 | } 68 | log.debug("awaited"); 69 | if (error != null) { 70 | Assert.assertTrue(error.toString(), false); 71 | } 72 | } 73 | } --------------------------------------------------------------------------------