lib: add FtpServer type

This commit is contained in:
2020-12-13 06:26:04 -06:00
parent 77cf4f5820
commit cf920c57c6
4 changed files with 71 additions and 2 deletions

View File

@@ -0,0 +1,45 @@
package net.monarchpass.piecannon.impl;
import net.monarchpass.piecannon.Server;
import com.google.common.io.ByteSource;
import com.google.common.io.ByteStreams;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import lombok.Data;
@Data
public class FtpServer implements Server {
private final String label;
private final String host;
private final int port;
private final String username;
private final String password;
private final String path;
private final URI uri;
public URI upload (String name, ByteSource source) {
name = name.replace(" ", "%20");
try {
final URI target = URI.create(uri.toString() + "/" + name);
final URL ftpUrl = new URL(String.format("ftp://%s:%s@%s:%d/%s/%s;type=i", username, password, host, port, path, name));
final URLConnection connection = ftpUrl.openConnection();
try (InputStream in = source.openStream()) {
try (OutputStream out = connection.getOutputStream()) {
ByteStreams.copy(in, out);
}
}
return target;
} catch (final IOException exception) {
throw new RuntimeException(exception);
}
}
}

View File

@@ -6,11 +6,19 @@ import java.util.function.Function;
import com.google.gson.JsonObject;
import net.monarchpass.piecannon.Server;
import net.monarchpass.piecannon.impl.FtpServer;
import net.monarchpass.piecannon.impl.SftpServer;
public class ServerFactory implements Function<JsonObject, Server> {
public Server apply (final JsonObject object) {
return makeSftpServer(object);
final String type = object.getAsJsonPrimitive("type").getAsString();
if (type.equalsIgnoreCase("ftp")) {
return makeFtpServer(object);
} else if (type.equalsIgnoreCase("sftp")) {
return makeSftpServer(object);
}
throw new IllegalArgumentException("Invalid server type: " + type);
}
private Server makeSftpServer (final JsonObject object) {
@@ -27,4 +35,19 @@ public class ServerFactory implements Function<JsonObject, Server> {
path, URI.create(url)
);
}
private Server makeFtpServer (final JsonObject object) {
final String host = object.getAsJsonPrimitive("host").getAsString();
final String label = object.has("label") ? object.getAsJsonPrimitive("label").getAsString() : host;
final int port = object.has("port") ? object.getAsJsonPrimitive("port").getAsInt() : 21;
final String username = object.getAsJsonPrimitive("username").getAsString();
final String password = object.getAsJsonPrimitive("password").getAsString();
final String path = object.getAsJsonPrimitive("path").getAsString();
final String url = object.getAsJsonPrimitive("url").getAsString();
return new FtpServer(
label, host, port, username, password,
path, URI.create(url)
);
}
}