Java Code Examples for com.google.api.client.googleapis.json.GoogleJsonResponseException#getStatusCode()

The following examples show how to use com.google.api.client.googleapis.json.GoogleJsonResponseException#getStatusCode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GcloudPubsub.java    From cloud-pubsub-mqtt-proxy with Apache License 2.0 6 votes vote down vote up
private void createTopic(final String topic) throws IOException {
  try {
    pubsub.projects().topics().create(topic, new Topic()).execute();
  } catch (GoogleJsonResponseException e) {
    // two threads were trying to create topic at the same time
    // first thread created a topic, causing second thread to wait(this method is synchronized)
    // second thread causes an exception since it tries to create an existing topic
    if (e.getStatusCode() == RESOURCE_CONFLICT) {
      logger.info("Topic was created by another thread");
      return ;
    }
    // if it is not a topic conflict(or topic already exists) error,
    // it must be a low level error, and the client should send the PUBLISH packet again for retry
    // we throw the exception, so that we don't send a PUBACK to the client
    throw e;
  }
  logger.info("Google Cloud Pub/Sub Topic Created");
}
 
Example 2
Source File: GPlusDataCollector.java    From streams with Apache License 2.0 6 votes vote down vote up
/**
 * Looks at the status code of the exception.  If the code indicates that the request should be retried,
 * it executes the back off strategy and returns true.
 * @param gjre GoogleJsonResponseException
 * @param backOff BackOffStrategy
 * @return returns true if the error code of the exception indicates the request should be retried.
 */
public boolean backoffAndIdentifyIfRetry(GoogleJsonResponseException gjre, BackOffStrategy backOff) throws BackOffException {
  boolean tryAgain = false;
  switch (gjre.getStatusCode()) {
    case 400 :
      LOGGER.warn("Bad Request  : {}",  gjre);
      break;
    case 401 :
      LOGGER.warn("Invalid Credentials : {}", gjre);
      break;
    case 403 :
      LOGGER.warn("Possible rate limit exception. Retrying. : {}", gjre.getMessage());
      backOff.backOff();
      tryAgain = true;
      break;
    case 503 :
      LOGGER.warn("Google Backend Service Error : {}", gjre);
      break;
    default:
      LOGGER.warn("Google Service returned error : {}", gjre);
      tryAgain = true;
      backOff.backOff();
      break;
  }
  return tryAgain;
}
 
Example 3
Source File: Authenticator.java    From styx with Apache License 2.0 6 votes vote down vote up
private boolean resolveProjectAccess(String projectId) throws IOException {
  final GetAncestryResponse ancestry;
  var request = cloudResourceManager.projects().getAncestry(projectId, new GetAncestryRequest());
  try {
    ancestry = executeWithRetries(request, retryWaitStrategy, retryStopStrategy);
  } catch (GoogleJsonResponseException e) {
    if (e.getStatusCode() == 404) {
      logger.debug("Project {} doesn't exist", projectId, e);
      return false;
    }

    logger.info("Cannot get project with id {}", projectId, e);
    return false;
  }
  if (ancestry.getAncestor() == null) {
    return false;
  }
  return resolveAccess(ancestry.getAncestor());
}
 
Example 4
Source File: GcloudPubsub.java    From cloud-pubsub-mqtt-proxy with Apache License 2.0 6 votes vote down vote up
/**
 * If there are no more client subscriptions for the given pubsub topic,
 * the subscription gets terminated, and removed from the subscription map.
 *
 * @param subscriptionName an identifier for the subscription we are attempting to terminate.
 * @return true if the subscription has been terminated, and false otherwise.
 */
public synchronized boolean shouldTerminateSubscription(String subscriptionName) {
  if (!activeSubscriptions.contains(subscriptionName)) {
    try {
      pubsub.projects().subscriptions().delete(subscriptionName);
      return true;
    } catch (GoogleJsonResponseException e) {
      if (e.getStatusCode() == RESOURCE_NOT_FOUND) {
        return true;
      }
    } catch (IOException ioe) {
      // we will return false and the pull task will call this method again when rescheduled.
    }
  }
  return false;
}
 
Example 5
Source File: ConditionalRetrievalSample.java    From java-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a test event, pauses while the user modifies the event in the Calendar UI, and then
 * checks if the event has been modified.
 */
private static void run() throws IOException {
  // Create a test event.
  Event event = Utils.createTestEvent(client, "Test Event");
  System.out.println(String.format("Event created: %s", event.getHtmlLink()));

  // Pause while the user modifies the event in the Calendar UI.
  System.out.println("Modify the event's description and hit enter to continue.");
  System.in.read();

  // Fetch the event again if it's been modified.
  Calendar.Events.Get getRequest = client.events().get("primary", event.getId());
  getRequest.setRequestHeaders(new HttpHeaders().setIfNoneMatch(event.getEtag()));
  try {
    event = getRequest.execute();
    System.out.println("The event was modified, retrieved latest version.");
  } catch (GoogleJsonResponseException e) {
    if (e.getStatusCode() == 304) {
      // A 304 status code, "Not modified", indicates that the etags match, and the event has
      // not been modified since we last retrieved it.
      System.out.println("The event was not modified, using local version.");
    } else {
      throw e;
    }
  }
}
 
Example 6
Source File: PubSubWrapper.java    From eip with MIT License 6 votes vote down vote up
/**
 * Sets up a subscription to projects/<code>appName</code>/subscriptions/<code>subName</code>.
 * Ignores error if the subscription already exists.
 * <p/>
 * See <a href="https://cloud.google.com/pubsub/subscriber">cloud.google.com/pubsub/subscriber</a>
 */
Subscription subscribeTopic(String subscriptionName, String topicName) throws IOException {
    String sub = getSubscription(subscriptionName);
    Subscription subscription = new Subscription()
            .setName(sub)
            .setAckDeadlineSeconds(15)
            .setTopic(getTopic(topicName));
    try {
        return pubsub.projects().subscriptions().create(sub, subscription).execute();
    } catch (GoogleJsonResponseException e) {
        if (e.getStatusCode() == HttpURLConnection.HTTP_CONFLICT) {
            return subscription;
        } else {
            throw e;
        }
    }
}
 
Example 7
Source File: ServiceAccountKeyManager.java    From styx with Apache License 2.0 5 votes vote down vote up
public boolean serviceAccountExists(String serviceAccount) throws IOException {
  try {
    iam.projects().serviceAccounts().get("projects/-/serviceAccounts/" + serviceAccount)
        .execute();
    return true;
  } catch (GoogleJsonResponseException e) {
    if (e.getStatusCode() == 404) {
      return false;
    }
    throw e;
  }
}
 
Example 8
Source File: ExampleUtils.java    From beam with Apache License 2.0 5 votes vote down vote up
private static <T> T executeNullIfNotFound(AbstractGoogleClientRequest<T> request)
    throws IOException {
  try {
    return request.execute();
  } catch (GoogleJsonResponseException e) {
    if (e.getStatusCode() == SC_NOT_FOUND) {
      return null;
    } else {
      throw e;
    }
  }
}
 
Example 9
Source File: InjectorUtils.java    From beam with Apache License 2.0 5 votes vote down vote up
/** Create a topic if it doesn't exist. */
public static void createTopic(Pubsub client, String fullTopicName) throws IOException {
  System.out.println("fullTopicName " + fullTopicName);
  try {
    client.projects().topics().get(fullTopicName).execute();
  } catch (GoogleJsonResponseException e) {
    if (e.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) {
      Topic topic = client.projects().topics().create(fullTopicName, new Topic()).execute();
      System.out.printf("Topic %s was created.%n", topic.getName());
    }
  }
}
 
Example 10
Source File: BaseServlet.java    From drivemarks with Apache License 2.0 5 votes vote down vote up
/**
 * Redirects to OAuth2 consent page if user is not logged in.
 * @param req   Request object.
 * @param resp  Response object.
 * @throws IOException 
 */
protected void loginIfRequired(HttpServletRequest req,
    HttpServletResponse resp, GoogleJsonResponseException e) throws IOException {
  if (e.getStatusCode() == 401 || e.getStatusCode() == 403) {
    StringBuffer requestURL = req.getRequestURL();
    if (req.getQueryString() != null) {
        requestURL.append("?").append(req.getQueryString());
    }
    req.getSession().setAttribute(KEY_SESSION_REDIRECT, requestURL.toString());
    resp.sendRedirect("/login");
  }
}
 
Example 11
Source File: CheckBackupAction.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private Operation getExportStatus() throws IOException {
  try {
    return datastoreAdmin.get(backupName).execute();
  } catch (GoogleJsonResponseException e) {
    if (e.getStatusCode() == SC_NOT_FOUND) {
      String message = String.format("Bad backup name %s: %s", backupName, e.getMessage());
      // TODO(b/19081569): Ideally this would return a 2XX error so the task would not be
      // retried but we might abandon backups that start late and haven't yet written to
      // Datastore. We could fix that by replacing this with a two-phase polling strategy.
      throw new BadRequestException(message, e);
    }
    throw e;
  }
}
 
Example 12
Source File: BqClient.java    From digdag with Apache License 2.0 5 votes vote down vote up
boolean datasetExists(String projectId, String datasetId)
        throws IOException
{
    try {
        client.datasets().get(projectId, datasetId).execute();
        return true;
    }
    catch (GoogleJsonResponseException e) {
        if (e.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) {
            return false;
        }
        throw e;
    }
}
 
Example 13
Source File: GcsClient.java    From digdag with Apache License 2.0 5 votes vote down vote up
Optional<StorageObject> stat(String bucket, String object)
        throws IOException
{
    try {
        return Optional.of(client.objects()
                .get(bucket, object)
                .execute());
    }
    catch (GoogleJsonResponseException e) {
        if (e.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) {
            return Optional.absent();
        }
        throw e;
    }
}
 
Example 14
Source File: Authenticator.java    From styx with Apache License 2.0 5 votes vote down vote up
private String getProjectIdOfServiceAccount(String email) throws IOException {
  var request = iam.projects().serviceAccounts().get("projects/-/serviceAccounts/" + email);
  try {
    var serviceAccount = executeWithRetries(request, retryWaitStrategy, retryStopStrategy);
    return serviceAccount.getProjectId();
  } catch (GoogleJsonResponseException e) {
    if (e.getStatusCode() == 404) {
      logger.debug("Service account {} doesn't exist", email, e);
      return null;
    }

    logger.info("Cannot get project id for service account {}", email, e);
    return null;
  }
}
 
Example 15
Source File: InitServlet.java    From cloud-pubsub-samples-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a Cloud Pub/Sub subscription if it doesn't exist.
 *
 * @param client Pubsub client object.
 * @throws IOException when API calls to Cloud Pub/Sub fails.
 */
private void setupSubscription(final Pubsub client) throws IOException {
    String fullName = String.format("projects/%s/subscriptions/%s",
            PubsubUtils.getProjectId(),
            PubsubUtils.getAppSubscriptionName());

    try {
        client.projects().subscriptions().get(fullName).execute();
    } catch (GoogleJsonResponseException e) {
        if (e.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) {
            // Create the subscription if it doesn't exist
            String fullTopicName = String.format("projects/%s/topics/%s",
                    PubsubUtils.getProjectId(),
                    PubsubUtils.getAppTopicName());
            PushConfig pushConfig = new PushConfig()
                    .setPushEndpoint(PubsubUtils.getAppEndpointUrl());
            Subscription subscription = new Subscription()
                    .setTopic(fullTopicName)
                    .setPushConfig(pushConfig);
            client.projects().subscriptions()
                    .create(fullName, subscription)
                    .execute();
        } else {
            throw e;
        }
    }
}
 
Example 16
Source File: ExampleUtils.java    From deployment-examples with MIT License 5 votes vote down vote up
private static <T> T executeNullIfNotFound(AbstractGoogleClientRequest<T> request)
    throws IOException {
  try {
    return request.execute();
  } catch (GoogleJsonResponseException e) {
    if (e.getStatusCode() == SC_NOT_FOUND) {
      return null;
    } else {
      throw e;
    }
  }
}
 
Example 17
Source File: YoutubeDataCollector.java    From streams with Apache License 2.0 5 votes vote down vote up
/**
 * Looks at the status code of the expception.  If the code indicates that the request should be retried,
 * it executes the back off strategy and returns true.
 * @param gjre
 * @param backOff
 * @return returns true if the error code of the exception indicates the request should be retried.
 */
public boolean backoffAndIdentifyIfRetry(GoogleJsonResponseException gjre, BackOffStrategy backOff) throws BackOffException {
  boolean tryAgain = false;

  switch (gjre.getStatusCode()) {
    case 400 :
      LOGGER.warn("Bad Request  : {}",  gjre);
      break;
    case 401 :
      LOGGER.warn("Invalid Credentials : {}", gjre);
      break;
    case 403 :
      LOGGER.warn("Possible rate limit exception. Retrying. : {}", gjre.getMessage());
      backOff.backOff();
      tryAgain = true;
      break;
    case 503 :
      LOGGER.warn("Google Backend Service Error : {}", gjre);
      break;
    default:
      LOGGER.warn("Google Service returned error : {}", gjre);
      tryAgain = true;
      backOff.backOff();
      break;
  }

  return tryAgain;
}
 
Example 18
Source File: GcpUtil.java    From styx with Apache License 2.0 4 votes vote down vote up
public static boolean isPermissionDenied(GoogleJsonResponseException e) {
  return e.getStatusCode() == 403 && Optional.ofNullable(e.getDetails())
      .map(GcpUtil::isPermissionDenied)
      .orElse(false);
}
 
Example 19
Source File: ConditionalModificationSample.java    From java-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a test event, pauses while the user modifies the event in the Calendar UI, and then
 * updates the event with a new location, ensure that the user's changes aren't overwritten.
 */
private static void run() throws IOException {
  // Create a test event.
  Event event = Utils.createTestEvent(client, "Test Event");
  System.out.println(String.format("Event created: %s", event.getHtmlLink()));

  // Pause while the user modifies the event in the Calendar UI.
  System.out.println("Modify the event's description and hit enter to continue.");
  System.in.read();

  // Modify the local copy of the event.
  event.setSummary("Updated Test Event");

  // Update the event, making sure that we don't overwrite other changes.
  int numAttempts = 0;
  boolean isUpdated = false;
  do {
    Calendar.Events.Update request = client.events().update("primary", event.getId(), event);
    request.setRequestHeaders(new HttpHeaders().setIfMatch(event.getEtag()));
    try {
      event = request.execute();
      isUpdated = true;
    } catch (GoogleJsonResponseException e) {
      if (e.getStatusCode() == 412) {
        // A 412 status code, "Precondition failed", indicates that the etag values didn't
        // match, and the event was updated on the server since we last retrieved it. Use
        // {@link Calendar.Events.Get} to retrieve the latest version.
        Event latestEvent = client.events().get("primary", event.getId()).execute();

        // You may want to have more complex logic here to resolve conflicts. In this sample we're
        // simply overwriting the summary.
        latestEvent.setSummary(event.getSummary());
        event = latestEvent;
      } else {
        throw e;
      }
    }
    numAttempts++;
  } while (!isUpdated && numAttempts <= MAX_UPDATE_ATTEMPTS);

  if (isUpdated) {
    System.out.println("Event updated.");
  } else {
    System.out.println(String.format("Failed to update event after %d attempts.", numAttempts));
  }
}
 
Example 20
Source File: ApiErrorExtractor.java    From hadoop-connectors with Apache License 2.0 2 votes vote down vote up
/**
 * Returns HTTP status code from the given exception.
 *
 * <p>Note: GoogleJsonResponseException.getStatusCode() method is marked final therefore it cannot
 * be mocked using Mockito. We use this helper so that we can override it in tests.
 */
protected int getHttpStatusCode(GoogleJsonResponseException e) {
  return e.getStatusCode();
}