use of ch.cyberduck.core.http.HttpExceptionMappingService in project cyberduck by iterate-ch.
the class StoregateWriteFeature method start.
protected String start(final Path file, final TransferStatus status) throws BackgroundException {
try {
final StoregateApiClient client = session.getClient();
final HttpEntityEnclosingRequestBase request = new HttpPost(String.format("%s/v4/upload/resumable", client.getBasePath()));
final FileMetadata meta = new FileMetadata();
meta.setId(StringUtils.EMPTY);
if (status.isHidden()) {
// Hidden
meta.setAttributes(2);
} else {
meta.setAttributes(0);
}
meta.setFlags(0);
if (status.getLockId() != null) {
request.addHeader("X-Lock-Id", status.getLockId().toString());
}
meta.setFileName(URIEncoder.encode(file.getName()));
meta.setParentId(fileid.getFileId(file.getParent(), new DisabledListProgressListener()));
meta.setFileSize(status.getLength() > 0 ? status.getLength() : null);
meta.setCreated(DateTime.now());
if (null != status.getTimestamp()) {
meta.setModified(new DateTime(status.getTimestamp()));
}
request.setEntity(new StringEntity(new JSON().getContext(meta.getClass()).writeValueAsString(meta), ContentType.create("application/json", StandardCharsets.UTF_8.name())));
request.addHeader(HTTP.CONTENT_TYPE, MEDIA_TYPE);
final CloseableHttpResponse response = client.getClient().execute(request);
try {
switch(response.getStatusLine().getStatusCode()) {
case HttpStatus.SC_OK:
break;
default:
throw new StoregateExceptionMappingService(fileid).map(new ApiException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase(), Collections.emptyMap(), EntityUtils.toString(response.getEntity())));
}
} finally {
EntityUtils.consume(response.getEntity());
}
if (response.containsHeader(HttpHeaders.LOCATION)) {
return response.getFirstHeader(HttpHeaders.LOCATION).getValue();
}
throw new StoregateExceptionMappingService(fileid).map(new ApiException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase(), Collections.emptyMap(), EntityUtils.toString(response.getEntity())));
} catch (IOException e) {
throw new HttpExceptionMappingService().map("Upload {0} failed", e, file);
}
}
use of ch.cyberduck.core.http.HttpExceptionMappingService in project cyberduck by iterate-ch.
the class StoregateWriteFeature method write.
@Override
public HttpResponseOutputStream<FileMetadata> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
final DelayedHttpEntityCallable<FileMetadata> command = new DelayedHttpEntityCallable<FileMetadata>() {
@Override
public FileMetadata call(final AbstractHttpEntity entity) throws BackgroundException {
// Initiate a resumable upload
String location;
try {
location = start(file, status);
} catch (InteroperabilityException e) {
if (null == status.getLockId()) {
throw e;
}
location = start(file, status.withLockId(null));
}
final StoregateApiClient client = session.getClient();
try {
// Upload the file
final HttpPut put = new HttpPut(location);
put.setEntity(entity);
final String header;
if (status.getLength() == 0) {
// Touch
header = "*/0";
} else {
final HttpRange range = HttpRange.byLength(0, status.getLength());
header = String.format("%d-%d/%d", range.getStart(), range.getEnd(), status.getLength());
}
put.addHeader(HttpHeaders.CONTENT_RANGE, String.format("bytes %s", header));
final HttpResponse putResponse = client.getClient().execute(put);
try {
switch(putResponse.getStatusLine().getStatusCode()) {
case HttpStatus.SC_OK:
case HttpStatus.SC_CREATED:
final FileMetadata result = new JSON().getContext(FileMetadata.class).readValue(new InputStreamReader(putResponse.getEntity().getContent(), StandardCharsets.UTF_8), FileMetadata.class);
fileid.cache(file, result.getId());
return result;
default:
throw new StoregateExceptionMappingService(fileid).map(new ApiException(putResponse.getStatusLine().getStatusCode(), putResponse.getStatusLine().getReasonPhrase(), Collections.emptyMap(), EntityUtils.toString(putResponse.getEntity())));
}
} catch (BackgroundException e) {
// Cancel upload on error reply
cancel(file, location);
throw e;
} finally {
EntityUtils.consume(putResponse.getEntity());
}
} catch (IOException e) {
// Cancel upload on I/O failure
cancel(file, location);
throw new HttpExceptionMappingService().map("Upload {0} failed", e, file);
}
}
@Override
public long getContentLength() {
return status.getLength();
}
};
return this.write(file, status, command);
}
use of ch.cyberduck.core.http.HttpExceptionMappingService in project cyberduck by iterate-ch.
the class FreenetAuthenticatedUrlProvider method toUrl.
@Override
public DescriptiveUrl toUrl(final Host bookmark) {
try {
// Run password flow
final TokenResponse response;
try {
final Host target = new Host(new DAVSSLProtocol(), "oauth.freenet.de");
final X509TrustManager trust = new KeychainX509TrustManager(new DisabledCertificateTrustCallback(), new DefaultTrustManagerHostnameCallback(target), CertificateStoreFactory.get());
final X509KeyManager key = new KeychainX509KeyManager(new DisabledCertificateIdentityCallback(), target, CertificateStoreFactory.get());
final CloseableHttpClient client = new HttpConnectionPoolBuilder(target, new ThreadLocalHostnameDelegatingTrustManager(trust, target.getHostname()), key, ProxyFactory.get()).build(ProxyFactory.get().find(new ProxyHostUrlProvider().get(target)), new DisabledTranscriptListener(), new DisabledLoginCallback()).setUserAgent(new FreenetUserAgentProvider().get()).build();
final String username = bookmark.getCredentials().getUsername();
final String password;
if (StringUtils.isBlank(bookmark.getCredentials().getPassword())) {
password = PasswordStoreFactory.get().findLoginPassword(bookmark);
} else {
password = bookmark.getCredentials().getPassword();
}
response = new PasswordTokenRequest(new ApacheHttpTransport(client), new GsonFactory(), new GenericUrl("https://oauth.freenet.de/oauth/token"), username, password).setClientAuthentication(new BasicAuthentication("desktop_client", "6LIGIHuOSkznLomu5xw0EPPBJOXb2jLp")).setRequestInitializer(new UserAgentHttpRequestInitializer(new FreenetUserAgentProvider())).set("world", new HostPreferences(bookmark).getProperty("world")).set("webLogin", Boolean.TRUE).execute();
final FreenetTemporaryLoginResponse login = this.getLoginSession(client, response.getAccessToken());
return new DescriptiveUrl(URI.create(login.urls.login), DescriptiveUrl.Type.authenticated);
} catch (IOException e) {
throw new HttpExceptionMappingService().map(e);
}
} catch (BackgroundException e) {
log.warn(String.format("Failure %s retrieving authenticated URL for %s", e, bookmark));
return DescriptiveUrl.EMPTY;
}
}
use of ch.cyberduck.core.http.HttpExceptionMappingService in project cyberduck by iterate-ch.
the class DAVAttributesFinderFeature method find.
@Override
public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException {
if (file.isRoot()) {
return PathAttributes.EMPTY;
}
try {
try {
for (final DavResource resource : this.list(file)) {
if (resource.isDirectory()) {
if (!file.getType().contains(Path.Type.directory)) {
throw new NotfoundException(String.format("Path %s is directory", file.getAbsolute()));
}
} else {
if (!file.getType().contains(Path.Type.file)) {
throw new NotfoundException(String.format("Path %s is file", file.getAbsolute()));
}
}
return this.toAttributes(resource);
}
throw new NotfoundException(file.getAbsolute());
} catch (SardineException e) {
try {
throw new DAVExceptionMappingService().map("Failure to read attributes of {0}", e, file);
} catch (InteroperabilityException i) {
// PROPFIND Method not allowed
log.warn(String.format("Failure with PROPFIND request for %s. %s", file, i.getMessage()));
final Map<String, String> headers = session.getClient().execute(new HttpHead(new DAVPathEncoder().encode(file)), new HeadersResponseHandler());
final PathAttributes attributes = new PathAttributes();
try {
attributes.setModificationDate(rfc1123.parse(headers.get(HttpHeaders.LAST_MODIFIED)).getTime());
} catch (InvalidDateException p) {
log.warn(String.format("%s is not RFC 1123 format %s", headers.get(HttpHeaders.LAST_MODIFIED), p.getMessage()));
}
if (!headers.containsKey(HttpHeaders.CONTENT_ENCODING)) {
// Set size unless response is compressed
attributes.setSize(NumberUtils.toLong(headers.get(HttpHeaders.CONTENT_LENGTH), -1));
}
if (headers.containsKey(HttpHeaders.ETAG)) {
attributes.setETag(headers.get(HttpHeaders.ETAG));
// Setting checksum is disabled. See #8798
// attributes.setChecksum(Checksum.parse(headers.get(HttpHeaders.ETAG)));
}
if (headers.containsKey(HttpHeaders.CONTENT_MD5)) {
attributes.setChecksum(Checksum.parse(headers.get(HttpHeaders.CONTENT_MD5)));
}
return attributes;
}
}
} catch (SardineException e) {
throw new DAVExceptionMappingService().map("Failure to read attributes of {0}", e, file);
} catch (IOException e) {
throw new HttpExceptionMappingService().map(e, file);
}
}
use of ch.cyberduck.core.http.HttpExceptionMappingService in project cyberduck by iterate-ch.
the class DAVListService method list.
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
try {
final AttributedList<Path> children = new AttributedList<Path>();
for (final DavResource resource : this.list(directory)) {
// Try to parse as RFC 2396
final String href = PathNormalizer.normalize(resource.getHref().getPath(), true);
if (href.equals(directory.getAbsolute())) {
log.warn(String.format("Ignore resource %s", href));
// Do not include self
if (resource.isDirectory()) {
continue;
}
throw new NotfoundException(directory.getAbsolute());
}
final PathAttributes attr = attributes.toAttributes(resource);
final Path file = new Path(directory, PathNormalizer.name(href), resource.isDirectory() ? EnumSet.of(Path.Type.directory) : EnumSet.of(Path.Type.file), attr);
children.add(file);
listener.chunk(directory, children);
}
return children;
} catch (SardineException e) {
throw new DAVExceptionMappingService().map("Listing directory {0} failed", e, directory);
} catch (IOException e) {
throw new HttpExceptionMappingService().map(e, directory);
}
}
Aggregations