Search in sources :

Example 6 with ByteArrayContent

use of com.google.api.client.http.ByteArrayContent in project keepass2android by PhilippC.

the class GoogleDriveFileStorage method uploadFile.

@Override
public void uploadFile(String path, byte[] data, boolean writeTransactional) throws Exception {
    logDebug("upload file...");
    try {
        ByteArrayContent content = new ByteArrayContent(null, data);
        GDrivePath gdrivePath = new GDrivePath(path);
        Drive driveService = getDriveService(gdrivePath.getAccount());
        File driveFile = getFileForPath(gdrivePath, driveService);
        getDriveService(gdrivePath.getAccount()).files().update(driveFile.getId(), driveFile, content).execute();
        logDebug("upload file ok.");
    } catch (Exception e) {
        throw convertException(e);
    }
}
Also used : Drive(com.google.api.services.drive.Drive) ByteArrayContent(com.google.api.client.http.ByteArrayContent) File(com.google.api.services.drive.model.File) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) UserRecoverableAuthIOException(com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 7 with ByteArrayContent

use of com.google.api.client.http.ByteArrayContent in project providence by morimekta.

the class HttpClientHandler method handleCall.

@Override
public <Request extends PMessage<Request, RequestField>, Response extends PMessage<Response, ResponseField>, RequestField extends PField, ResponseField extends PField> PServiceCall<Response, ResponseField> handleCall(PServiceCall<Request, RequestField> call, PService service) throws IOException {
    if (call.getType() == PServiceCallType.EXCEPTION || call.getType() == PServiceCallType.REPLY) {
        throw new PApplicationException("Request with invalid call type: " + call.getType(), PApplicationExceptionType.INVALID_MESSAGE_TYPE);
    }
    long startTime = System.nanoTime();
    PServiceCall<Response, ResponseField> reply = null;
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        requestSerializer.serialize(baos, call);
        ByteArrayContent content = new ByteArrayContent(requestSerializer.mediaType(), baos.toByteArray());
        @Nonnull GenericUrl url = urlSupplier.get();
        try {
            HttpRequest request = factory.buildPostRequest(url, content);
            request.getHeaders().setAccept(requestSerializer.mediaType());
            HttpResponse response = request.execute();
            try {
                if (call.getType() == PServiceCallType.CALL) {
                    Serializer responseSerializer = requestSerializer;
                    if (response.getContentType() != null) {
                        try {
                            MediaType mediaType = MediaType.parse(response.getContentType());
                            responseSerializer = serializerProvider.getSerializer(mediaType.withoutParameters().toString());
                        } catch (IllegalArgumentException e) {
                            throw new PApplicationException("Unknown content-type in response: " + response.getContentType(), PApplicationExceptionType.INVALID_PROTOCOL).initCause(e);
                        }
                    }
                    // non 200 responses should have triggered a HttpResponseException,
                    // so this is safe.
                    reply = responseSerializer.deserialize(response.getContent(), service);
                    if (reply.getType() == PServiceCallType.CALL || reply.getType() == PServiceCallType.ONEWAY) {
                        throw new PApplicationException("Reply with invalid call type: " + reply.getType(), PApplicationExceptionType.INVALID_MESSAGE_TYPE);
                    }
                    if (reply.getSequence() != call.getSequence()) {
                        throw new PApplicationException("Reply sequence out of order: call = " + call.getSequence() + ", reply = " + reply.getSequence(), PApplicationExceptionType.BAD_SEQUENCE_ID);
                    }
                }
                long endTime = System.nanoTime();
                double duration = ((double) (endTime - startTime)) / NS_IN_MILLIS;
                try {
                    instrumentation.onComplete(duration, call, reply);
                } catch (Exception ignore) {
                }
                return reply;
            } finally {
                // Ignore whatever is left of the response when returning, in
                // case we did'nt read the whole response.
                response.ignore();
            }
        } catch (HttpHostConnectException e) {
            throw e;
        } catch (ConnectException e) {
            // The native exception is not helpful (for when using NetHttpTransport).
            throw new HttpHostConnectException(e, new HttpHost(url.getHost(), url.getPort(), url.getScheme()));
        }
    } catch (Exception e) {
        long endTime = System.nanoTime();
        double duration = ((double) (endTime - startTime)) / NS_IN_MILLIS;
        try {
            instrumentation.onTransportException(e, duration, call, reply);
        } catch (Throwable ie) {
            e.addSuppressed(ie);
        }
        throw e;
    }
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) Nonnull(javax.annotation.Nonnull) HttpResponse(com.google.api.client.http.HttpResponse) ByteArrayOutputStream(java.io.ByteArrayOutputStream) GenericUrl(com.google.api.client.http.GenericUrl) PApplicationException(net.morimekta.providence.PApplicationException) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) ConnectException(java.net.ConnectException) IOException(java.io.IOException) HttpResponse(com.google.api.client.http.HttpResponse) HttpHost(org.apache.http.HttpHost) PApplicationException(net.morimekta.providence.PApplicationException) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) MediaType(com.google.common.net.MediaType) ByteArrayContent(com.google.api.client.http.ByteArrayContent) Serializer(net.morimekta.providence.serializer.Serializer) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) ConnectException(java.net.ConnectException)

Example 8 with ByteArrayContent

use of com.google.api.client.http.ByteArrayContent in project FortniteAPI by Xilixir.

the class FortniteAPI method authenticate.

public void authenticate() throws IOException {
    log("Starting Authentication...");
    Gson gson = new Gson();
    // initial login
    GenericUrl tokenUrl = new GenericUrl(authTokenEndpoint);
    String initialLoginPayload = payloadBuilder(new String[] { "grant_type", "username", "password", "includePerms" }, new String[] { "password", encode(credentials.getEmail()), encode(credentials.getPassword()), "true" });
    ByteArrayContent initialLoginContent = new ByteArrayContent("application/x-www-form-urlencoded", initialLoginPayload.getBytes());
    HttpRequest initialLoginRequest = factory.buildPostRequest(tokenUrl, initialLoginContent);
    initialLoginRequest.getHeaders().setAuthorization("basic " + credentials.getBase64hashPair());
    // initial login response
    String initialLoginResponse = initialLoginRequest.execute().parseAsString();
    this.auth = gson.fromJson(initialLoginResponse, EpicAuthorization.class);
    // exchange-1
    String authExchangeEndpoint = "https://account-public-service-prod03.ol.epicgames.com/account/api/oauth/exchange";
    GenericUrl exchangeUrl = new GenericUrl(authExchangeEndpoint);
    HttpRequest exchangeRequest = factory.buildGetRequest(exchangeUrl);
    exchangeRequest.getHeaders().setAuthorization("bearer " + this.auth.getAccessToken());
    // exchange-1 response
    String exchangeResponse = exchangeRequest.execute().parseAsString();
    EpicAuthorizationExchange exchange = gson.fromJson(exchangeResponse, EpicAuthorizationExchange.class);
    // exchange-2
    String exchangeTokenPayload = payloadBuilder(new String[] { "grant_type", "exchange_code", "includePerms", "token_type" }, new String[] { "exchange_code", exchange.getCode(), "true", "eg1" });
    ByteArrayContent exchangeTokenContent = new ByteArrayContent("application/x-www-form-urlencoded", exchangeTokenPayload.getBytes());
    HttpRequest exchangeTokenRequest = factory.buildPostRequest(tokenUrl, exchangeTokenContent);
    exchangeTokenRequest.getHeaders().setAuthorization("basic " + credentials.getBase64hashPairClient());
    // exchange-2 response
    String exchangeTokenResponse = exchangeTokenRequest.execute().parseAsString();
    this.auth = gson.fromJson(exchangeTokenResponse, EpicAuthorization.class);
    log("Authenticated successfully!");
    this.scheduleTokenRefresh();
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) EpicAuthorization(com.xilixir.fortniteapi.v2.Epic.EpicAuthorization) Gson(com.google.gson.Gson) GenericUrl(com.google.api.client.http.GenericUrl) ByteArrayContent(com.google.api.client.http.ByteArrayContent) EpicAuthorizationExchange(com.xilixir.fortniteapi.v2.Epic.EpicAuthorizationExchange)

Example 9 with ByteArrayContent

use of com.google.api.client.http.ByteArrayContent in project FortniteAPI by Xilixir.

the class FortniteAPI method refreshToken.

private void refreshToken() {
    try {
        log("Refreshing token...");
        Gson gson = new Gson();
        // refresh request
        GenericUrl url = new GenericUrl(authTokenEndpoint);
        String refreshTokenPayload = payloadBuilder(new String[] { "grant_type", "refresh_token", "includePerms" }, new String[] { "refresh_token", this.auth.getRefreshToken(), "true" });
        ByteArrayContent refreshTokenContent = new ByteArrayContent("application/x-www-form-urlencoded", refreshTokenPayload.getBytes());
        HttpRequest refreshTokenRequest = factory.buildPostRequest(url, refreshTokenContent);
        refreshTokenRequest.getHeaders().setAuthorization("basic " + this.credentials.getBase64hashPairClient());
        // refresh response
        String refreshTokenResponse = refreshTokenRequest.execute().parseAsString();
        this.auth = gson.fromJson(refreshTokenResponse, EpicAuthorization.class);
        this.scheduleTokenRefresh();
        log("Token refresh complete");
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) EpicAuthorization(com.xilixir.fortniteapi.v2.Epic.EpicAuthorization) Gson(com.google.gson.Gson) GenericUrl(com.google.api.client.http.GenericUrl) IOException(java.io.IOException) ByteArrayContent(com.google.api.client.http.ByteArrayContent)

Example 10 with ByteArrayContent

use of com.google.api.client.http.ByteArrayContent in project google-api-java-client by google.

the class MediaHttpUploaderTest method testDirectUploadServerErrorWithBackOffEnabled.

public void testDirectUploadServerErrorWithBackOffEnabled() throws Exception {
    int contentLength = MediaHttpUploader.DEFAULT_CHUNK_SIZE * 2;
    MediaTransport fakeTransport = new MediaTransport(contentLength);
    fakeTransport.testServerError = true;
    fakeTransport.directUploadEnabled = true;
    ByteArrayContent mediaContent = new ByteArrayContent(TEST_CONTENT_TYPE, new byte[contentLength]);
    MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, fakeTransport, new ZeroBackOffRequestInitializer());
    uploader.setDirectUploadEnabled(true);
    uploader.upload(new GenericUrl(TEST_DIRECT_REQUEST_URL));
    // should be 2 calls made: 1 upload request with server error, 1 successful upload request
    assertEquals(2, fakeTransport.lowLevelExecCalls);
}
Also used : GenericUrl(com.google.api.client.http.GenericUrl) ByteArrayContent(com.google.api.client.http.ByteArrayContent)

Aggregations

ByteArrayContent (com.google.api.client.http.ByteArrayContent)43 GenericUrl (com.google.api.client.http.GenericUrl)24 HttpRequest (com.google.api.client.http.HttpRequest)17 IOException (java.io.IOException)12 Test (org.junit.Test)12 HttpResponse (com.google.api.client.http.HttpResponse)10 HttpRequestFactory (com.google.api.client.http.HttpRequestFactory)7 HttpContent (com.google.api.client.http.HttpContent)6 HttpHeaders (com.google.api.client.http.HttpHeaders)6 Gson (com.google.gson.Gson)6 MockResponse (com.google.api.ads.common.lib.testing.MockResponse)4 MockHttpTransport (com.google.api.client.testing.http.MockHttpTransport)4 MockLowLevelHttpRequest (com.google.api.client.testing.http.MockLowLevelHttpRequest)4 File (com.google.api.services.drive.model.File)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 Credential (com.google.api.client.auth.oauth2.Credential)3 GoogleCredential (com.google.api.client.googleapis.auth.oauth2.GoogleCredential)3 HttpResponseException (com.google.api.client.http.HttpResponseException)3 InputStreamContent (com.google.api.client.http.InputStreamContent)3 AbstractInputStreamContent (com.google.api.client.http.AbstractInputStreamContent)2