Java Code Examples for com.google.api.client.http.HttpStatusCodes#STATUS_CODE_NOT_FOUND

The following examples show how to use com.google.api.client.http.HttpStatusCodes#STATUS_CODE_NOT_FOUND . 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: BqClient.java    From digdag with Apache License 2.0 6 votes vote down vote up
void deleteDataset(String projectId, String datasetId)
        throws IOException
{
    if (datasetExists(projectId, datasetId)) {
        deleteTables(projectId, datasetId);

        try {
            client.datasets().delete(projectId, datasetId).execute();
        }
        catch (GoogleJsonResponseException e) {
            if (e.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) {
                // Already deleted
                return;
            }
            throw e;
        }
    }
}
 
Example 2
Source File: InitServlet.java    From cloud-pubsub-samples-java with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a Cloud Pub/Sub topic if it doesn't exist.
 *
 * @param client Pubsub client object.
 * @throws IOException when API calls to Cloud Pub/Sub fails.
 */
private void setupTopic(final Pubsub client) throws IOException {
    String fullName = String.format("projects/%s/topics/%s",
            PubsubUtils.getProjectId(),
            PubsubUtils.getAppTopicName());

    try {
        client.projects().topics().get(fullName).execute();
    } catch (GoogleJsonResponseException e) {
        if (e.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) {
            // Create the topic if it doesn't exist
            client.projects().topics()
                    .create(fullName, new Topic())
                    .execute();
        } else {
            throw e;
        }
    }
}
 
Example 3
Source File: InjectorUtils.java    From deployment-examples with MIT License 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 4
Source File: ForceOAuthClient.java    From salesforce-jdbc with MIT License 5 votes vote down vote up
private boolean isBadTokenError(HttpResponseException e) {
    return ((e.getStatusCode() == HttpStatusCodes.STATUS_CODE_FORBIDDEN)
            && StringUtils.equalsAnyIgnoreCase(e.getContent(),
            BAD_TOKEN_SF_ERROR_CODE, MISSING_TOKEN_SF_ERROR_CODE, WRONG_ORG_SF_ERROR_CODE))
            ||
            (e.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND &&
                    StringUtils.equalsIgnoreCase(e.getContent(), BAD_ID_SF_ERROR_CODE));
}
 
Example 5
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 6
Source File: BqClient.java    From digdag with Apache License 2.0 5 votes vote down vote up
void deleteTable(String projectId, String datasetId, String tableId)
        throws IOException
{
    try {
        client.tables().delete(projectId, datasetId, tableId).execute();
    }
    catch (GoogleJsonResponseException e) {
        if (e.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) {
            // Already deleted
            return;
        }
        throw e;
    }
}
 
Example 7
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 8
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 9
Source File: GcpUtil.java    From digdag with Apache License 2.0 5 votes vote down vote up
static boolean tableExists(Bigquery bq, String projectId, String datasetId, String tableId)
        throws IOException
{
    try {
        bq.tables().get(projectId, datasetId, tableId).execute();
        return true;
    }
    catch (GoogleJsonResponseException e) {
        if (e.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) {
            return false;
        }
        throw e;
    }
}
 
Example 10
Source File: GcpUtil.java    From digdag with Apache License 2.0 5 votes vote down vote up
static boolean datasetExists(Bigquery bq, String projectId, String datasetId)
        throws IOException
{
    try {
        bq.datasets().get(projectId, datasetId).execute();
        return true;
    }
    catch (GoogleJsonResponseException e) {
        if (e.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) {
            return false;
        }
        throw e;
    }
}
 
Example 11
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 12
Source File: DefaultCredentialProvider.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
@Override
protected TokenResponse executeRefreshToken() throws IOException {
  GenericUrl tokenUrl = new GenericUrl(getTokenServerEncodedUrl());
  HttpRequest request = getTransport().createRequestFactory().buildGetRequest(tokenUrl);
  JsonObjectParser parser = new JsonObjectParser(getJsonFactory());
  request.setParser(parser);
  request.getHeaders().set("Metadata-Flavor", "Google");
  request.setThrowExceptionOnExecuteError(false);
  HttpResponse response = request.execute();
  int statusCode = response.getStatusCode();
  if (statusCode == HttpStatusCodes.STATUS_CODE_OK) {
    InputStream content = response.getContent();
    if (content == null) {
      // Throw explicitly rather than allow a later null reference as default mock
      // transports return success codes with empty contents.
      throw new IOException("Empty content from metadata token server request.");
    }
    return parser.parseAndClose(content, response.getContentCharset(), TokenResponse.class);
  }
  if (statusCode == HttpStatusCodes.STATUS_CODE_NOT_FOUND) {
    throw new IOException(String.format("Error code %s trying to get security access token from"
        + " Compute Engine metadata for the default service account. This may be because"
        + " the virtual machine instance does not have permission scopes specified.",
        statusCode));
  }
  throw new IOException(String.format("Unexpected Error code %s trying to get security access"
      + " token from Compute Engine metadata for the default service account: %s", statusCode,
      response.parseAsString()));
}
 
Example 13
Source File: ForceOAuthClient.java    From salesforce-jdbc with MIT License 4 votes vote down vote up
private boolean isForceInternalError(HttpResponseException e) {
    return e.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND &&
            StringUtils.equalsIgnoreCase(e.getContent(), INTERNAL_SERVER_ERROR_SF_ERROR_CODE);
}
 
Example 14
Source File: TestPublisher.java    From play-work with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args)
    throws IOException, GeneralSecurityException {

  Pubsub pubsubClient = ServiceAccountConfiguration.createPubsubClient(
      Settings.getSettings().getServiceAccountEmail(),
      Settings.getSettings().getServiceAccountP12KeyPath());
  String topicName = Settings.getSettings().getTopicName();

  try {
    Topic topic = pubsubClient
        .projects()
        .topics()
        .get(topicName)
        .execute();

    LOG.info("The topic " + topicName + " exists: " + topic.toPrettyString());
  } catch (HttpResponseException e) {
    if (e.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) {
      // The topic doesn't exist
      LOG.info("The topic " + topicName + " doesn't exist, creating it");
      
      // TODO(kirillov): add explicit error handling here
      pubsubClient
          .projects()
          .topics()
          .create(topicName, new Topic())
          .execute();
      LOG.info("The topic " + topicName + " created");
    }
  }

  ImmutableList.Builder<PubsubMessage> listBuilder = ImmutableList.builder();

  EmmPubsub.MdmPushNotification mdmPushNotification = EmmPubsub.MdmPushNotification.newBuilder()
      .setEnterpriseId("12321321")
      .setEventNotificationSentTimestampMillis(System.currentTimeMillis())
      .addProductApprovalEvent(EmmPubsub.ProductApprovalEvent.newBuilder()
          .setApproved(EmmPubsub.ProductApprovalEvent.ApprovalStatus.UNAPPROVED)
          .setProductId("app:com.android.chrome"))
      .build();

  PublishRequest publishRequest = new PublishRequest()
      .setMessages(ImmutableList.of(new PubsubMessage()
          .encodeData(mdmPushNotification.toByteArray())));

  LOG.info("Publishing a request: " + publishRequest.toPrettyString());

  pubsubClient
      .projects()
      .topics()
      .publish(topicName, publishRequest)
      .execute();
}
 
Example 15
Source File: PushSubscriber.java    From play-work with Apache License 2.0 4 votes vote down vote up
/**
 * Verifies that the subscription with the name defined in settings file actually exists and 
 * points to a correct topic defined in the same settings file. If the subscription doesn't
 * exist, it will be created.
 */
private static void ensureSubscriptionExists(Pubsub client) throws IOException {
  // First we check if the subscription with this name actually exists.
  Subscription subscription = null;

  String topicName = Settings.getSettings().getTopicName();
  String subName = Settings.getSettings().getSubscriptionName();

  LOG.info("Will be using topic name: " + topicName + ", subscription name: " + subName);

  try {
    LOG.info("Trying to get subscription named " + subName);
    subscription = client
        .projects()
        .subscriptions()
        .get(subName)
        .execute();
    
    Preconditions.checkArgument(
        subscription.getTopic().equals(topicName),
        "Subscription %s already exists but points to a topic %s and not %s." +
            "Please specify a different subscription name or delete this subscription",
        subscription.getName(),
        subscription.getTopic(),
        topicName);

    LOG.info("Will be re-using existing subscription: " + subscription.toPrettyString());
  } catch (HttpResponseException e) {

    // Subscription not found
    if (e.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) {
      LOG.info("Subscription doesn't exist, will try to create " + subName);

      // Creating subscription
      subscription = client
          .projects()
          .subscriptions()
          .create(subName, new Subscription()
              .setTopic(topicName)   // Name of the topic it subscribes to
              .setAckDeadlineSeconds(600)
              .setPushConfig(new PushConfig()
                  // FQDN with valid SSL certificate
                  .setPushEndpoint(Settings.getSettings().getPushEndpoint())))
          .execute();

      LOG.info("Created: " + subscription.toPrettyString());
    }
  }
}