Search in sources :

Example 1 with HttpExceptionMappingService

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);
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpEntityEnclosingRequestBase(org.apache.http.client.methods.HttpEntityEnclosingRequestBase) DisabledListProgressListener(ch.cyberduck.core.DisabledListProgressListener) FileMetadata(ch.cyberduck.core.storegate.io.swagger.client.model.FileMetadata) JSON(ch.cyberduck.core.storegate.io.swagger.client.JSON) IOException(java.io.IOException) DateTime(org.joda.time.DateTime) StringEntity(org.apache.http.entity.StringEntity) HttpExceptionMappingService(ch.cyberduck.core.http.HttpExceptionMappingService) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) ApiException(ch.cyberduck.core.storegate.io.swagger.client.ApiException)

Example 2 with HttpExceptionMappingService

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);
}
Also used : InteroperabilityException(ch.cyberduck.core.exception.InteroperabilityException) InputStreamReader(java.io.InputStreamReader) FileMetadata(ch.cyberduck.core.storegate.io.swagger.client.model.FileMetadata) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpResponse(org.apache.http.HttpResponse) JSON(ch.cyberduck.core.storegate.io.swagger.client.JSON) IOException(java.io.IOException) DelayedHttpEntityCallable(ch.cyberduck.core.http.DelayedHttpEntityCallable) HttpPut(org.apache.http.client.methods.HttpPut) HttpExceptionMappingService(ch.cyberduck.core.http.HttpExceptionMappingService) AbstractHttpEntity(org.apache.http.entity.AbstractHttpEntity) BackgroundException(ch.cyberduck.core.exception.BackgroundException) HttpRange(ch.cyberduck.core.http.HttpRange) ApiException(ch.cyberduck.core.storegate.io.swagger.client.ApiException)

Example 3 with HttpExceptionMappingService

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;
    }
}
Also used : UserAgentHttpRequestInitializer(ch.cyberduck.core.http.UserAgentHttpRequestInitializer) KeychainX509KeyManager(ch.cyberduck.core.ssl.KeychainX509KeyManager) DisabledCertificateIdentityCallback(ch.cyberduck.core.DisabledCertificateIdentityCallback) ProxyHostUrlProvider(ch.cyberduck.core.proxy.ProxyHostUrlProvider) GenericUrl(com.google.api.client.http.GenericUrl) DAVSSLProtocol(ch.cyberduck.core.dav.DAVSSLProtocol) KeychainX509TrustManager(ch.cyberduck.core.ssl.KeychainX509TrustManager) HttpExceptionMappingService(ch.cyberduck.core.http.HttpExceptionMappingService) HttpConnectionPoolBuilder(ch.cyberduck.core.http.HttpConnectionPoolBuilder) KeychainX509KeyManager(ch.cyberduck.core.ssl.KeychainX509KeyManager) X509KeyManager(ch.cyberduck.core.ssl.X509KeyManager) DisabledCertificateTrustCallback(ch.cyberduck.core.DisabledCertificateTrustCallback) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) GsonFactory(com.google.api.client.json.gson.GsonFactory) Host(ch.cyberduck.core.Host) IOException(java.io.IOException) DisabledTranscriptListener(ch.cyberduck.core.DisabledTranscriptListener) HostPreferences(ch.cyberduck.core.preferences.HostPreferences) DescriptiveUrl(ch.cyberduck.core.DescriptiveUrl) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) X509TrustManager(ch.cyberduck.core.ssl.X509TrustManager) KeychainX509TrustManager(ch.cyberduck.core.ssl.KeychainX509TrustManager) DisabledLoginCallback(ch.cyberduck.core.DisabledLoginCallback) ThreadLocalHostnameDelegatingTrustManager(ch.cyberduck.core.ssl.ThreadLocalHostnameDelegatingTrustManager) DefaultTrustManagerHostnameCallback(ch.cyberduck.core.ssl.DefaultTrustManagerHostnameCallback) BasicAuthentication(com.google.api.client.http.BasicAuthentication) PasswordTokenRequest(com.google.api.client.auth.oauth2.PasswordTokenRequest) ApacheHttpTransport(com.google.api.client.http.apache.v2.ApacheHttpTransport) BackgroundException(ch.cyberduck.core.exception.BackgroundException)

Example 4 with HttpExceptionMappingService

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);
    }
}
Also used : NotfoundException(ch.cyberduck.core.exception.NotfoundException) DavResource(com.github.sardine.DavResource) InteroperabilityException(ch.cyberduck.core.exception.InteroperabilityException) PathAttributes(ch.cyberduck.core.PathAttributes) IOException(java.io.IOException) HttpHead(org.apache.http.client.methods.HttpHead) SardineException(com.github.sardine.impl.SardineException) HttpExceptionMappingService(ch.cyberduck.core.http.HttpExceptionMappingService) InvalidDateException(ch.cyberduck.core.date.InvalidDateException) HeadersResponseHandler(com.github.sardine.impl.handler.HeadersResponseHandler)

Example 5 with HttpExceptionMappingService

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);
    }
}
Also used : Path(ch.cyberduck.core.Path) NotfoundException(ch.cyberduck.core.exception.NotfoundException) SardineException(com.github.sardine.impl.SardineException) HttpExceptionMappingService(ch.cyberduck.core.http.HttpExceptionMappingService) DavResource(com.github.sardine.DavResource) AttributedList(ch.cyberduck.core.AttributedList) PathAttributes(ch.cyberduck.core.PathAttributes) IOException(java.io.IOException)

Aggregations

HttpExceptionMappingService (ch.cyberduck.core.http.HttpExceptionMappingService)15 IOException (java.io.IOException)15 SardineException (com.github.sardine.impl.SardineException)8 Path (ch.cyberduck.core.Path)4 HttpResponse (org.apache.http.HttpResponse)4 DisabledListProgressListener (ch.cyberduck.core.DisabledListProgressListener)3 HttpRange (ch.cyberduck.core.http.HttpRange)3 ArrayList (java.util.ArrayList)3 Map (java.util.Map)3 Header (org.apache.http.Header)3 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)3 HttpHead (org.apache.http.client.methods.HttpHead)3 AttributedList (ch.cyberduck.core.AttributedList)2 PathAttributes (ch.cyberduck.core.PathAttributes)2 BackgroundException (ch.cyberduck.core.exception.BackgroundException)2 InteroperabilityException (ch.cyberduck.core.exception.InteroperabilityException)2 NotfoundException (ch.cyberduck.core.exception.NotfoundException)2 HttpMethodReleaseInputStream (ch.cyberduck.core.http.HttpMethodReleaseInputStream)2 DefaultPathHomeFeature (ch.cyberduck.core.shared.DefaultPathHomeFeature)2 DelegatingHomeFeature (ch.cyberduck.core.shared.DelegatingHomeFeature)2