Java Code Examples for com.google.api.client.util.Preconditions#checkState()

The following examples show how to use com.google.api.client.util.Preconditions#checkState() . 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: PsqlReplicationCheck.java    From dbeam with Apache License 2.0 6 votes vote down vote up
static Instant queryReplication(final Connection connection, final String query)
    throws SQLException {
  final ResultSet resultSet = connection.createStatement().executeQuery(query);
  Preconditions.checkState(
      resultSet.next(),
      "Replication query returned empty results, consider using jdbc-avro-job instead");
  Instant lastReplication =
      Preconditions.checkNotNull(
              resultSet.getTimestamp("last_replication"),
              "Empty last_replication, consider using jdbc-avro-job instead")
          .toInstant();
  Duration replicationDelay = Duration.ofSeconds(resultSet.getLong("replication_delay"));
  LOGGER.info(
      "Psql replication check lastReplication={} replicationDelay={}",
      lastReplication,
      replicationDelay);
  return lastReplication;
}
 
Example 2
Source File: DerEncoder.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
static byte[] encode(byte[] signature) {
  // expect the signature to be 64 bytes long
  Preconditions.checkState(signature.length == 64);

  byte[] int1 = new BigInteger(1, Arrays.copyOfRange(signature, 0, 32)).toByteArray();
  byte[] int2 = new BigInteger(1, Arrays.copyOfRange(signature, 32, 64)).toByteArray();
  byte[] der = new byte[6 + int1.length + int2.length];

  // Mark that this is a signature object
  der[0] = DER_TAG_SIGNATURE_OBJECT;
  der[1] = (byte) (der.length - 2);

  // Start ASN1 integer and write the first 32 bits
  der[2] = DER_TAG_ASN1_INTEGER;
  der[3] = (byte) int1.length;
  System.arraycopy(int1, 0, der, 4, int1.length);

  // Start ASN1 integer and write the second 32 bits
  int offset = int1.length + 4;
  der[offset] = DER_TAG_ASN1_INTEGER;
  der[offset + 1] = (byte) int2.length;
  System.arraycopy(int2, 0, der, offset + 2, int2.length);

  return der;
}
 
Example 3
Source File: ApacheHttpRequest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
@Override
public LowLevelHttpResponse execute() throws IOException {
  if (getStreamingContent() != null) {
    Preconditions.checkState(
        request instanceof HttpEntityEnclosingRequest,
        "Apache HTTP client does not support %s requests with content.",
        request.getRequestLine().getMethod());
    ContentEntity entity = new ContentEntity(getContentLength(), getStreamingContent());
    entity.setContentEncoding(getContentEncoding());
    entity.setContentType(getContentType());
    if (getContentLength() == -1) {
      entity.setChunked(true);
    }
    ((HttpEntityEnclosingRequest) request).setEntity(entity);
  }
  return new ApacheHttpResponse(request, httpClient.execute(request));
}
 
Example 4
Source File: ApacheHttpRequest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
@Override
public LowLevelHttpResponse execute() throws IOException {
  if (getStreamingContent() != null) {
    Preconditions.checkState(
        request instanceof HttpEntityEnclosingRequest,
        "Apache HTTP client does not support %s requests with content.",
        request.getRequestLine().getMethod());
    ContentEntity entity = new ContentEntity(getContentLength(), getStreamingContent());
    entity.setContentEncoding(getContentEncoding());
    entity.setContentType(getContentType());
    if (getContentLength() == -1) {
      entity.setChunked(true);
    }
    ((HttpEntityEnclosingRequest) request).setEntity(entity);
  }
  request.setConfig(requestConfig.build());
  return new ApacheHttpResponse(request, httpClient.execute(request));
}
 
Example 5
Source File: DatastoreIndexesUpdatedStatusHandler.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
@Override
public Object handleStatus(IStatus status, Object source) throws CoreException {
  Preconditions.checkArgument(source instanceof DatastoreIndexUpdateData);
  DatastoreIndexUpdateData update = (DatastoreIndexUpdateData) source;
  Preconditions.checkState(update.datastoreIndexesAutoXml != null);

  if (DebugUITools.isPrivate(update.configuration)) {
    return null;
  }

  IWorkbenchPage page = getActivePage();
  Shell shell = page.getWorkbenchWindow().getShell();
  String[] buttonLabels =
      new String[] {Messages.getString("REVIEW_CHANGES"), Messages.getString("IGNORE_CHANGES")};
  MessageDialog dialog =
      new MessageDialog(shell, Messages.getString("REVIEW_DATASTORE_INDEXES_UPDATE_TITLE"), //$NON-NLS-1$
          null, Messages.getString("REVIEW_DATASTORE_INDEXES_UPDATE_MESSAGE"), //$NON-NLS-1$
          MessageDialog.QUESTION, 0, buttonLabels);
  if (dialog.open() != 0) {
    return null;
  }

  // create an empty source file if it doesn't exist
  IFile datastoreIndexesXml = update.datastoreIndexesXml;
  if (datastoreIndexesXml == null) {
    IProject project = update.module.getProject();
    try {
      datastoreIndexesXml = createNewDatastoreIndexesXml(project, null /* monitor */);
    } catch (CoreException ex) {
      logger.log(Level.SEVERE, "could not create empty datastore-indexes.xml in " + project, ex); //$NON-NLS-1$
    }
  }

  CompareEditorInput input = new GeneratedDatastoreIndexesUpdateEditorInput(page,
      datastoreIndexesXml, update.datastoreIndexesAutoXml.toFile());
  CompareUI.openCompareEditor(input);
  return null;
}
 
Example 6
Source File: DatastoreIndexesUpdatedStatusHandler.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
/** Find the current window page; should never be {@code null}. */
private IWorkbenchPage getActivePage() {
  IWorkbench workbench = PlatformUI.getWorkbench();
  Preconditions.checkState(workbench.getWorkbenchWindowCount() > 0);
  IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
  if (window == null) {
    window = workbench.getWorkbenchWindows()[0];
  }
  return window.getActivePage();
}
 
Example 7
Source File: Xml.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Parses the namespaces declared on the current element into the namespace dictionary.
 *
 * @param parser XML pull parser
 * @param namespaceDictionary namespace dictionary
 */
private static void parseNamespacesForElement(
    XmlPullParser parser, XmlNamespaceDictionary namespaceDictionary)
    throws XmlPullParserException {
  int eventType = parser.getEventType();
  Preconditions.checkState(
      eventType == XmlPullParser.START_TAG,
      "expected start of XML element, but got something else (event type %s)",
      eventType);
  int depth = parser.getDepth();
  int nsStart = parser.getNamespaceCount(depth - 1);
  int nsEnd = parser.getNamespaceCount(depth);
  for (int i = nsStart; i < nsEnd; i++) {
    String namespace = parser.getNamespaceUri(i);
    // if namespace isn't already in our dictionary, add it now
    if (namespaceDictionary.getAliasForUri(namespace) == null) {
      String prefix = parser.getNamespacePrefix(i);
      String originalAlias = prefix == null ? "" : prefix;
      // find an available alias
      String alias = originalAlias;
      int suffix = 1;
      while (namespaceDictionary.getUriForAlias(alias) != null) {
        suffix++;
        alias = originalAlias + suffix;
      }
      namespaceDictionary.set(alias, namespace);
    }
  }
}
 
Example 8
Source File: PCoAnalysis.java    From dataflow-java with Apache License 2.0 5 votes vote down vote up
public static GraphResult fromString(String tsv) {
  Preconditions.checkNotNull(tsv);
  String[] tokens = tsv.split("[\\s\t]+");
  Preconditions.checkState(3 == tokens.length,
      "Expected three values in serialized GraphResult but found %d", tokens.length);
  return new GraphResult(tokens[0],
      Double.parseDouble(tokens[1]),
      Double.parseDouble(tokens[2]));
}
 
Example 9
Source File: AppEngineServletUtils.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Return the user id for the currently logged in user.
 */
static final String getUserId() {
  UserService userService = UserServiceFactory.getUserService();
  User loggedIn = userService.getCurrentUser();
  Preconditions.checkState(loggedIn != null, "This servlet requires the user to be logged in.");
  return loggedIn.getUserId();
}
 
Example 10
Source File: GoogleAuthorizationCodeFlow.java    From google-api-java-client with Apache License 2.0 4 votes vote down vote up
@Override
public Builder setScopes(Collection<String> scopes) {
  Preconditions.checkState(!scopes.isEmpty());
  return (Builder) super.setScopes(scopes);
}
 
Example 11
Source File: BatchRequest.java    From google-api-java-client with Apache License 2.0 4 votes vote down vote up
/**
 * Executes all queued HTTP requests in a single call, parses the responses and invokes callbacks.
 *
 * <p>
 * Calling {@link #execute()} executes and clears the queued requests. This means that the
 * {@link BatchRequest} object can be reused to {@link #queue} and {@link #execute()} requests
 * again.
 * </p>
 */
public void execute() throws IOException {
  boolean retryAllowed;
  Preconditions.checkState(!requestInfos.isEmpty());

  // Log a warning if the user is using the global batch endpoint. In the future, we can turn this
  // into a preconditions check.
  if (GLOBAL_BATCH_ENDPOINT.equals(this.batchUrl.toString())) {
    LOGGER.log(Level.WARNING, GLOBAL_BATCH_ENDPOINT_WARNING);
  }

  HttpRequest batchRequest = requestFactory.buildPostRequest(this.batchUrl, null);
  // NOTE: batch does not support gzip encoding
  HttpExecuteInterceptor originalInterceptor = batchRequest.getInterceptor();
  batchRequest.setInterceptor(new BatchInterceptor(originalInterceptor));
  int retriesRemaining = batchRequest.getNumberOfRetries();

  do {
    retryAllowed = retriesRemaining > 0;
    MultipartContent batchContent = new MultipartContent();
    batchContent.getMediaType().setSubType("mixed");
    int contentId = 1;
    for (RequestInfo<?, ?> requestInfo : requestInfos) {
      batchContent.addPart(new MultipartContent.Part(
          new HttpHeaders().setAcceptEncoding(null).set("Content-ID", contentId++),
          new HttpRequestContent(requestInfo.request)));
    }
    batchRequest.setContent(batchContent);
    HttpResponse response = batchRequest.execute();
    BatchUnparsedResponse batchResponse;
    try {
      // Find the boundary from the Content-Type header.
      String boundary = "--" + response.getMediaType().getParameter("boundary");

      // Parse the content stream.
      InputStream contentStream = response.getContent();
      batchResponse =
          new BatchUnparsedResponse(contentStream, boundary, requestInfos, retryAllowed);

      while (batchResponse.hasNext) {
        batchResponse.parseNextResponse();
      }
    } finally {
      response.disconnect();
    }

    List<RequestInfo<?, ?>> unsuccessfulRequestInfos = batchResponse.unsuccessfulRequestInfos;
    if (!unsuccessfulRequestInfos.isEmpty()) {
      requestInfos = unsuccessfulRequestInfos;
    } else {
      break;
    }
    retriesRemaining--;
  } while (retryAllowed);
  requestInfos.clear();
}
 
Example 12
Source File: MockHttpTransport.java    From google-http-java-client with Apache License 2.0 3 votes vote down vote up
/**
 * Sets the {@link MockLowLevelHttpRequest} that will be returned by {@link #buildRequest}, if
 * non-{@code null}. If {@code null}, {@link #buildRequest} will create a new {@link
 * MockLowLevelHttpRequest} arguments.
 *
 * <p>Note that the user can set a low level HTTP Request only if a low level HTTP response has
 * not been set on this instance.
 *
 * @since 1.18
 */
public final Builder setLowLevelHttpRequest(MockLowLevelHttpRequest lowLevelHttpRequest) {
  Preconditions.checkState(
      lowLevelHttpResponse == null,
      "Cannnot set a low level HTTP request when a low level HTTP response has been set.");
  this.lowLevelHttpRequest = lowLevelHttpRequest;
  return this;
}
 
Example 13
Source File: MockHttpTransport.java    From google-http-java-client with Apache License 2.0 3 votes vote down vote up
/**
 * Sets the {@link MockLowLevelHttpResponse} that will be the result when the {@link
 * MockLowLevelHttpRequest} returned by {@link #buildRequest} is executed. Note that the
 * response can be set only the caller has not provided a {@link MockLowLevelHttpRequest} via
 * {@link #setLowLevelHttpRequest}.
 *
 * @throws IllegalStateException if the caller has already set a {@link LowLevelHttpRequest} in
 *     this instance
 * @since 1.18
 */
public final Builder setLowLevelHttpResponse(MockLowLevelHttpResponse lowLevelHttpResponse) {
  Preconditions.checkState(
      lowLevelHttpRequest == null,
      "Cannot set a low level HTTP response when a low level HTTP request has been set.");
  this.lowLevelHttpResponse = lowLevelHttpResponse;
  return this;
}