Refactor client instance usage.

This commit is contained in:
David Kocher
2026-01-07 15:29:45 +01:00
parent 67c3f9b637
commit 0f455eb32f
14 changed files with 27 additions and 33 deletions
@@ -16,6 +16,7 @@ package ch.cyberduck.core.brick;
*/
import ch.cyberduck.core.ConnectionTimeoutFactory;
import ch.cyberduck.core.Host;
import ch.cyberduck.core.HostUrlProvider;
import ch.cyberduck.core.PreferencesUseragentProvider;
import ch.cyberduck.core.brick.io.swagger.client.ApiClient;
@@ -24,6 +25,7 @@ import ch.cyberduck.core.brick.io.swagger.client.JSON;
import ch.cyberduck.core.brick.io.swagger.client.Pair;
import ch.cyberduck.core.jersey.HttpComponentsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
@@ -43,18 +45,18 @@ public class BrickApiClient extends ApiClient {
Logger.getLogger("org.glassfish.jersey.client.ClientExecutorProvidersConfigurator").setLevel(java.util.logging.Level.SEVERE);
}
private final BrickSession session;
private final Host host;
public BrickApiClient(final BrickSession session) {
this.session = session;
public BrickApiClient(final Host host, final CloseableHttpClient client) {
this.host = host;
this.setHttpClient(ClientBuilder.newClient(new ClientConfig()
.register(new InputStreamProvider())
.register(MultiPartFeature.class)
.register(new JSON())
.register(JacksonFeature.class)
.connectorProvider(new HttpComponentsProvider(session.getClient())))
.connectorProvider(new HttpComponentsProvider(client)))
);
final int timeout = ConnectionTimeoutFactory.get(session.getHost()).getTimeout() * 1000;
final int timeout = ConnectionTimeoutFactory.get(host).getTimeout() * 1000;
this.setConnectTimeout(timeout);
this.setReadTimeout(timeout);
this.setUserAgent(new PreferencesUseragentProvider().get());
@@ -70,7 +72,7 @@ public class BrickApiClient extends ApiClient {
@Override
public <T> T invokeAPI(final String path, final String method, final List<Pair> queryParams, final Object body, final Map<String, String> headerParams, final Map<String, Object> formParams, final String accept, final String contentType, final String[] authNames, final GenericType<T> returnType) throws ApiException {
try {
this.setBasePath(String.format("%s/api/rest/v1", new HostUrlProvider().withUsername(false).get(session.getHost())));
this.setBasePath(String.format("%s/api/rest/v1", new HostUrlProvider().withUsername(false).get(host)));
return super.invokeAPI(path, method, queryParams, body, headerParams, formParams, accept, contentType, authNames, returnType);
}
catch(ProcessingException e) {
@@ -42,7 +42,7 @@ public class BrickAttributesFinderFeature implements AttributesFinder, Attribute
@Override
public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException {
try {
final FileEntity entity = new FilesApi(new BrickApiClient(session))
final FileEntity entity = new FilesApi(session.getClient())
.download(StringUtils.removeStart(file.getAbsolute(), String.valueOf(Path.DELIMITER)),
"stat", null, false, false);
switch(entity.getType()) {
@@ -18,7 +18,6 @@ package ch.cyberduck.core.brick;
import ch.cyberduck.core.ConnectionCallback;
import ch.cyberduck.core.DefaultPathAttributes;
import ch.cyberduck.core.Path;
import ch.cyberduck.core.PathAttributes;
import ch.cyberduck.core.brick.io.swagger.client.ApiException;
import ch.cyberduck.core.brick.io.swagger.client.api.FileActionsApi;
import ch.cyberduck.core.brick.io.swagger.client.model.CopyPathBody;
@@ -51,7 +50,7 @@ public class BrickCopyFeature extends BrickFileMigrationFeature implements Copy
@Override
public Path copy(final Path file, final Path target, final TransferStatus status, final ConnectionCallback callback, final StreamListener listener) throws BackgroundException {
try {
final BrickApiClient client = new BrickApiClient(session);
final BrickApiClient client = session.getClient();
if(status.isExists()) {
log.warn("Delete file {} to be replaced with {}", target, file);
new BrickDeleteFeature(session).delete(Collections.singletonList(target), callback, new Delete.DisabledCallback());
@@ -41,7 +41,7 @@ public class BrickDeleteFeature implements Delete {
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException {
for(Path f : files.keySet()) {
try {
new FilesApi(new BrickApiClient(session)).deleteFilesPath(
new FilesApi(session.getClient()).deleteFilesPath(
StringUtils.removeStart(f.getAbsolute(), String.valueOf(Path.DELIMITER)), f.isDirectory());
}
catch(ApiException e) {
@@ -38,7 +38,7 @@ public class BrickDirectoryFeature implements Directory<FileEntity> {
public Path mkdir(final Write<FileEntity> writer, final Path folder, final TransferStatus status) throws BackgroundException {
try {
return new Path(folder).withAttributes(
new BrickAttributesFinderFeature(session).toAttributes(new FoldersApi(new BrickApiClient(session))
new BrickAttributesFinderFeature(session).toAttributes(new FoldersApi(session.getClient())
.postFoldersPath(StringUtils.removeStart(folder.getAbsolute(), String.valueOf(Path.DELIMITER)))));
}
catch(ApiException e) {
@@ -51,7 +51,7 @@ public class BrickListService implements ListService {
final AttributedList<Path> children = new AttributedList<>();
String cursor = null;
List<FileEntity> response;
final BrickApiClient client = new BrickApiClient(session);
final BrickApiClient client = session.getClient();
do {
response = new FoldersApi(client).foldersListForPath(StringUtils.removeStart(directory.getAbsolute(), String.valueOf(Path.DELIMITER)),
cursor, chunksize, null, null, null, null, null, null);
@@ -35,7 +35,7 @@ public class BrickLockFeature implements Lock<String> {
@Override
public String lock(final Path file) throws BackgroundException {
try {
return new LocksApi(new BrickApiClient(session))
return new LocksApi(session.getClient())
.postLocksPath(StringUtils.removeStart(file.getAbsolute(), String.valueOf(Path.DELIMITER)),
new LocksPathBody().exclusive(true).allowAccessByAnyUser(true)).getToken();
}
@@ -47,7 +47,7 @@ public class BrickLockFeature implements Lock<String> {
@Override
public void unlock(final Path file, final String token) throws BackgroundException {
try {
new LocksApi(new BrickApiClient(session))
new LocksApi(session.getClient())
.deleteLocksPath(StringUtils.removeStart(file.getAbsolute(), String.valueOf(Path.DELIMITER)), token);
}
catch(ApiException e) {
@@ -19,7 +19,6 @@ import ch.cyberduck.core.CaseInsensitivePathPredicate;
import ch.cyberduck.core.ConnectionCallback;
import ch.cyberduck.core.DefaultPathAttributes;
import ch.cyberduck.core.Path;
import ch.cyberduck.core.PathAttributes;
import ch.cyberduck.core.brick.io.swagger.client.ApiException;
import ch.cyberduck.core.brick.io.swagger.client.api.FileActionsApi;
import ch.cyberduck.core.brick.io.swagger.client.model.FileActionEntity;
@@ -48,7 +47,7 @@ public class BrickMoveFeature extends BrickFileMigrationFeature implements Move
@Override
public Path move(final Path file, final Path target, final TransferStatus status, final Delete.Callback delete, final ConnectionCallback callback) throws BackgroundException {
try {
final BrickApiClient client = new BrickApiClient(session);
final BrickApiClient client = session.getClient();
if(status.isExists()) {
if(!new CaseInsensitivePathPredicate(file).test(target)) {
log.warn("Delete file {} to be replaced with {}", target, file);
@@ -117,7 +117,7 @@ public class BrickMultipartWriteFeature implements MultipartWrite<FileEntity> {
public TransferStatus call() throws BackgroundException {
final List<FileUploadPartEntity> uploadPartEntities;
try {
uploadPartEntities = new FileActionsApi(new BrickApiClient(session))
uploadPartEntities = new FileActionsApi(session.getClient())
.beginUpload(StringUtils.removeStart(file.getAbsolute(), String.valueOf(Path.DELIMITER)), new BeginUploadPathBody().ref(ref).part(partNumber));
}
catch(ApiException e) {
@@ -177,7 +177,7 @@ public class BrickMultipartWriteFeature implements MultipartWrite<FileEntity> {
}
else {
try {
response.set(new FilesApi(new BrickApiClient(session)).postFilesPath(new FilesPathBody()
response.set(new FilesApi(session.getClient()).postFilesPath(new FilesPathBody()
.providedMtime(null != overall.getModified() ? new DateTime(overall.getModified()) : null)
.etagsEtag(checksums.stream().map(s -> s.getChecksum().hash).collect(Collectors.toList()))
.etagsPart(checksums.stream().map(TransferStatus::getPart).collect(Collectors.toList()))
@@ -54,7 +54,7 @@ public class BrickReadFeature implements Read {
@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
final FileEntity entity = new FilesApi(new BrickApiClient(session))
final FileEntity entity = new FilesApi(session.getClient())
.download(StringUtils.removeStart(file.getAbsolute(), String.valueOf(Path.DELIMITER)),
null, null, null, null);
final HttpUriRequest request = new HttpGet(entity.getDownloadUri());
@@ -17,7 +17,6 @@ package ch.cyberduck.core.brick;
import ch.cyberduck.core.ConnectionCallback;
import ch.cyberduck.core.Credentials;
import ch.cyberduck.core.DefaultIOExceptionMappingService;
import ch.cyberduck.core.DisabledConnectionCallback;
import ch.cyberduck.core.Host;
import ch.cyberduck.core.HostKeyCallback;
@@ -58,17 +57,15 @@ import ch.cyberduck.core.ssl.X509TrustManager;
import ch.cyberduck.core.threading.CancelCallback;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.CountDownLatch;
public class BrickSession extends HttpSession<CloseableHttpClient> {
public class BrickSession extends HttpSession<BrickApiClient> {
private static final Logger log = LogManager.getLogger(BrickSession.class);
private BrickUnauthorizedRetryStrategy retryHandler;
@@ -78,13 +75,13 @@ public class BrickSession extends HttpSession<CloseableHttpClient> {
}
@Override
protected CloseableHttpClient connect(final ProxyFinder proxy, final HostKeyCallback key, final LoginCallback prompt, final CancelCallback cancel) {
protected BrickApiClient connect(final ProxyFinder proxy, final HostKeyCallback key, final LoginCallback prompt, final CancelCallback cancel) {
final HttpClientBuilder configuration = builder.build(proxy, this, prompt);
configuration.setServiceUnavailableRetryStrategy(new CustomServiceUnavailableRetryStrategy(host,
retryHandler = new BrickUnauthorizedRetryStrategy(this, prompt, cancel)));
configuration.addInterceptorLast(retryHandler);
configuration.addInterceptorLast(new BrickPreferencesRequestInterceptor());
return configuration.build();
return new BrickApiClient(host, configuration.build());
}
@Override
@@ -114,12 +111,9 @@ public class BrickSession extends HttpSession<CloseableHttpClient> {
public void disconnect() throws BackgroundException {
try {
if(client != null) {
client.close();
client.getHttpClient().close();
}
}
catch(IOException e) {
throw new DefaultIOExceptionMappingService().map(e);
}
finally {
super.disconnect();
}
@@ -55,7 +55,7 @@ public class BrickShareFeature implements Share {
LocaleFactory.localizedString("Passphrase", "Cryptomator"),
MessageFormat.format(LocaleFactory.localizedString("Create a passphrase required to access {0}", "Credentials"), file.getName()),
new LoginOptions().anonymous(true).keychain(false).icon(session.getHost().getProtocol().disk()));
return new DescriptiveUrl(new BundlesApi(new BrickApiClient(session))
return new DescriptiveUrl(new BundlesApi(session.getClient())
.postBundles(new BundlesBody().password(password.isPasswordAuthentication() ? password.getPassword() : null).paths(Collections.singletonList(
StringUtils.removeStart(file.getAbsolute(), String.valueOf(Path.DELIMITER))))).getUrl(), DescriptiveUrl.Type.signed);
}
@@ -39,7 +39,7 @@ public class BrickTimestampFeature implements Timestamp {
public void setTimestamp(final Path file, final TransferStatus status) throws BackgroundException {
try {
if(null != status.getModified()) {
final FileEntity response = new FilesApi(new BrickApiClient(session))
final FileEntity response = new FilesApi(session.getClient())
.patchFilesPath(StringUtils.removeStart(file.getAbsolute(), String.valueOf(Path.DELIMITER)),
new FilesPathBody().providedMtime(status.getModified() != null ? new DateTime(status.getModified()) : null));
status.setResponse(new BrickAttributesFinderFeature(session).toAttributes(response));
@@ -122,7 +122,7 @@ public class BrickUploadFeature extends HttpUploadFeature<FileEntity, MessageDig
protected FileUploadPartEntity continueUpload(final Path file, final String ref, final int partNumber) throws BackgroundException {
final List<FileUploadPartEntity> uploadPartEntities;
try {
uploadPartEntities = new FileActionsApi(new BrickApiClient(session))
uploadPartEntities = new FileActionsApi(session.getClient())
.beginUpload(StringUtils.removeStart(file.getAbsolute(), String.valueOf(Path.DELIMITER)), new BeginUploadPathBody().ref(ref).part(partNumber));
}
catch(ApiException e) {
@@ -137,7 +137,7 @@ public class BrickUploadFeature extends HttpUploadFeature<FileEntity, MessageDig
protected FileEntity completeUpload(final Path file, final String ref, final TransferStatus status, final List<TransferStatus> checksums) throws BackgroundException {
try {
return new FilesApi(new BrickApiClient(session)).postFilesPath(new FilesPathBody()
return new FilesApi(session.getClient()).postFilesPath(new FilesPathBody()
.etagsEtag(checksums.stream().map(s -> s.getChecksum().hash).collect(Collectors.toList()))
.etagsPart(checksums.stream().map(TransferStatus::getPart).collect(Collectors.toList()))
.providedMtime(null != status.getModified() ? new DateTime(status.getModified()) : null)