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;
}
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();
}
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);
}
}
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()));
}
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");
}
}
Aggregations