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

The following examples show how to use com.google.api.client.util.Preconditions#checkArgument() . 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: ReportProcessor.java    From aw-reporting with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor.
 *
 * @param reportRowsSetSize the size of the set parsed before persisting to the database.
 * @param numberOfReportProcessors the number of threads used to process reports.
 * @param authenticator to create the AdWords session.
 * @throws ReportProcessingException
 */
@Autowired
public ReportProcessor(
    Integer reportRowsSetSize, Integer numberOfReportProcessors, Authenticator authenticator)
    throws ReportProcessingException {
  Preconditions.checkNotNull(reportRowsSetSize, "ReportRowSetSize cannot be null!");
  Preconditions.checkNotNull(
      numberOfReportProcessors, "NumberOfReportProcessors cannot be null!");
  Preconditions.checkNotNull(authenticator, "Authenticator cannot be null!");
  Preconditions.checkArgument(reportRowsSetSize > 0, "ReportRowSetSize must be > 0");
  Preconditions.checkArgument(
      numberOfReportProcessors > 0, "NumberOfReportProcessors must be > 0");
  
  this.reportRowsSetSize = reportRowsSetSize.intValue();
  this.numberOfReportProcessors = numberOfReportProcessors.intValue();

  try {
    sessionBuilder = authenticator.authenticate();
  } catch (OAuthException e) {
    throw new ReportProcessingException("Failed to authenticate AdWordsSession.", e);
  }
}
 
Example 2
Source File: LinkHeaderParser.java    From android-oauth-client with Apache License 2.0 5 votes vote down vote up
@Override
public Object parseAndClose(Reader reader, Type dataType) throws IOException {
    Preconditions.checkArgument(
            dataType instanceof Class<?>, "dataType has to be of type Class<?>");

    Object newInstance = Types.newInstance((Class<?>) dataType);
    parse(new BufferedReader(reader), newInstance);
    return newInstance;
}
 
Example 3
Source File: OpenCensusUtils.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Records a message event of a certain {@link MessageEvent.Type}. This method is package
 * protected since {@link MessageEvent} might be deprecated in future releases.
 *
 * @param span The {@code span} in which the event occurs.
 * @param size Size of the message.
 * @param eventType The {@code NetworkEvent.Type} of the message event.
 */
@VisibleForTesting
static void recordMessageEvent(Span span, long size, Type eventType) {
  Preconditions.checkArgument(span != null, "span should not be null.");
  if (size < 0) {
    size = 0;
  }
  MessageEvent event =
      MessageEvent.builder(eventType, idGenerator.getAndIncrement())
          .setUncompressedMessageSize(size)
          .build();
  span.addMessageEvent(event);
}
 
Example 4
Source File: OpenCensusUtils.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Propagate information of current tracing context. This information will be injected into HTTP
 * header.
 *
 * @param span the span to be propagated.
 * @param headers the headers used in propagation.
 */
public static void propagateTracingContext(Span span, HttpHeaders headers) {
  Preconditions.checkArgument(span != null, "span should not be null.");
  Preconditions.checkArgument(headers != null, "headers should not be null.");
  if (propagationTextFormat != null && propagationTextFormatSetter != null) {
    if (!span.equals(BlankSpan.INSTANCE)) {
      propagationTextFormat.inject(span.getContext(), headers, propagationTextFormatSetter);
    }
  }
}
 
Example 5
Source File: HttpMediaType.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the media parameter to the specified value.
 *
 * @param name case-insensitive name of the parameter
 * @param value value of the parameter or {@code null} to remove
 */
public HttpMediaType setParameter(String name, String value) {
  if (value == null) {
    removeParameter(name);
    return this;
  }

  Preconditions.checkArgument(
      TOKEN_REGEX.matcher(name).matches(), "Name contains reserved characters");
  cachedBuildResult = null;
  parameters.put(name.toLowerCase(Locale.US), value);
  return this;
}
 
Example 6
Source File: GooglePublicKeysManager.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Forces a refresh of the public certificates downloaded from {@link #getPublicCertsEncodedUrl}.
 *
 * <p>
 * This method is automatically called from {@link #getPublicKeys()} if the public keys have not
 * yet been initialized or if the expiration time is very close, so normally this doesn't need to
 * be called. Only call this method to explicitly force the public keys to be updated.
 * </p>
 */
public GooglePublicKeysManager refresh() throws GeneralSecurityException, IOException {
  lock.lock();
  try {
    publicKeys = new ArrayList<PublicKey>();
    // HTTP request to public endpoint
    CertificateFactory factory = SecurityUtils.getX509CertificateFactory();
    HttpResponse certsResponse = transport.createRequestFactory()
        .buildGetRequest(new GenericUrl(publicCertsEncodedUrl)).execute();
    expirationTimeMilliseconds =
        clock.currentTimeMillis() + getCacheTimeInSec(certsResponse.getHeaders()) * 1000;
    // parse each public key in the JSON response
    JsonParser parser = jsonFactory.createJsonParser(certsResponse.getContent());
    JsonToken currentToken = parser.getCurrentToken();
    // token is null at start, so get next token
    if (currentToken == null) {
      currentToken = parser.nextToken();
    }
    Preconditions.checkArgument(currentToken == JsonToken.START_OBJECT);
    try {
      while (parser.nextToken() != JsonToken.END_OBJECT) {
        parser.nextToken();
        String certValue = parser.getText();
        X509Certificate x509Cert = (X509Certificate) factory.generateCertificate(
            new ByteArrayInputStream(StringUtils.getBytesUtf8(certValue)));
        publicKeys.add(x509Cert.getPublicKey());
      }
      publicKeys = Collections.unmodifiableList(publicKeys);
    } finally {
      parser.close();
    }
    return this;
  } finally {
    lock.unlock();
  }
}
 
Example 7
Source File: HttpMediaType.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the (main) media type, for example {@code "text"}.
 *
 * @param type main/major media type
 */
public HttpMediaType setType(String type) {
  Preconditions.checkArgument(
      TYPE_REGEX.matcher(type).matches(), "Type contains reserved characters");
  this.type = type;
  cachedBuildResult = null;
  return this;
}
 
Example 8
Source File: UrlFetchTransport.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
@Override
protected UrlFetchRequest buildRequest(String method, String url) throws IOException {
  Preconditions.checkArgument(supportsMethod(method), "HTTP method %s not supported", method);
  HTTPMethod httpMethod;
  if (method.equals(HttpMethods.DELETE)) {
    httpMethod = HTTPMethod.DELETE;
  } else if (method.equals(HttpMethods.GET)) {
    httpMethod = HTTPMethod.GET;
  } else if (method.equals(HttpMethods.HEAD)) {
    httpMethod = HTTPMethod.HEAD;
  } else if (method.equals(HttpMethods.POST)) {
    httpMethod = HTTPMethod.POST;
  } else if (method.equals(HttpMethods.PATCH)) {
    httpMethod = HTTPMethod.PATCH;
  } else {
    httpMethod = HTTPMethod.PUT;
  }
  // fetch options
  FetchOptions fetchOptions =
      FetchOptions.Builder.doNotFollowRedirects().disallowTruncate().validateCertificate();
  switch (certificateValidationBehavior) {
    case VALIDATE:
      fetchOptions.validateCertificate();
      break;
    case DO_NOT_VALIDATE:
      fetchOptions.doNotValidateCertificate();
      break;
    default:
      break;
  }
  return new UrlFetchRequest(fetchOptions, httpMethod, url);
}
 
Example 9
Source File: ComputeCredential.java    From google-api-java-client with Apache License 2.0 4 votes vote down vote up
@Override
public Builder setClientAuthentication(HttpExecuteInterceptor clientAuthentication) {
  Preconditions.checkArgument(clientAuthentication == null);
  return this;
}
 
Example 10
Source File: HttpRequest.java    From google-http-java-client with Apache License 2.0 4 votes vote down vote up
/**
 * Sets the timeout in milliseconds to send POST/PUT data or {@code 0} for an infinite timeout.
 *
 * @since 1.27
 */
public HttpRequest setWriteTimeout(int writeTimeout) {
  Preconditions.checkArgument(writeTimeout >= 0);
  this.writeTimeout = writeTimeout;
  return this;
}
 
Example 11
Source File: DownloadSetting.java    From aw-reporting with Apache License 2.0 4 votes vote down vote up
public void setNumThreads(Integer numThreads) {
  Preconditions.checkNotNull(numThreads, "numThreads cannot be null.");
  Preconditions.checkArgument(numThreads > 0, "numThreads must be positive.");
  this.numThreads = numThreads.intValue();
}
 
Example 12
Source File: DownloadSetting.java    From aw-reporting with Apache License 2.0 4 votes vote down vote up
public void setBackoffInterval(Integer backoffInterval) {
  Preconditions.checkNotNull(backoffInterval, "backoffInterval cannot be null.");
  Preconditions.checkArgument(backoffInterval >= 0, "backoffInterval must be non-negative.");
  this.backoffInterval = backoffInterval.intValue();
}
 
Example 13
Source File: StorageServiceAccountSample.java    From cloud-storage-docs-xml-api-examples with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
  try {
    try {
      httpTransport = GoogleNetHttpTransport.newTrustedTransport();
      // Check for valid setup.
      Preconditions.checkArgument(!SERVICE_ACCOUNT_EMAIL.startsWith("[["),
          "Please enter your service account e-mail from the Google APIs "
          + "Console to the SERVICE_ACCOUNT_EMAIL constant in %s",
          StorageServiceAccountSample.class.getName());
      Preconditions.checkArgument(!BUCKET_NAME.startsWith("[["),
          "Please enter your desired Google Cloud Storage bucket name "
          + "to the BUCKET_NAME constant in %s", StorageServiceAccountSample.class.getName());
      String p12Content = Files.readFirstLine(new File("key.p12"), Charset.defaultCharset());
      Preconditions.checkArgument(!p12Content.startsWith("Please"), p12Content);

      //[START snippet]
      // Build a service account credential.
      GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
          .setJsonFactory(JSON_FACTORY)
          .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
          .setServiceAccountScopes(Collections.singleton(STORAGE_SCOPE))
          .setServiceAccountPrivateKeyFromP12File(new File("key.p12"))
          .build();

      // Set up and execute a Google Cloud Storage request.
      String URI = "https://storage.googleapis.com/" + BUCKET_NAME;
      HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);
      GenericUrl url = new GenericUrl(URI);
      HttpRequest request = requestFactory.buildGetRequest(url);
      HttpResponse response = request.execute();
      String content = response.parseAsString();
     //[END snippet]

      // Instantiate transformer input.
      Source xmlInput = new StreamSource(new StringReader(content));
      StreamResult xmlOutput = new StreamResult(new StringWriter());

      // Configure transformer.
      Transformer transformer = TransformerFactory.newInstance().newTransformer(); // An identity
                                                                                   // transformer
      transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "testing.dtd");
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
      transformer.transform(xmlInput, xmlOutput);

      // Pretty print the output XML.
      System.out.println("\nBucket listing for " + BUCKET_NAME + ":\n");
      System.out.println(xmlOutput.getWriter().toString());
      System.exit(0);

    } catch (IOException e) {
      System.err.println(e.getMessage());
    }
  } catch (Throwable t) {
    t.printStackTrace();
  }
  System.exit(1);
}
 
Example 14
Source File: MediaHttpUploader.java    From google-api-java-client with Apache License 2.0 3 votes vote down vote up
/**
 * Sets the maximum size of individual chunks that will get uploaded by single HTTP requests. The
 * default value is {@link #DEFAULT_CHUNK_SIZE}.
 *
 * <p>
 * The minimum allowable value is {@link #MINIMUM_CHUNK_SIZE} and the specified chunk size must be
 * a multiple of {@link #MINIMUM_CHUNK_SIZE}.
 * </p>
 */
public MediaHttpUploader setChunkSize(int chunkSize) {
  Preconditions.checkArgument(chunkSize > 0 && chunkSize % MINIMUM_CHUNK_SIZE == 0, "chunkSize"
      + " must be a positive multiple of " + MINIMUM_CHUNK_SIZE + ".");
  this.chunkSize = chunkSize;
  return this;
}
 
Example 15
Source File: MediaHttpUploader.java    From google-api-java-client with Apache License 2.0 3 votes vote down vote up
/**
 * Sets the HTTP method used for the initiation request.
 *
 * <p>
 * Can only be {@link HttpMethods#POST} (for media upload) or {@link HttpMethods#PUT} (for media
 * update). The default value is {@link HttpMethods#POST}.
 * </p>
 *
 * @since 1.12
 */
public MediaHttpUploader setInitiationRequestMethod(String initiationRequestMethod) {
  Preconditions.checkArgument(initiationRequestMethod.equals(HttpMethods.POST)
      || initiationRequestMethod.equals(HttpMethods.PUT)
      || initiationRequestMethod.equals(HttpMethods.PATCH));
  this.initiationRequestMethod = initiationRequestMethod;
  return this;
}
 
Example 16
Source File: IdTokenVerifier.java    From google-oauth-java-client with Apache License 2.0 2 votes vote down vote up
/**
 * Sets the seconds of time skew to accept when verifying time (default is
 * {@link #DEFAULT_TIME_SKEW_SECONDS}).
 *
 * <p>
 * It must be greater or equal to zero.
 * </p>
 *
 * <p>
 * Overriding is only supported for the purpose of calling the super implementation and changing
 * the return type, but nothing else.
 * </p>
 */
public Builder setAcceptableTimeSkewSeconds(long acceptableTimeSkewSeconds) {
  Preconditions.checkArgument(acceptableTimeSkewSeconds >= 0);
  this.acceptableTimeSkewSeconds = acceptableTimeSkewSeconds;
  return this;
}
 
Example 17
Source File: MockHttpContent.java    From google-http-java-client with Apache License 2.0 2 votes vote down vote up
/**
 * Returns the HTTP content length or {@code -1} for unknown.
 *
 * <p>Default value is {@code -1}.
 *
 * @since 1.5
 */
public MockHttpContent setLength(long length) {
  Preconditions.checkArgument(length >= -1);
  this.length = length;
  return this;
}
 
Example 18
Source File: MediaHttpDownloader.java    From google-api-java-client with Apache License 2.0 2 votes vote down vote up
/**
 * Sets the maximum size of individual chunks that will get downloaded by single HTTP requests.
 * The default value is {@link #MAXIMUM_CHUNK_SIZE}.
 *
 * <p>
 * The maximum allowable value is {@link #MAXIMUM_CHUNK_SIZE}.
 * </p>
 */
public MediaHttpDownloader setChunkSize(int chunkSize) {
  Preconditions.checkArgument(chunkSize > 0 && chunkSize <= MAXIMUM_CHUNK_SIZE);
  this.chunkSize = chunkSize;
  return this;
}
 
Example 19
Source File: AbstractGoogleClientRequest.java    From google-api-java-client with Apache License 2.0 2 votes vote down vote up
/**
 * Ensures that the specified required parameter is not null or
 * {@link AbstractGoogleClient#getSuppressRequiredParameterChecks()} is true.
 *
 * @param value the value of the required parameter
 * @param name the name of the required parameter
 * @throws IllegalArgumentException if the specified required parameter is null and
 *         {@link AbstractGoogleClient#getSuppressRequiredParameterChecks()} is false
 * @since 1.14
 */
protected final void checkRequiredParameter(Object value, String name) {
  Preconditions.checkArgument(
      abstractGoogleClient.getSuppressRequiredParameterChecks() || value != null,
      "Required parameter %s must be specified", name);
}
 
Example 20
Source File: AbstractNotification.java    From google-api-java-client with Apache License 2.0 2 votes vote down vote up
/**
 * Sets the message number (a monotonically increasing value starting with 1).
 *
 * <p>
 * Overriding is only supported for the purpose of calling the super implementation and changing
 * the return type, but nothing else.
 * </p>
 */
public AbstractNotification setMessageNumber(long messageNumber) {
  Preconditions.checkArgument(messageNumber >= 1);
  this.messageNumber = messageNumber;
  return this;
}