### Run Commons Net Example via Classpath Source: https://commons.apache.org/proper/commons-net/index.html Execute a sample application by including both the examples and main library JARs in the classpath. ```bash java -cp commons-net-examples-3.8.0.jar;commons-net-3.8.0.jar examples/ftp/FTPClientExample [parameters] ``` -------------------------------- ### Example Transaction Sequence Source: https://commons.apache.org/proper/commons-net/jacoco/org.apache.commons.net.smtp/SMTPClient.java.html A partial example demonstrating the initiation of message data transmission. ```java writer = client.sendMessageData(); if (writer == null) // failure return false; ``` -------------------------------- ### Simple NTP Server Example Source: https://commons.apache.org/proper/commons-net/rat-report.html A basic implementation of an NTP server that responds to time requests. This is a simplified example and may not conform to all NTP specifications. ```Java /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.net.examples.ntp; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import org.apache.commons.net.ntp.NtpV3Packet; import org.apache.commons.net.ntp.NtpV3Support; import org.apache.commons.net.ntp.TimeStamp; /** * A very simple NTP server that responds to requests with the current time. * This is a basic example and does not implement all NTP features. */ public class SimpleNTPServer { private static final int NTP_PORT = 123; private static final int BUFFER_SIZE = 48; // Standard NTP packet size public static void main(String[] args) { try (DatagramSocket socket = new DatagramSocket(NTP_PORT)) { System.out.println("NTP Server started on port " + NTP_PORT); byte[] buffer = new byte[BUFFER_SIZE]; while (true) { DatagramPacket requestPacket = new DatagramPacket(buffer, buffer.length); socket.receive(requestPacket); // Process the NTP request NtpV3Support ntpSupport = new NtpV3Support(); NtpV3Packet request = ntpSupport.getNtpMessage(buffer); // Create a response packet NtpV3Packet response = ntpSupport.getNtpMessage(buffer); response.setMode(NtpV3Packet.MODE_SERVER); response.setVersion(NtpV3Packet.VERSION_3); response.setStratum(1); // Stratum 1 indicates a reference clock response.setReferenceId(0); response.setPoll(4); // Poll interval response.setPrecision(0); // Set timestamps long currentTimeMillis = System.currentTimeMillis(); TimeStamp referenceTime = TimeStamp.getNtpTime(currentTimeMillis - 1000); // Adjust for clock drift response.setReferenceTime(referenceTime); response.setOriginateTime(request.getOriginateTime()); response.setReceiveTime(TimeStamp.getNtpTime(currentTimeMillis)); response.setTransmitTime(TimeStamp.getNtpTime(currentTimeMillis)); // Send the response back to the client DatagramPacket responsePacket = new DatagramPacket(response.toByteArray(), response.toByteArray().length, requestPacket.getAddress(), requestPacket.getPort()); socket.send(responsePacket); System.out.println("Responded to NTP request from " + requestPacket.getAddress().getHostAddress()); } } catch (IOException e) { System.err.println("Error: Could not start NTP server."); e.printStackTrace(); } } } ``` -------------------------------- ### GET /listHelp Source: https://commons.apache.org/proper/commons-net/jacoco/org.apache.commons.net.ftp/FTPClient.java.html Retrieves the system help string from the FTP server. ```APIDOC ## GET /listHelp ### Description Fetches the system help string from the FTP server. ### Method GET ### Endpoint /listHelp ### Response #### Success Response (200) - **result** (String) - The system help string obtained from the server, or null if it could not be obtained. ``` -------------------------------- ### FTP z/OS Site Command Example Source: https://commons.apache.org/proper/commons-net/apidocs/src-html/org/apache/commons/net/ftp/parser/MVSFTPEntryParser.html Example of using the FTP SITE command to set the file type for z/OS interactions. Use 'filetype=jes' for Job Entry Subsystem interactions. ```ftp ftp> quote site filetype=jes ``` -------------------------------- ### FTP Server to Server Transfer Example Source: https://commons.apache.org/proper/commons-net/jacoco/org.apache.commons.net.examples.ftp/ServerToServerFTP.java.html This example program demonstrates how to use the FTPClient class to arrange a server to server file transfer. It transfers a file from host1 to host2. Note that this might only work if host2 is the same as the host you run it on due to security restrictions on PORT commands. ```java /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.net.examples.ftp; import java.io.IOException; import java.net.InetAddress; import org.apache.commons.net.ProtocolCommandListener; import org.apache.commons.net.examples.PrintCommandListeners; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; /** * This is an example program demonstrating how to use the FTPClient class. This program arranges a server to server file transfer that transfers a file from * host1 to host2. Keep in mind, this program might only work if host2 is the same as the host you run it on (for security reasons, some ftp servers only allow * PORT commands to be issued with a host argument equal to the client host). *

* Usage: ftp */ public final class ServerToServerFTP { public static void main(final String[] args) { String server1; final String user1; final String password1; final String file1; String server2; final String user2; final String password2; final String file2; String[] parts; int port1 = 0; int port2 = 0; final FTPClient ftp1; final FTPClient ftp2; final ProtocolCommandListener listener; if (args.length < 8) { System.err.println("Usage: ftp "); System.exit(1); } server1 = args[0]; parts = server1.split(":"); if (parts.length == 2) { server1 = parts[0]; port1 = Integer.parseInt(parts[1]); } user1 = args[1]; password1 = args[2]; file1 = args[3]; server2 = args[4]; parts = server2.split(":"); if (parts.length == 2) { server2 = parts[0]; port2 = Integer.parseInt(parts[1]); } user2 = args[5]; password2 = args[6]; file2 = args[7]; listener = PrintCommandListeners.sysOutPrintCommandListener(); ftp1 = new FTPClient(); ftp1.addProtocolCommandListener(listener); ftp2 = new FTPClient(); ftp2.addProtocolCommandListener(listener); try { final int reply; if (port1 > 0) { ftp1.connect(server1, port1); } else { ftp1.connect(server1); } System.out.println("Connected to " + server1 + "."); reply = ftp1.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp1.disconnect(); System.err.println("FTP server1 refused connection."); System.exit(1); } } catch (final IOException e) { if (ftp1.isConnected()) { try { ftp1.disconnect(); } catch (final IOException f) { // do nothing } } System.err.println("Could not connect to server1."); e.printStackTrace(); System.exit(1); } } } ``` -------------------------------- ### FTP Download Files Example Source: https://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/parser/OS400FTPEntryParser.html Example of downloading members of all files of a library using the FTP get action. ```APIDOC ## POST /api/files/download ### Description Downloads members of all files of a library from an FTP server. ### Method POST ### Endpoint /api/files/download ### Parameters #### Request Body - **server** (string) - Required - The FTP server address. - **userid** (string) - Required - The FTP username. - **password** (string) - Required - The FTP password. - **binary** (boolean) - Optional - Set to true for binary transfer, false for text. - **verbose** (boolean) - Optional - Set to true for verbose output. - **remotedir** (string) - Required - The remote directory on the FTP server. - **systemTypeKey** (string) - Optional - The system type key (e.g., "OS/400"). - **fileset** (object) - Required - Defines the files to download. - **dir** (string) - Required - The local directory to save files to. - **casesensitive** (boolean) - Optional - Whether filenames are case-sensitive. - **include** (string) - Required - Ant-style include pattern for files (e.g., "**\run*.mbr"). ### Request Example ```json { "server": "${ftp.server}", "userid": "${ftp.user}", "password": "${ftp.password}", "binary": false, "verbose": true, "remotedir": "/QSYS.LIB/RPGUNIT.LIB", "systemTypeKey": "OS/400", "fileset": { "dir": "./i5-downloads-lib", "casesensitive": false, "include": "**\run*.mbr" } } ``` ### Response #### Success Response (200) - **message** (string) - A message indicating the status of the operation. - **files_retrieved** (integer) - The number of files successfully retrieved. #### Response Example ```json { "message": "6 files retrieved", "files_retrieved": 6 } ``` ``` -------------------------------- ### FTP Download Save File Example Source: https://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/parser/OS400FTPEntryParser.html Example of downloading a save file of a library using the FTP get action with binary transfer. ```APIDOC ## POST /api/files/download/savefile ### Description Downloads a save file of a library from an FTP server. ### Method POST ### Endpoint /api/files/download/savefile ### Parameters #### Request Body - **server** (string) - Required - The FTP server address. - **userid** (string) - Required - The FTP username. - **password** (string) - Required - The FTP password. - **binary** (boolean) - Required - Set to true for binary transfer. - **verbose** (boolean) - Optional - Set to true for verbose output. - **remotedir** (string) - Required - The remote directory on the FTP server. - **systemTypeKey** (string) - Optional - The system type key (e.g., "OS/400"). - **fileset** (object) - Required - Defines the save file to download. - **dir** (string) - Required - The local directory to save the file to. - **casesensitive** (boolean) - Optional - Whether filenames are case-sensitive. - **include** (string) - Required - The name of the save file to include (e.g., "RPGUNIT.SAVF"). ### Request Example ```json { "server": "${ftp.server}", "userid": "${ftp.user}", "password": "${ftp.password}", "binary": true, "verbose": true, "remotedir": "/QSYS.LIB/RPGUNIT.LIB", "systemTypeKey": "OS/400", "fileset": { "dir": "./i5-downloads-savf", "casesensitive": false, "include": "RPGUNIT.SAVF" } } ``` ### Response #### Success Response (200) - **message** (string) - A message indicating the status of the operation. - **files_retrieved** (integer) - The number of files successfully retrieved. #### Response Example ```json { "message": "1 files retrieved", "files_retrieved": 1 } ``` ``` -------------------------------- ### Run Commons Net Example via JAR Source: https://commons.apache.org/proper/commons-net/index.html Execute a sample application using the provided commons-net-examples JAR file. ```bash java -jar [path/]commons-net-examples-3.8.0.jar FTPClientExample [parameters] ``` -------------------------------- ### Connect and Configure FTPClient Source: https://commons.apache.org/proper/commons-net/apidocs/src-html/org/apache/commons/net/ftp/FTPClient.HostnameResolver.html Demonstrates initializing an FTPClient, applying configuration, and verifying the connection status with reply codes. ```java FTPClient ftp = new FTPClient(); FTPClientConfig config = new FTPClientConfig(); config.setXXX(YYY); // change required options // for example config.setServerTimeZoneId("Pacific/Pitcairn") ftp.configure(config ); boolean error = false; try { int reply; String server = "ftp.example.com"; ftp.connect(server); System.out.println("Connected to " + server + "."); System.out.print(ftp.getReplyString()); // After connection attempt, you should check the reply code to verify // success. reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); System.exit(1); } ... // transfer files ftp.logout(); } catch (IOException e) { error = true; e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { // do nothing } } System.exit(error ? 1 : 0); } ``` -------------------------------- ### Time Client Example Source: https://commons.apache.org/proper/commons-net/rat-report.html A client that uses the Time protocol (port 37) to get the current time from a server. This is a simpler protocol than NTP. ```Java /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.net.examples.ntp; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.SocketException; import org.apache.commons.net.examples.util.IOUtil; /** * Time client example. Connects to a Time server (port 37) and retrieves the current time. */ public class TimeClient { public static void main(String[] args) { if (args.length != 1) { System.err.println("Usage: timeclient "); System.exit(1); } final String hostname = args[0]; final int timePort = 37; // Standard Time protocol port Socket socket = null; InputStream inputStream = null; OutputStream outputStream = null; try { socket = new Socket(hostname, timePort); inputStream = socket.getInputStream(); outputStream = socket.getOutputStream(); // The Time protocol is simple: send a dummy byte (or nothing) and read the 4-byte timestamp. // Sending a byte is sometimes required by servers. outputStream.write(0); outputStream.flush(); byte[] timeBytes = new byte[4]; int bytesRead = inputStream.read(timeBytes); if (bytesRead == 4) { // Convert the 4-byte network byte order (big-endian) timestamp to a Java long. long time = ((long)timeBytes[0] << 24) | ((long)timeBytes[1] << 16) | ((long)timeBytes[2] << 8) | (long)timeBytes[3]; // The Time protocol timestamp is seconds since Jan 1, 1900 UTC. // Java's System.currentTimeMillis() is milliseconds since Jan 1, 1970 UTC. // We need to convert the epoch and units. long javaEpochOffsetMillis = 2208988800L * 1000L; // Seconds to milliseconds for Jan 1, 1970 long currentTimeMillis = (time * 1000L) - javaEpochOffsetMillis; System.out.println("Time from server: " + new java.util.Date(currentTimeMillis)); } else { System.err.println("Error: Did not receive 4 bytes for time."); } } catch (SocketException e) { System.err.println("Error: Could not connect to the Time server."); e.printStackTrace(); } catch (IOException e) { System.err.println("Error: An I/O error occurred."); e.printStackTrace(); } finally { IOUtil.closeConnection(socket); // Streams are closed automatically when the socket is closed. } } } ``` -------------------------------- ### Get Next Batch of Files Source: https://commons.apache.org/proper/commons-net/apidocs/src-html/org/apache/commons/net/ftp/FTPListParseEngine.html Retrieves a specified quantity of FTPFile objects starting from the current position of the internal iterator. The iterator is advanced after retrieval. ```APIDOC ## GET /files/next ### Description Retrieves a specified number of FTPFile objects starting from the current position of the internal iterator. The iterator is advanced by the number of elements returned. ### Method GET ### Endpoint /files/next ### Parameters #### Query Parameters - **quantityRequested** (int) - Required - The maximum number of entries to retrieve. ### Request Body None ### Response #### Success Response (200) - **FTPFile[]** - An array of FTPFile objects, potentially containing null members if parsing failed. #### Response Example ```json [ { "name": "file4.jpg", "size": 8192, "timestamp": "2023-10-27T10:30:00Z", "isDirectory": false }, { "name": "file5.png", "size": 16384, "timestamp": "2023-10-27T10:35:00Z", "isDirectory": false } ] ``` ``` -------------------------------- ### TelnetClient Implementation Example Source: https://commons.apache.org/proper/commons-net/examples/telnet/TelnetClientExample.java Demonstrates connecting to a remote Telnet server, registering option handlers, and managing input/output streams. ```java /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.net.examples.telnet; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.Charset; import java.time.Duration; import java.util.StringTokenizer; import org.apache.commons.net.telnet.EchoOptionHandler; import org.apache.commons.net.telnet.InvalidTelnetOptionException; import org.apache.commons.net.telnet.SimpleOptionHandler; import org.apache.commons.net.telnet.SuppressGAOptionHandler; import org.apache.commons.net.telnet.TelnetClient; import org.apache.commons.net.telnet.TelnetNotificationHandler; import org.apache.commons.net.telnet.TerminalTypeOptionHandler; /** * This is a simple example of use of TelnetClient. An external option handler (SimpleTelnetOptionHandler) is used. Initial configuration requested by * TelnetClient will be: WILL ECHO, WILL SUPPRESS-GA, DO SUPPRESS-GA. VT100 terminal type will be subnegotiated. *

* Also, use of the sendAYT(), getLocalOptionState(), getRemoteOptionState() is demonstrated. When connected, type AYT to send an AYT command to the server and * see the result. Type OPT to see a report of the state of the first 25 options. */ public class TelnetClientExample implements Runnable, TelnetNotificationHandler { private static TelnetClient tc; //NOPMD example code /** * Main for the TelnetClientExample. * * @param args input params * @throws Exception on error */ public static void main(final String[] args) throws Exception { FileOutputStream fout = null; if (args.length < 1) { System.err.println("Usage: TelnetClientExample []"); System.exit(1); } final String remoteip = args[0]; final int remoteport; if (args.length > 1) { remoteport = Integer.parseInt(args[1]); } else { remoteport = 23; } try { fout = new FileOutputStream("spy.log", true); } catch (final IOException e) { System.err.println("Exception while opening the spy file: " + e.getMessage()); } tc = new TelnetClient(); final TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false); final EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false); final SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true); try { tc.addOptionHandler(ttopt); tc.addOptionHandler(echoopt); tc.addOptionHandler(gaopt); } catch (final InvalidTelnetOptionException e) { System.err.println("Error registering option handlers: " + e.getMessage()); } while (true) { boolean end_loop = false; try { tc.connect(remoteip, remoteport); final Thread reader = new Thread(new TelnetClientExample()); tc.registerNotifHandler(new TelnetClientExample()); System.out.println("TelnetClientExample"); System.out.println("Type AYT to send an AYT Telnet command"); System.out.println("Type OPT to print a report of status of options (0-24)"); System.out.println("Type REGISTER to register a new SimpleOptionHandler"); System.out.println("Type UNREGISTER to unregister an OptionHandler"); System.out.println("Type SPY to register the spy (connect to port 3333 to spy)"); System.out.println("Type UNSPY to stop spying the connection"); System.out.println("Type ^[A-Z] to send the control character; use ^^ to send ^"); reader.start(); final OutputStream outstr = tc.getOutputStream(); final byte[] buff = new byte[1024]; int readCount = 0; do { try { readCount = System.in.read(buff); if (readCount > 0) { final Charset charset = Charset.defaultCharset(); ``` -------------------------------- ### Example Usage of FingerClient Source: https://commons.apache.org/proper/commons-net/jacoco/org.apache.commons.net.finger/FingerClient.java.html Demonstrates how to create a FingerClient, connect to a host, query user information, and disconnect. Ensure proper error handling for IOExceptions. ```java FingerClient finger; finger = new FingerClient(); try { finger.connect("foo.bar.com"); System.out.println(finger.query("foobar", false)); finger.disconnect(); } catch (IOException e) { System.err.println("Error I/O exception: " + e.getMessage()); return; } ``` -------------------------------- ### Unix RDate Protocol Example Source: https://commons.apache.org/proper/commons-net/rat-report.html Demonstrates connecting to a Unix RDate service to get the current date and time from the server. Requires an RDate service running. ```Java /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.net.examples.unix; import java.io.IOException; import java.io.InputStream; import java.net.SocketException; import org.apache.commons.net.examples.util.IOUtil; /** * Unix RDate protocol client example. Connects to an RDate service and prints the server's date and time. */ public class rdate { public static void main(String[] args) { if (args.length != 1) { System.err.println("Usage: rdate "); System.exit(1); } final String hostname = args[0]; final int rdatePort = 513; // RDate typically uses port 513 (often associated with rlogin/rsh) try (java.net.Socket socket = new java.net.Socket(hostname, rdatePort)) { InputStream inputStream = socket.getInputStream(); byte[] buffer = new byte[1024]; int bytesRead; System.out.println("Connected to RDate service at " + hostname + ". Receiving date and time..."); // Read the date and time string from the server StringBuilder dateTimeString = new StringBuilder(); while ((bytesRead = inputStream.read(buffer)) != -1) { dateTimeString.append(new String(buffer, 0, bytesRead)); } System.out.println("Server date and time: " + dateTimeString.toString().trim()); } catch (SocketException e) { System.err.println("Error: Could not connect to the RDate service."); e.printStackTrace(); } catch (IOException e) { System.err.println("Error: An I/O error occurred."); e.printStackTrace(); } } } ``` -------------------------------- ### Example: Handling File Transfer with storeFileStream Source: https://commons.apache.org/proper/commons-net/apidocs/src-html/org/apache/commons/net/ftp/FTPClient.html Demonstrates the correct procedure for using `storeFileStream` and `completePendingCommand` for robust file transfers. Includes error handling and stream management. ```java InputStream input; OutputStream output; input = new FileInputStream("foobaz.txt"); output = ftp.storeFileStream("foobar.txt") if (!FTPReply.isPositiveIntermediate(ftp.getReplyCode())) { input.close(); output.close(); ftp.logout(); ftp.disconnect(); System.err.println("File transfer failed."); System.exit(1); } Util.copyStream(input, output); input.close(); output.close(); // Must call completePendingCommand() to finish command. if (!ftp.completePendingCommand()) { ftp.logout(); ftp.disconnect(); System.err.println("File transfer failed."); System.exit(1); } ``` -------------------------------- ### Get Previous Batch of Files Source: https://commons.apache.org/proper/commons-net/apidocs/src-html/org/apache/commons/net/ftp/FTPListParseEngine.html Retrieves a specified quantity of FTPFile objects starting from the current position and moving backward. The iterator is moved back after retrieval. ```APIDOC ## GET /files/previous ### Description Retrieves a specified number of FTPFile objects starting from the current position and moving backward towards the beginning of the list. The internal iterator is moved back by the number of elements returned. ### Method GET ### Endpoint /files/previous ### Parameters #### Query Parameters - **quantityRequested** (int) - Required - The maximum number of entries to retrieve. ### Request Body None ### Response #### Success Response (200) - **FTPFile[]** - An array of FTPFile objects, potentially containing null members if parsing failed. #### Response Example ```json [ { "name": "file3.csv", "size": 4096, "timestamp": "2023-10-27T10:20:00Z", "isDirectory": false }, { "name": "file2.log", "size": 2048, "timestamp": "2023-10-27T10:10:00Z", "isDirectory": false } ] ``` ``` -------------------------------- ### Configure FTPClient for Server Systems Source: https://commons.apache.org/proper/commons-net/xref/org/apache/commons/net/ftp/FTPClientConfig.html Use FTPClientConfig to specify the server system type and time zone before connecting. These examples demonstrate setup for native Windows-NT and Unix-style configurations. ```java FTPClient f = FTPClient(); FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT); conf.setTimeZoneId("America/Denver"); f.configure(conf); f.connect(server); f.login(user, password); FTPFile[] files = listFiles(directory); ``` ```java FTPClient f = FTPClient(); FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX); conf.setTimeZoneId("America/Denver"); f.configure(conf); f.connect(server); f.login(user, password); FTPFile[] files = listFiles(directory); ``` -------------------------------- ### Initialize and Connect FTPClient Source: https://commons.apache.org/proper/commons-net/apidocs/src-html/org/apache/commons/net/ftp/FTPClient.NatServerResolverImpl.html Basic setup for connecting to an FTP server using the FTPClient class. ```java FTPClient f = new FTPClient(); f.connect(server); f.login(user, password); ``` -------------------------------- ### GET /getServerSystemKey Source: https://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClientConfig.html Gets the server system key property. ```APIDOC ## GET /getServerSystemKey ### Description Gets the serverSystemKey property, which specifies the general type of server to which the client connects. ### Method GET ### Response #### Success Response (200) - **serverSystemKey** (String) - The server system key. ``` -------------------------------- ### Main Method for Daytime Example Source: https://commons.apache.org/proper/commons-net/examples/unix/daytime.java Handles command-line arguments to execute either the TCP or UDP daytime client. Exits with an error message if usage is incorrect. ```java public static void main(final String[] args) { if (args.length == 1) { try { daytimeTCP(args[0]); } catch (final IOException e) { e.printStackTrace(); System.exit(1); } } else if (args.length == 2 && args[0].equals("-udp")) { try { daytimeUDP(args[1]); } catch (final IOException e) { e.printStackTrace(); System.exit(1); } } else { System.err.println("Usage: daytime [-udp] "); System.exit(1); } } ``` -------------------------------- ### NTP Client Example Source: https://commons.apache.org/proper/commons-net/rat-report.html Demonstrates how to query an NTP server for the current time. Requires access to an NTP server. ```Java /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.net.examples.ntp; import java.io.IOException; import java.net.DatagramSocket; import java.net.InetAddress; import org.apache.commons.net.ntp.NTPClient; import org.apache.commons.net.ntp.TimeInfo; /** * NTP client example. Connects to an NTP server and retrieves the current time. */ public class NTPClient { public static void main(String[] args) { if (args.length != 1) { System.err.println("Usage: ntpclient "); System.exit(1); } final String host = args[0]; NTPClient client = new NTPClient(); // Set the time server to use client.setDefaultServerAddress(host); try { // Use a DatagramSocket to send and receive UDP packets try (DatagramSocket socket = new DatagramSocket()) { client.open(socket); System.out.println("Requesting time from " + host + "..."); TimeInfo info = client.getTime(InetAddress.getByName(host)); info.computeDetails(); // compute offset and delay System.out.println("Time from server: " + info.getReturnTime().getTime()); System.out.println("Offset: " + info.getOffset() + " ms"); System.out.println("Delay: " + info.getDelay() + " ms"); } } catch (IOException e) { System.err.println("Error: Could not communicate with NTP server."); e.printStackTrace(); } } } ``` -------------------------------- ### Initialize and Configure TFTPClient Source: https://commons.apache.org/proper/commons-net/examples/ftp/TFTPExample.java Sets up the TFTPClient instance with optional verbose tracing and a default timeout duration. ```java // Get host and file arguments hostname = args[argc]; localFilename = args[argc + 1]; remoteFilename = args[argc + 2]; // Create our TFTP instance to handle the file transfer. if (verbose) { tftp = new TFTPClient() { @Override protected void trace(final String direction, final TFTPPacket packet) { System.out.println(direction + " " + packet); } }; } else { tftp = new TFTPClient(); } // We want to timeout if a response takes longer than 60 seconds tftp.setDefaultTimeout(Duration.ofSeconds(timeout)); // We haven't closed the local file yet. closed = false; // If we're receiving a file, receive, otherwise send. if (receiveFile) { closed = receive(transferMode, hostname, localFilename, remoteFilename, tftp); } else { // We're sending a file closed = send(transferMode, hostname, localFilename, remoteFilename, tftp); } System.out.println("Recd: " + tftp.getTotalBytesReceived() + " Sent: " + tftp.getTotalBytesSent()); if (!closed) { System.out.println("Failed"); System.exit(1); } System.out.println("OK"); } ``` -------------------------------- ### GET /api/default-timeout Source: https://commons.apache.org/proper/commons-net/jacoco/org.apache.commons.net/DatagramSocketClient.java.html Gets the default timeout in milliseconds for opening a socket. Deprecated in favor of getDefaultTimeoutDuration(). ```APIDOC ## GET /api/default-timeout ### Description Gets the default timeout in milliseconds that is used when opening a socket. This method is deprecated and users should use `getDefaultTimeoutDuration()` instead. ### Method GET ### Endpoint /api/default-timeout ### Response #### Success Response (200) - **timeout_ms** (int) - The default timeout in milliseconds. #### Response Example ```json { "timeout_ms": 5000 } ``` ``` -------------------------------- ### FTPClient Configuration Example Source: https://commons.apache.org/proper/commons-net/apidocs/src-html/org/apache/commons/net/ftp/FTPClientConfig.html Demonstrates how to configure an FTPClient with a specific system type and timezone for accurate file listing. ```APIDOC ## FTPClient Configuration Example ### Description This example shows how to configure an `FTPClient` to work with a Unix-style listing format on a Windows-NT server, specifying a particular timezone for accurate date parsing. ### Method N/A (Illustrative Code) ### Endpoint N/A (Illustrative Code) ### Parameters N/A (Illustrative Code) ### Request Example ```java FTPClient f = new FTPClient(); FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX); conf.setTimeZoneId("America/Denver"); f.configure(conf); f.connect(server); f.login(user, password); FTPFile[] files = f.listFiles(directory); ``` ### Response N/A (Illustrative Code) ``` -------------------------------- ### GET /api/default-timeout-duration Source: https://commons.apache.org/proper/commons-net/jacoco/org.apache.commons.net/DatagramSocketClient.java.html Gets the default timeout duration for opening a socket. Available since version 3.13.0. ```APIDOC ## GET /api/default-timeout-duration ### Description Gets the default timeout duration that is used when opening a socket. ### Method GET ### Endpoint /api/default-timeout-duration ### Response #### Success Response (200) - **timeout_duration** (Duration) - The default timeout duration. #### Response Example ```json { "timeout_duration": "5s" } ``` ``` -------------------------------- ### GET /api/local-port Source: https://commons.apache.org/proper/commons-net/jacoco/org.apache.commons.net/DatagramSocketClient.java.html Gets the local port number of the open socket. Throws NullPointerException if the client socket is not open. ```APIDOC ## GET /api/local-port ### Description Gets the port number of the open socket on the local host used for the connection. This method will throw a NullPointerException if the client socket is not currently open. ### Method GET ### Endpoint /api/local-port ### Response #### Success Response (200) - **local_port** (int) - The local port number. #### Response Example ```json { "local_port": 12345 } ``` ``` -------------------------------- ### listHelp() Source: https://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html Fetches the system help information from the FTP server and returns it as a single string. This provides general assistance information available on the server. ```APIDOC ## GET /help/system ### Description Fetches the system help information from the FTP server and returns the full string. ### Method GET ### Endpoint `/help/system` ### Response #### Success Response (200) - **String** - The system help string obtained from the server. Returns null if the information could not be obtained. #### Response Example ``` 214-The following commands are recognized. USER PASS QUIT 214 Help OK. ``` ### Throws - **FTPConnectionClosedException** - If the FTP server prematurely closes the connection. - **IOException** - If an I/O error occurs. ``` -------------------------------- ### Time Client Example Source: https://commons.apache.org/proper/commons-net/cpd.html Example usage of the TimeClient class for fetching time from a server via TCP or UDP. ```APIDOC ## GET /time ### Description Fetches the current time from a time server using the TimeClient utility. Supports both TCP and UDP protocols. ### Method GET ### Endpoint /time ### Query Parameters - **protocol** (string) - Optional - Specifies the protocol to use. Accepts 'tcp' (default) or 'udp'. - **hostname** (string) - Required - The hostname or IP address of the time server. ### Request Example `GET /time?protocol=tcp&hostname=pool.ntp.org` `GET /time?hostname=time.nist.gov` ### Response #### Success Response (200) - **currentTime** (string) - The current time obtained from the server in a human-readable format. #### Response Example { "currentTime": "2023-10-27T10:30:00Z" } ``` -------------------------------- ### execTLS Source: https://commons.apache.org/proper/commons-net/jacoco/org.apache.commons.net.smtp/SMTPSClient.java.html Executes the STARTTLS command to upgrade an existing insecure connection to a secure one. ```APIDOC ## execTLS ### Description Initiates the TLS command execution to secure the SMTP connection via STARTTLS. ### Method POST (Internal Command) ### Response - **boolean** - Returns true if the command and SSL negotiation succeeded, false otherwise. ### Errors - **IOException** - Thrown if an I/O error occurs during command transmission or SSL negotiation. ``` -------------------------------- ### Main Method for Chargen Example Source: https://commons.apache.org/proper/commons-net/examples/unix/chargen.java Parses command-line arguments to determine whether to run the TCP or UDP chargen client. Exits with an error message for invalid usage. ```Java public static void main(final String[] args) { if (args.length == 1) { try { chargenTCP(args[0]); } catch (final IOException e) { e.printStackTrace(); System.exit(1); } } else if (args.length == 2 && args[0].equals("-udp")) { try { chargenUDP(args[1]); } catch (final IOException e) { e.printStackTrace(); System.exit(1); } } else { System.err.println("Usage: chargen [-udp] "); System.exit(1); } } ``` -------------------------------- ### ANT FTP Task Examples Source: https://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/parser/OS400FTPEntryParser.html Examples of using the Apache ANT FTP task to interact with IBM i systems. ```xml Listing members of a file: ``` ```text [echo] Listing members of a file: [ftp] listing files [ftp] listing RUN.MBR [ftp] listing RUNNER.MBR [ftp] listing RUNNERBND.MBR [ftp] 3 files listed ``` ```xml Listing members of all files of a library: ``` ```text [echo] Listing members of all files of a library: [ftp] listing files [ftp] listing RPGUNIT1.FILE\RUN.MBR [ftp] listing RPGUNIT1.FILE\RUNRMT.MBR [ftp] listing RPGUNITT1.FILE\RUNT.MBR [ftp] listing RPGUNITY1.FILE\RUN.MBR [ftp] listing RPGUNITY1.FILE\RUNNER.MBR [ftp] listing RPGUNITY1.FILE\RUNNERBND.MBR [ftp] 6 files listed ``` ```xml Downloading members of a file: ``` ```text [echo] Downloading members of a file: [ftp] getting files [ftp] transferring RUN.MBR to C:\workspaces\rdp_080\workspace\ANT - FTP\i5-downloads-file\RUN.MBR [ftp] transferring RUNNER.MBR to C:\workspaces\rdp_080\workspace\ANT - FTP\i5-downloads-file\RUNNER.MBR [ftp] transferring RUNNERBND.MBR to C:\workspaces\rdp_080\workspace\ANT - FTP\i5-downloads-file\RUNNERBND.MBR [ftp] 3 files retrieved ``` -------------------------------- ### GET /systemName (Deprecated) Source: https://commons.apache.org/proper/commons-net/apidocs/src-html/org/apache/commons/net/ftp/FTPClient.HostnameResolver.html Gets the system name of the FTP server. This method is deprecated and users should use getSystemType() instead. ```APIDOC ## GET /systemName (Deprecated) ### Description Gets the system name of the FTP server. This method is deprecated and users should use getSystemType() instead. ### Method GET ### Endpoint /systemName ### Parameters None ### Request Example None ### Response #### Success Response (200) - **systemName** (string) - The system name returned by the server. #### Response Example ```json { "systemName": "UNIX Type: 214" } ``` ### Errors - **IOException**: If an I/O error occurs while sending a command to the server or receiving a reply. ``` -------------------------------- ### Querying New Newsgroups Source: https://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/nntp/NewGroupsOrNewsQuery.html Example of initializing a query and retrieving newsgroups with a specific distribution prefix. ```java query = new NewsGroupsOrNewsQuery(new GregorianCalendar(97, 11, 15), false); query.addDistribution("comp"); NewsgroupInfo[] newsgroups = client.listNewgroups(query); ```