Search in sources :

Example 46 with GoogleJsonResponseException

use of com.google.api.client.googleapis.json.GoogleJsonResponseException in project OsmAnd-tools by osmandapp.

the class UpdateSubscription method processAndroidSubscription.

private SubscriptionPurchase processAndroidSubscription(AndroidPublisher.Purchases purchases, String purchaseToken, String sku, String orderId, Timestamp regTime, Timestamp startTime, Timestamp expireTime, long currentTime, boolean verbose) throws SQLException, SubscriptionUpdateException {
    SubscriptionPurchase subscription = null;
    String reason = "";
    String kind = null;
    try {
        if (sku.startsWith("osm_free") || sku.contains("_free_")) {
            subscription = purchases.subscriptions().get(GOOGLE_PACKAGE_NAME_FREE, sku, purchaseToken).execute();
        } else {
            subscription = purchases.subscriptions().get(GOOGLE_PACKAGE_NAME, sku, purchaseToken).execute();
        }
        if (verbose) {
            System.out.println("Result: " + subscription.toPrettyString());
        }
    } catch (IOException e) {
        int errorCode = 0;
        if (e instanceof GoogleJsonResponseException) {
            errorCode = ((GoogleJsonResponseException) e).getStatusCode();
        }
        if (expireTime != null && currentTime - expireTime.getTime() > MAX_WAITING_TIME_TO_EXPIRE) {
            reason = String.format(" subscription expired more than %.1f days ago (%s)", (currentTime - expireTime.getTime()) / (DAY * 1.0d), e.getMessage());
            kind = "expired";
        } else if (!purchaseToken.contains(".AO") || errorCode == 400) {
            reason = String.format(" subscription is invalid - possibly fraud %s, %s (%s)", orderId, purchaseToken, e.getMessage());
            if ((currentTime - regTime.getTime()) > MAX_WAITING_TIME_TO_MAKE_INVALID) {
                kind = "invalid";
            }
        } else if (errorCode == 410) {
            kind = "gone";
            reason = " user doesn't exist (" + e.getMessage() + ") ";
        } else {
            reason = " unknown reason (should be checked and fixed)! " + e.getMessage();
        }
    }
    if (subscription != null) {
        String appStoreOrderId = simplifyOrderId(subscription.getOrderId());
        if (!Algorithms.objectEquals(appStoreOrderId, orderId)) {
            throw new IllegalStateException(String.format("Order id '%s' != '%s' don't match", orderId, appStoreOrderId));
        }
        updateSubscriptionDb(orderId, sku, startTime, expireTime, currentTime, subscription);
    } else if (kind != null) {
        deleteSubscription(orderId, sku, currentTime, reason, kind);
    } else {
        System.err.println(String.format("ERROR updating sku '%s' orderId '%s': %s", sku, orderId, reason));
        int ind = 1;
        updCheckStat.setTimestamp(ind++, new Timestamp(currentTime));
        updCheckStat.setString(ind++, orderId);
        updCheckStat.setString(ind++, sku);
        updCheckStat.addBatch();
        checkChanges++;
        if (checkChanges > BATCH_SIZE) {
            updCheckStat.executeBatch();
            checkChanges = 0;
        }
    }
    return subscription;
}
Also used : GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) SubscriptionPurchase(com.google.api.services.androidpublisher.model.SubscriptionPurchase) IOException(java.io.IOException) AmazonIOException(net.osmand.live.subscriptions.AmazonIAPHelper.AmazonIOException) Timestamp(java.sql.Timestamp)

Example 47 with GoogleJsonResponseException

use of com.google.api.client.googleapis.json.GoogleJsonResponseException in project google-cloud-java by GoogleCloudPlatform.

the class BaseHttpServiceException method makeExceptionData.

private static ExceptionData makeExceptionData(IOException exception, boolean idempotent, Set<BaseServiceException.Error> retryableErrors) {
    int code = UNKNOWN_CODE;
    String reason = null;
    String location = null;
    String debugInfo = null;
    Boolean retryable = null;
    if (exception instanceof HttpResponseException) {
        if (exception instanceof GoogleJsonResponseException) {
            GoogleJsonError jsonError = ((GoogleJsonResponseException) exception).getDetails();
            if (jsonError != null) {
                BaseServiceException.Error error = new BaseServiceException.Error(jsonError.getCode(), reason(jsonError));
                code = error.getCode();
                reason = error.getReason();
                retryable = error.isRetryable(idempotent, retryableErrors);
                if (reason != null) {
                    GoogleJsonError.ErrorInfo errorInfo = jsonError.getErrors().get(0);
                    location = errorInfo.getLocation();
                    debugInfo = (String) errorInfo.get("debugInfo");
                }
            } else {
                code = ((GoogleJsonResponseException) exception).getStatusCode();
            }
        } else {
            // In cases where an exception is an instance of HttpResponseException but not
            // an instance of GoogleJsonResponseException, check the status code to determine whether it's retryable
            code = ((HttpResponseException) exception).getStatusCode();
            retryable = BaseServiceException.isRetryable(code, null, idempotent, retryableErrors);
        }
    }
    return ExceptionData.newBuilder().setMessage(message(exception)).setCause(exception).setRetryable(MoreObjects.firstNonNull(retryable, BaseServiceException.isRetryable(idempotent, exception))).setCode(code).setReason(reason).setLocation(location).setDebugInfo(debugInfo).build();
}
Also used : GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) BaseServiceException(com.google.cloud.BaseServiceException) GoogleJsonError(com.google.api.client.googleapis.json.GoogleJsonError) HttpResponseException(com.google.api.client.http.HttpResponseException) GoogleJsonError(com.google.api.client.googleapis.json.GoogleJsonError)

Example 48 with GoogleJsonResponseException

use of com.google.api.client.googleapis.json.GoogleJsonResponseException in project beam by apache.

the class GcsUtil method createBucket.

@VisibleForTesting
void createBucket(String projectId, Bucket bucket, BackOff backoff, Sleeper sleeper) throws IOException {
    Storage.Buckets.Insert insertBucket = storageClient.buckets().insert(projectId, bucket);
    insertBucket.setPredefinedAcl("projectPrivate");
    insertBucket.setPredefinedDefaultObjectAcl("projectPrivate");
    try {
        ResilientOperation.retry(ResilientOperation.getGoogleRequestCallable(insertBucket), backoff, new RetryDeterminer<IOException>() {

            @Override
            public boolean shouldRetry(IOException e) {
                if (errorExtractor.itemAlreadyExists(e) || errorExtractor.accessDenied(e)) {
                    return false;
                }
                return RetryDeterminer.SOCKET_ERRORS.shouldRetry(e);
            }
        }, IOException.class, sleeper);
        return;
    } catch (GoogleJsonResponseException e) {
        if (errorExtractor.accessDenied(e)) {
            throw new AccessDeniedException(bucket.getName(), null, e.getMessage());
        }
        if (errorExtractor.itemAlreadyExists(e)) {
            throw new FileAlreadyExistsException(bucket.getName(), null, e.getMessage());
        }
        throw e;
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new IOException(String.format("Error while attempting to create bucket gs://%s for rproject %s", bucket.getName(), projectId), e);
    }
}
Also used : GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) AccessDeniedException(java.nio.file.AccessDeniedException) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) IOException(java.io.IOException) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 49 with GoogleJsonResponseException

use of com.google.api.client.googleapis.json.GoogleJsonResponseException in project beam by apache.

the class GcsUtilTest method testBucketDoesNotExistBecauseOfAccessError.

@Test
public void testBucketDoesNotExistBecauseOfAccessError() throws IOException {
    GcsOptions pipelineOptions = gcsOptionsWithTestCredential();
    GcsUtil gcsUtil = pipelineOptions.getGcsUtil();
    Storage mockStorage = Mockito.mock(Storage.class);
    gcsUtil.setStorageClient(mockStorage);
    Storage.Buckets mockStorageObjects = Mockito.mock(Storage.Buckets.class);
    Storage.Buckets.Get mockStorageGet = Mockito.mock(Storage.Buckets.Get.class);
    BackOff mockBackOff = BackOffAdapter.toGcpBackOff(FluentBackoff.DEFAULT.backoff());
    GoogleJsonResponseException expectedException = googleJsonResponseException(HttpStatusCodes.STATUS_CODE_FORBIDDEN, "Waves hand mysteriously", "These aren't the buckets you're looking for");
    when(mockStorage.buckets()).thenReturn(mockStorageObjects);
    when(mockStorageObjects.get("testbucket")).thenReturn(mockStorageGet);
    when(mockStorageGet.execute()).thenThrow(expectedException);
    assertFalse(gcsUtil.bucketAccessible(GcsPath.fromComponents("testbucket", "testobject"), mockBackOff, new FastNanoClockAndSleeper()));
}
Also used : GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) Storage(com.google.api.services.storage.Storage) GcsOptions(org.apache.beam.sdk.extensions.gcp.options.GcsOptions) BackOff(com.google.api.client.util.BackOff) Test(org.junit.Test)

Example 50 with GoogleJsonResponseException

use of com.google.api.client.googleapis.json.GoogleJsonResponseException in project ignite by apache.

the class TcpDiscoveryGoogleStorageIpFinder method init.

/**
 * Google Cloud Storage initialization.
 *
 * @throws IgniteSpiException In case of error.
 */
private void init() throws IgniteSpiException {
    if (initGuard.compareAndSet(false, true)) {
        if (srvcAccountId == null || srvcAccountP12FilePath == null || projectName == null || bucketName == null) {
            throw new IgniteSpiException("One or more of the required parameters is not set [serviceAccountId=" + srvcAccountId + ", serviceAccountP12FilePath=" + srvcAccountP12FilePath + ", projectName=" + projectName + ", bucketName=" + bucketName + "]");
        }
        try {
            NetHttpTransport httpTransport;
            try {
                httpTransport = GoogleNetHttpTransport.newTrustedTransport();
            } catch (GeneralSecurityException | IOException e) {
                throw new IgniteSpiException(e);
            }
            GoogleCredential cred;
            try {
                cred = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(JacksonFactory.getDefaultInstance()).setServiceAccountId(srvcAccountId).setServiceAccountPrivateKeyFromP12File(new File(srvcAccountP12FilePath)).setServiceAccountScopes(Collections.singleton(StorageScopes.DEVSTORAGE_FULL_CONTROL)).build();
            } catch (Exception e) {
                throw new IgniteSpiException("Failed to authenticate on Google Cloud Platform", e);
            }
            try {
                storage = new Storage.Builder(httpTransport, JacksonFactory.getDefaultInstance(), cred).setApplicationName(projectName).build();
            } catch (Exception e) {
                throw new IgniteSpiException("Failed to open a storage for given project name: " + projectName, e);
            }
            boolean createBucket = false;
            try {
                Storage.Buckets.Get getBucket = storage.buckets().get(bucketName);
                getBucket.setProjection("full");
                getBucket.execute();
            } catch (GoogleJsonResponseException e) {
                if (e.getStatusCode() == 404) {
                    U.warn(log, "Bucket doesn't exist, will create it [bucketName=" + bucketName + "]");
                    createBucket = true;
                } else
                    throw new IgniteSpiException("Failed to open the bucket: " + bucketName, e);
            } catch (Exception e) {
                throw new IgniteSpiException("Failed to open the bucket: " + bucketName, e);
            }
            if (createBucket) {
                Bucket newBucket = new Bucket();
                newBucket.setName(bucketName);
                try {
                    Storage.Buckets.Insert insertBucket = storage.buckets().insert(projectName, newBucket);
                    insertBucket.setProjection("full");
                    insertBucket.setPredefinedDefaultObjectAcl("projectPrivate");
                    insertBucket.execute();
                } catch (Exception e) {
                    throw new IgniteSpiException("Failed to create the bucket: " + bucketName, e);
                }
            }
        } finally {
            initLatch.countDown();
        }
    } else {
        try {
            U.await(initLatch);
        } catch (IgniteInterruptedCheckedException e) {
            throw new IgniteSpiException("Thread has been interrupted.", e);
        }
        if (storage == null)
            throw new IgniteSpiException("IpFinder has not been initialized properly");
    }
}
Also used : GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) GoogleCredential(com.google.api.client.googleapis.auth.oauth2.GoogleCredential) IgniteSpiException(org.apache.ignite.spi.IgniteSpiException) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) GeneralSecurityException(java.security.GeneralSecurityException) IgniteInterruptedCheckedException(org.apache.ignite.internal.IgniteInterruptedCheckedException) IOException(java.io.IOException) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) IgniteInterruptedCheckedException(org.apache.ignite.internal.IgniteInterruptedCheckedException) Storage(com.google.api.services.storage.Storage) Bucket(com.google.api.services.storage.model.Bucket) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) GoogleNetHttpTransport(com.google.api.client.googleapis.javanet.GoogleNetHttpTransport) IgniteSpiException(org.apache.ignite.spi.IgniteSpiException) File(java.io.File)

Aggregations

GoogleJsonResponseException (com.google.api.client.googleapis.json.GoogleJsonResponseException)94 IOException (java.io.IOException)48 YouTube (com.google.api.services.youtube.YouTube)26 Credential (com.google.api.client.auth.oauth2.Credential)25 ArrayList (java.util.ArrayList)13 Operation (com.google.api.services.compute.model.Operation)12 Test (org.junit.Test)12 Compute (com.google.api.services.compute.Compute)11 Storage (com.google.api.services.storage.Storage)10 GcpResourceException (com.sequenceiq.cloudbreak.cloud.gcp.GcpResourceException)8 GcsOptions (org.apache.beam.sdk.extensions.gcp.options.GcsOptions)7 GoogleJsonError (com.google.api.client.googleapis.json.GoogleJsonError)5 InputStreamContent (com.google.api.client.http.InputStreamContent)5 BackOff (com.google.api.client.util.BackOff)5 HashMap (java.util.HashMap)5 Objects (com.google.api.services.storage.model.Objects)4 GoogleCloudStorage (com.google.cloud.hadoop.gcsio.GoogleCloudStorage)4 HalException (com.netflix.spinnaker.halyard.core.error.v1.HalException)4 MediaHttpUploader (com.google.api.client.googleapis.media.MediaHttpUploader)3 MediaHttpUploaderProgressListener (com.google.api.client.googleapis.media.MediaHttpUploaderProgressListener)3