Testing the existence of a File using Apache Camel - java

I want to test if a given file exists at a remote SFTP server using Apache Camel.
The method has to return true if exists, false if not and an Exception in case
the client cannot get connected (timeout, wrong username/password, etc).
In fact to test if I can get logged in to the server is not a major problem
to test if the given file exists. Just send a request to the SFTP server, download=false and noop=true
and this is pretty much what it has to be done. An empty file will be downloaded to my TMP directory
in case the file exists, no file will be downloaded. In case I cannot logged in to the server an own Exception is thrown
(CannotConnectException).
My point is that I cannot catch this exception at my client.
I am pretty sure I am doing something wrong, but I do not know what.
I was thinking as a work around to set some error value in returned file is case I cannot get connected, but
this looks like a "hack" to me. Is there any way to catch the thrown exception? If not, what is the best way to
get an Exception my client in case I cannot get connected?
My code is as follows:
public final class MyFtpClient {
private static final Logger LOG = LoggerFactory.getLogger(MyFtpClient.class);
// Client settings
static String localPath = File.separator + "tmp";
public enum Existence{
EXIST, NOT_EXIST, UNKNOWN
}
private MyFtpClient() {
}
private static Existence doesFileExistAtServer(Main main, String protocol, String user, String password,
String server, int port, String filePathAtServer, String filenameAtServer, String localPath)
{
boolean fileExist = false;
try {
main.addRouteBuilder(new MyFtpClientRouteBuilder(protocol, user, password, server, port, filePathAtServer,
filenameAtServer, localPath));
main.start();
Thread.sleep(5000);
main.stop();
String filePath = localPath + File.separator + filenameAtServer;
File f = new File(filePath);
fileExist = f.exists();
if (fileExist) {
f.delete(); // Just delete it.
return Existence.EXIST;
} else {
return Existence.NOT_EXIST;
}
// I CANNOT CATCH THIS EXCEPTION
} catch (Exception e) {
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Cannot Connect to the Sftp Server " + server);
LOG.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Cannot Connect to the Sftp Server " + server);
LOG.info(e.getMessage());
return Existence.UNKNOWN;
}
}
public static void main(String[] args) throws Exception {
String protocol = "sftp";
int port = 22;
String server;
String user;
String password;
String filePathAtServer;
String filenameAtServer;
boolean fileExist;
Main main = new Main();
server = "unknown.com";
user = "demo";
password = "password";
filePathAtServer = "/";
filenameAtServer = "readme.txt";
doesFileExistAtServer(main, protocol, user, password, server, port, filePathAtServer, filenameAtServer, localPath);
LOG.info("\nThe accesibility of the file 1 " + filenameAtServer + " at the server " + server + " is " + fileExist + "\n")
}
Whereas my RouteBuilder looks as follows:
public class MyFtpClientRouteBuilder extends RouteBuilder {
private static final Logger LOG =
LoggerFactory.getLogger(MyFtpClientRouteBuilder.class);
String protocol = "sftp";
int port = 22;
String server;
String user;
String password;
String filePathAtServer;
String filenameAtServer;
String localPath;
boolean fileExist;
public MyFtpClientRouteBuilder(String protocol, String user, String password, String server, int port,
String filePathAtServer, String filenameAtServer, String localPath) {
super();
this.protocol = protocol;
this.user = user;
this.password = password;
this.server = server;
this.port = port;
this.filePathAtServer = filePathAtServer;
this.filenameAtServer = filenameAtServer;
this.localPath = localPath;
}
private static String generateFromUri(String protocol, String user, String password, String server, int port,
String path, String filename) {
final String downloadFalse = "download=false"; // NO, DO NOT Download the file
final String fastExistsCheck = "fastExistsCheck=true";
final String doNothing = "noop=true"; // Just connect, but DO NOTHING
final String connectFail = "throwExceptionOnConnectFailed=true"; // Just in case a connection fails
final String maxReconnect = "maximumReconnectAttempts=0";
final String bridgeError = "consumer.bridgeErrorHandler=true";
return protocol + "://" + user + "#" + server + ":" + port + path + "?" + "fileName=" + filename + "&"
+ downloadFalse + "&"
+ "password=" + password
+ "&" + fastExistsCheck
+ "&" + connectFail
+ "&" + doNothing
+ "&" + maxReconnect
+ "&" + bridgeError;
}
private static String generateLocalUri(String path) {
final String protocol = "file";
final String allowNullBody = "allowNullBody=true";
final String doNothing = "noop=true";
final String fileExist = "fileExist=move";
final String moveExisting = "moveExisting=oldFile";
return protocol + ":" + path + "?" + allowNullBody + "&" + doNothing + "&" + fileExist + "&" + moveExisting;
}
#Override
public void configure() throws CannotConnectException {
final String fromSftpServer = generateFromUri(protocol, user, password, server, port, filePathAtServer, filenameAtServer);
LOG.info("From: " + fromSftpServer);
final String toLocal = generateLocalUri(localPath);
LOG.info("To: " + toLocal);
onException(GenericFileOperationFailedException.class, JSchException.class)
//.handled(true)
.throwException(new CannotConnectException("Cannot connect to the remote SFTP server " + server))
.log("Cannot connect to the remote SFTP server " + server)
.maximumRedeliveries(0)
.to(toLocal)
.continued(false) // Either handled(true) or continue(false) but NOT both together
.end();
from(fromSftpServer).to(toLocal);
}
}

Related

How to store result of exchange.getRequestURI().getQuery() in variable and use it to get authorization code

I'm trying to implement this stage of project - https://hyperskill.org/projects/62/stages/337/implement.
I need to store result of String code = exchange.getRequestURI().getQuery(); in a variable and use it in POST request.
POST(HttpRequest.BodyPublishers.ofString("client_id=" + CLIENT_ID + "&client_secret=" + CLIENT_SECRET+ "&grant_type=" + GRANT_TYPE + "&code=" + CODE + "&redirect_uri=" + REDIRECT_URI))
But I can't do that, because of it doesn't store in a vairable outside of server.createContext.
Maybe I'm trying to do wrong thing? Can anyone help me?
private static final String CLIENT_ID = "da072c60fcee469e8b0f4140aa4480d5";
private static final String CLIENT_SECRET = "8ada13093c704487b57c3a660448884e";
private static final String AUTHORIZE_ADDRESS = "https://accounts.spotify.com/authorize";
private static final String RESPONSE_TYPE = "code";
private static final String TOKEN_ADDRESS = "https://accounts.spotify.com/api/token";
private static final String GRANT_TYPE = "authorization_code";
private static final String CODE = "";
private static final String REDIRECT_URI = "http://localhost:8080";
private static final String ANSWER_DENIED_ACCESS = "Please, provide access for application.";
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
boolean successfulAccess = false;
while (sc.hasNext()) {
String input = sc.next();
switch (input) {
case "auth":
server();
request();
successfulAccess = true;
System.out.println("---SUCCESS---");
break;
}
}
}
private static void server() throws IOException {
HttpServer server = HttpServer.create();
server.bind(new InetSocketAddress(8080), 0);
server.start();
System.out.println("use this link to request the access code:");
System.out.println(AUTHORIZE_ADDRESS
+ "?client_id=" + CLIENT_ID
+ "&redirect_uri=" + REDIRECT_URI
+ "&response_type=" + RESPONSE_TYPE);
System.out.println("waiting for code...");
server.createContext("/",
exchange -> {
String code = exchange.getRequestURI().getQuery();
String result = "";
String answer = "";
if (code.contains("code")) {
result = "Got the code. Return back to your program.";
answer = "code received";
} else {
result = "Not found authorization code. Try again.";
answer = "code didn't received";
}
exchange.sendResponseHeaders(200, result.length());
exchange.getResponseBody().write(result.getBytes());
exchange.getResponseBody().close();
System.out.println(answer);
}
);
server.stop(10);
}
private static void request() throws IOException, InterruptedException {
System.out.println("making http request for access_token...");
HttpRequest request = HttpRequest.newBuilder()
.POST(HttpRequest.BodyPublishers.ofString(
"client_id=" + CLIENT_ID
+ "&client_secret=" + CLIENT_SECRET
+ "&grant_type=" + GRANT_TYPE
+ "&code=" + CODE
+ "&redirect_uri=" + REDIRECT_URI))
.header("Content-Type", "application/x-www-form-urlencoded")
.uri(URI.create(TOKEN_ADDRESS))
.build();
HttpClient client = HttpClient.newBuilder().build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("response:");
System.out.println(response.body());
}
}```
I need while cycle with Thread.sleep, than you can normally store code in variable. Like this:
exchange -> {
String code = exchange.getRequestURI().getQuery();
String result = "";
String answer = "";
if (code != null && code.contains("code")) {
CODE = code.substring(5);
result = "Got the code. Return back to your program.";
answer = "code received";
} else {
result = "Not found authorization code. Try again.";
answer = "code not received";
}
exchange.sendResponseHeaders(200, result.length());
exchange.getResponseBody().write(result.getBytes());
exchange.getResponseBody().close();
System.out.println(answer);
}
);
while (CODE.equals("")) {
Thread.sleep(10);
}
server.stop(10);```

How do I make a WebDav call using resttemplate?

How do I make a WebDav call using resttemplate if I am trying to get file from a webdav server.
I used to do that using HttpClient like this:
public byte[] getFileAsBytes( String location ) throws FileNotFoundException, IOException {
GetMethod method = new GetMethod( baseUrl + "/" + location );
client.executeMethod( method );
if ( method.getStatusCode() == HttpStatus.SC_NOT_FOUND ) {
throw new FileNotFoundException( "Got error " + method.getStatusCode() + " : " + method.getStatusText()
+ " retrieving file from webdav server at path " + location );
} else if ( method.getStatusCode() != HttpStatus.SC_OK ) {
throw new IOException( "Got error " + method.getStatusCode() + " : " + method.getStatusText()
+ " retrieving file from webdav server at path " + location );
}
return method.getResponseBody();
}
I was able to hit the WebDav server using restTemplate as the following:
/**
* This method copies the file from webdav to local system
*
* #param documentMetadata
* #return
*/
#Override
public Document downloadFile( DocumentMetadata documentMetadata ) {
Document document = new Document();
String fileUrl = baseUrl + documentMetadata.getFilepath();
ResponseEntity<byte[]> result = restTemplate.exchange(fileUrl, HttpMethod.GET, new HttpEntity<>( createHeaders( username, password )), byte[].class );
return document;
}
private Void prepareDocument( ClientHttpResponse response, Document document, DocumentMetadata meta ) throws IOException {
document.setName( meta.getFilename() );
document.setFilePath( meta.getFilepath() );
document.setFile( IOUtils.toByteArray( response.getBody() ) );
return null;
}
public static HttpHeaders createHeaders( final String userName, final String password ) {
log.debug( "SlateUtil.createHeaders" );
return new HttpHeaders(){{
String auth = userName + ":" + password;
byte[] encodedAuth = Base64.encodeBase64(
auth.getBytes( Charset.forName( "US-ASCII" )));
String authHeader = "Basic " + new String( encodedAuth );
set( "Authorization", authHeader );
}};
}
For other people reference if they ever get this question:
here is how my models look like.
public class Document {
private String name;
private byte[] file;
private String filePath;
private String contentType;
// getters and setters
}
public class DocumentMetadata {
private String id;
private String filename;
private String filepath;
private String extension;
private String createdBy;
private Date createDate;
private String size;
private String documentType;
private String displayName;
// getters and setters
}

Upload File in Sharepoint online

I want to generate a file in sharepoint online I use this code but I still have an exception java.net.ConnectException: Connection timed out: connect
Any ideas please??
public static CopySoap getPort(String username, String password) {
Copy service = new Copy();
CopySoap port = service.getCopySoap();
BindingProvider bp = (BindingProvider) port;
bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, username);
bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, password);
bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
"https://mysite/sites/_vti_bin/Copy.asmx");
return port;
}
public static void createDocument(CopySoap port) throws Exception {
String url = "https://mysite/sites/Documents partages/test.txt";
String sourceUrl = "C:\\TEMP\\test.txt";
File file=new File(sourceUrl);
DestinationUrlCollection urls = new DestinationUrlCollection();
urls.getString().add(url);
byte[] content = readAll(file);
FieldInformation titleInfo = new FieldInformation ();
titleInfo.setDisplayName("Title");
titleInfo.setType(FieldType.TEXT);
titleInfo.setValue("Test Doc");
FieldInformationCollection infos = new FieldInformationCollection ();
infos.getFieldInformation().add(titleInfo);
CopyResultCollection results = new CopyResultCollection ();
Holder<CopyResultCollection> resultHolder = new Holder<CopyResultCollection>(results);
Holder<Long> longHolder = new Holder<Long>(new Long(-1));
port.copyIntoItems(sourceUrl, urls, infos, content, longHolder, resultHolder);
logger.debug("Long holder: " + longHolder.value);
//do something meaningful here
for (CopyResult copyResult : resultHolder.value.getCopyResult()) {
logger.debug("Destination: " + copyResult.getDestinationUrl());
logger.debug("Error Message: " + copyResult.getErrorMessage());
logger.debug("Error Code: " + copyResult.getErrorCode());
if(copyResult.getErrorCode() != CopyErrorCode.SUCCESS)
throw new Exception("Upload failed for: " + copyResult.getDestinationUrl() + " Message: "
+ copyResult.getErrorMessage() + " Code: " + copyResult.getErrorCode() );
}

Vertx Websockets starts encoding-decoding in loop after connecting second client

I have simple Vertx-based websocket chatting app. It consists of two parts MsgServerVerticle and MsgClientVerticle (source code below). So, if I am instantiating one server and only one client it looks like working normally. After second client connects, server starts trying to announce it to other clients. And things gonna weird. Log says that netty backed are encoding-decoding websocket frames continuously in loop. There is no difference what type of frames I am using, binary or text, issues are the same.
log screenshot here
What's wrong?
MsgClientVerticle Source code:
private Logger L;
private String eBusTag;
private String backwardTag;
private String targetHost;
private int port;
private String id;
private String path;
private EventBus eBus;
private HttpClient client;
public MsgClientVerticle(String eBusTag, String targetHost, int port, String path, String id, String backwardTag) {
this.eBusTag = eBusTag;
this.targetHost = targetHost;
this.path = path;
this.port = port;
this.id = id;
this.backwardTag = backwardTag;
L = LoggerFactory.getLogger(eBusTag);
}
#Override
public void start(Future<Void> startFuture) throws Exception {
L.info("Initializing client connection to " + targetHost + ":" + port + path);
eBus = vertx.eventBus();
try {
client = vertx.createHttpClient();
client.websocket(port, targetHost, path, webSock -> {
L.info("Connected to " + targetHost + ":" + port + "/" + path);
eBus.publish(backwardTag, Utils.msg("Connected"));
webSock.binaryMessageHandler(buf -> {
eBus.publish(backwardTag, Utils.bufToJson(buf));
});
eBus.consumer(eBusTag).handler(msg -> {
JsonObject message = (JsonObject) msg.body();
webSock.writeBinaryMessage(Utils.jsonToBuf(message));
});
});
} catch (NullPointerException e) {
L.error("Null Pointer: " + e.getLocalizedMessage());
e.printStackTrace();
}
startFuture.complete();
}
#Override
public void stop(Future<Void> stopFuture) throws Exception {
L.info("Connection to " + targetHost + ":" + port + "/" + path + " closed");
client.close();
stopFuture.complete();
}
And MsgServerVerticle source:
private Logger L;
private String path;
private int port;
private String eBusTag;
private String backwardTag;
private HttpServer server;
private EventBus eBus;
private Set<ServerWebSocket> conns;
public MsgServerVerticle(int port, String eBusTag, String backwardTag) {
this.port = port;
this.eBusTag = eBusTag;
this.backwardTag = backwardTag;
conns = new ConcurrentSet<>();
path = eBusTag;
L = LoggerFactory.getLogger(eBusTag);
}
#Override
public void start(Future<Void> startFuture) throws Exception {
eBus = vertx.eventBus();
L.info("Initializing server instance at port " + port);
server = vertx.createHttpServer();
server.websocketHandler(webSock -> {
if (!webSock.path().equals(path)) {
webSock.reject();
} else {
conns.add(webSock);
conns.forEach(sock -> {
if (sock != webSock) {
sock.writeBinaryMessage(Utils.jsonToBuf(Utils.msg("SERVER: new client " + webSock.remoteAddress().toString())));
}
});
eBus.publish(backwardTag, Utils.msg("SERVER: new client " + webSock.remoteAddress().toString()));
webSock.binaryMessageHandler(buf -> {
JsonObject msg = Utils.bufToJson(buf);
conns.forEach(sock -> {
if (sock != webSock) {
sock.writeBinaryMessage(buf);
}
});
eBus.publish(backwardTag, msg);
});
}
});
server.listen(port);
startFuture.complete();
}
#Override
public void stop(Future<Void> stopFuture) throws Exception {
conns.forEach(sock -> {
sock.writeFinalTextFrame("Server is shutting down...");
});
server.close();
stopFuture.complete();
}
I wasn't able to reproduce your original problem. But I had to make a few changes in the first place to test it.
One change is in initialization of your server:
this.path = "/" + eBusTag;
Otherwise this check will always fail:
if (!webSock.path().equals(this.path)) {
Since websock.path() will always start with /, hence /anything=/=anything
Second, please take a look how I initialized the clients, and check if you do the same:
final Vertx vertx = Vertx.vertx();
vertx.deployVerticle(new MsgServerVerticle(8080,
"ebus",
"back"), new DeploymentOptions().setWorker(true), (r) -> {
vertx.deployVerticle(new MsgClientVerticle("ebus",
"127.0.0.1",
8080,
"/ebus",
"a",
"back"), new DeploymentOptions().setWorker(true), (r2) -> {
vertx.deployVerticle(new MsgClientVerticle("ebus",
"127.0.0.1",
8080,
"/ebus",
"b",
"back"), new DeploymentOptions().setWorker(true), (r3) -> {
System.out.println("Done");
});
});
});
And third, as far as I could understand, your Utils class is something you implemented. My implementation looks as follows:
public class Utils {
public static Buffer jsonToBuf(final JsonObject message) {
return message.toBuffer();
}
public static JsonObject bufToJson(final Buffer buf) {
return buf.toJsonObject();
}
public static JsonObject msg(final String msg) {
return new JsonObject("{\"value\":\"" + msg + "\"}");
}
}
Hope that helps pinpoint your problem.

How to use apache vfs2 for sftp with public-private-key and without password

Currently I am using apache vfs2 to download files from a sftp. For authentication I use user-name and password.
Is there a way to use vfs2 only with public-private-keys and without a password?
I think I have use this function,but how? Set it only to "yes"?
SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(options, "no");
This is my current code (snippet):
private boolean downloadFile(){
StandardFileSystemManager sysManager = new StandardFileSystemManager();
//download der Datei
try {
sysManager.init();
FileObject localFile = sysManager.resolveFile(localFilePath);
FileObject remoteFile = sysManager.resolveFile(createConnectionString(host, user, password, fileName, port),createDefaultOptions());
//Selectors.SELECT_FILES --> A FileSelector that selects only the base file/folder.
localFile.copyFrom(remoteFile, Selectors.SELECT_FILES);
} catch (Exception e) {
logger.error("Downloading file failed: " + e.toString());
return false;
}finally{
sysManager.close();
}
return true;
}
and
private FileSystemOptions createDefaultOptions() throws FileSystemException{
//create options for sftp
FileSystemOptions options = new FileSystemOptions();
//ssh key
SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(options, "no");
//set root directory to user home
SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(options, true);
//timeout
SftpFileSystemConfigBuilder.getInstance().setTimeout(options, timeout);
return options;
}
Taking your code and wrapping it into a runnable example. Notice the IdentityInfo implementation. This can work with a key-with-passphrase by changing the obvious lines.
$ javac -cp 'jsch-0.1.51.jar;commons-vfs2-2.0.jar' SftpGet.java
$ java -cp 'jsch-0.1.51.jar;commons-vfs2-2.0.jar;commons-logging-1.1.1.jar;.' SftpGet
with
import java.io.File;
import com.jcraft.jsch.UserInfo;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.Selectors;
import org.apache.commons.vfs2.impl.StandardFileSystemManager;
import org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;
import org.apache.commons.vfs2.provider.sftp.IdentityInfo;
public class SftpGet {
public static void main(String[] args) {
downloadFile();
}
private static boolean downloadFile(){
String host = "HOSTNAMEHERE";
String user = "USERNAMEHERE";
String password = "";
String fileName = "/lines.txt";
String localFilePath = "c:/cygwin64/home/woddle/wrote_lines.txt";
// without passphrase
String keyPath = "c:/cygwin64/home/woddle/.ssh/id_dsa_nopass";
String passphrase = null;
// with passphrase
// String keyPath = "c:/cygwin64/home/woddle/.ssh/id_dsa_withpass";
// String passphrase = "super-secrets";
StandardFileSystemManager sysManager = new StandardFileSystemManager();
//download der Datei
try {
sysManager.init();
FileObject localFile = sysManager.resolveFile(localFilePath);
FileObject remoteFile = sysManager.resolveFile(createConnectionString(host, user, password, keyPath, passphrase, fileName), createDefaultOptions(keyPath, passphrase));
//Selectors.SELECT_FILES --> A FileSelector that selects only the base file/folder.
localFile.copyFrom(remoteFile, Selectors.SELECT_FILES);
} catch (Exception e) {
System.out.println("Downloading file failed: " + e.toString());
return false;
}finally{
sysManager.close();
}
return true;
}
public static String createConnectionString(String hostName, String username, String password, String keyPath, String passphrase, String remoteFilePath) {
if (keyPath != null) {
return "sftp://" + username + "#" + hostName + "/" + remoteFilePath;
} else {
return "sftp://" + username + ":" + password + "#" + hostName + "/" + remoteFilePath;
}
}
private static FileSystemOptions createDefaultOptions(final String keyPath, final String passphrase) throws FileSystemException{
//create options for sftp
FileSystemOptions options = new FileSystemOptions();
//ssh key
SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(options, "no");
//set root directory to user home
SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(options, true);
//timeout
SftpFileSystemConfigBuilder.getInstance().setTimeout(options, 10000);
if (keyPath != null) {
IdentityInfo identityInfo = null;
if(passPhrase!=null){
identityInfo = new IdentityInfo(new File(keyPath), passPhrase.getBytes());
}else{
identityInfo = new IdentityInfo(new File(keyPath));
}
SftpFileSystemConfigBuilder.getInstance().setIdentityInfo(options, identityInfo);
}
return options;
}
}
We should not use below method for creating the connection string. This may expose the password.
public static String createConnectionString(String hostName, String username, String password, String keyPath, String passphrase, String remoteFilePath) {
if (keyPath != null) {
return "sftp://" + username + "#" + hostName + "/" + remoteFilePath;
} else {
return "sftp://" + username + ":" + password + "#" + hostName + "/" + remoteFilePath;
}
}
As per the documentation available on the Apache website, we should use
StaticUserAuthenticator auth = new StaticUserAuthenticator("domain", "username", "password");
Link: https://commons.apache.org/proper/commons-vfs/api.html
Also, if we are using public key or private key based authentication, then we should use setIdentityInfo(FileSystemOptions, IdentityInfo...) instead of setIdentities(FileSystemOptions opts, File... identityFiles).
Reference: https://commons.apache.org/proper/commons-vfs/commons-vfs2/apidocs/org/apache/commons/vfs2/provider/sftp/SftpFileSystemConfigBuilder.html
FileSystemOptions opts = new FileSystemOptions();
SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");
SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, false);
String openSSHPrivateKey = "C:\\Users\\<filepath>\\id_rsa.key";
IdentityInfo myIdentityInfo = new IdentityInfo(new File(openSSHPrivateKey));
SftpFileSystemConfigBuilder.getInstance(). setIdentityInfo(opts, myIdentityInfo);

Categories