com.google.api.client.util.Preconditions Java Examples

The following examples show how to use com.google.api.client.util.Preconditions. 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: GetReservedWorkerAction.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
@Override
public ReservedWorker handle(GetReservedWorker workerRequest) {
  String id = workerRequest.getId();
  UUID jobId = decodeJobId(id);

  PortabilityJob job = jobStore.findJob(jobId);
  Preconditions.checkNotNull(
      job, "Couldn't lookup worker for job " + id + " because the job doesn't exist");
  if (job.jobAuthorization().state() != CREDS_ENCRYPTION_KEY_GENERATED) {
    monitor.debug(
        () -> format("Job %s has not entered state CREDS_ENCRYPTION_KEY_GENERATED yet", jobId),
        jobId);
    return new ReservedWorker(null);
  }
  monitor.debug(
      () ->
          format(
              "Got job %s in state CREDS_ENCRYPTION_KEY_GENERATED, returning its public key",
              jobId),
      jobId, EventCode.API_GOT_RESERVED_WORKER);
  return new ReservedWorker(job.jobAuthorization().authPublicKey());
}
 
Example #2
Source File: AuthorizationCodeInstalledAppTalend.java    From components with Apache License 2.0 6 votes vote down vote up
public static void browseWithProgramLauncher(String url) {
    Preconditions.checkNotNull(url);
    LOG.warn("Trying to open '{}'...", url);
    String osName = System.getProperty("os.name");
    String osNameMatch = osName.toLowerCase();
    if (osNameMatch.contains("linux")) {
        if (Program.findProgram("hmtl") == null) {
            try {
                Runtime.getRuntime().exec("xdg-open " + url);
                return;
            } catch (IOException e) {
                LOG.error("Failed to open url via xdg-open: {}.", e.getMessage());
            }
        }
    }
    Program.launch(url);
}
 
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);
  }
  request.setConfig(requestConfig.build());
  return new ApacheHttpResponse(request, httpClient.execute(request));
}
 
Example #4
Source File: AppEngineDataStoreFactory.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
@Override
public AppEngineDataStore<V> set(String key, V value) throws IOException {
  Preconditions.checkNotNull(key);
  Preconditions.checkNotNull(value);
  lock.lock();
  try {
    Entity entity = new Entity(getId(), key);
    entity.setUnindexedProperty(FIELD_VALUE, new Blob(IOUtils.serialize(value)));
    dataStoreService.put(entity);
    if (memcache != null) {
      memcache.put(key, value, memcacheExpiration);
    }
  } finally {
    lock.unlock();
  }
  return this;
}
 
Example #5
Source File: GenericUrl.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs the portion of the URL containing the scheme, host and port.
 *
 * <p>For the URL {@code "http://example.com/something?action=add"} this method would return
 * {@code "http://example.com"}.
 *
 * @return scheme://[user-info@]host[:port]
 * @since 1.9
 */
public final String buildAuthority() {
  // scheme, [user info], host, [port]
  StringBuilder buf = new StringBuilder();
  buf.append(Preconditions.checkNotNull(scheme));
  buf.append("://");
  if (userInfo != null) {
    buf.append(verbatim ? userInfo : CharEscapers.escapeUriUserInfo(userInfo)).append('@');
  }
  buf.append(Preconditions.checkNotNull(host));
  int port = this.port;
  if (port != -1) {
    buf.append(':').append(port);
  }
  return buf.toString();
}
 
Example #6
Source File: OAuthManager.java    From mirror with Apache License 2.0 6 votes vote down vote up
public OAuthFuture<Boolean> deleteCredential(final String userId,
                                             final OAuthCallback<Boolean> callback, Handler handler) {
    Preconditions.checkNotNull(userId);

    final Future2Task<Boolean> task = new Future2Task<Boolean>(handler, callback) {
        @Override
        public void doWork() throws Exception {
            Timber.i("deleteCredential");
            CredentialStore store = mFlow.getCredentialStore();
            if (store == null) {
                set(false);
                return;
            }

            store.delete(userId, null);
            set(true);
        }
    };

    // run the task in a background thread
    submitTaskToExecutor(task);

    return task;
}
 
Example #7
Source File: AuthorizationCodeFlow.java    From google-oauth-java-client with Apache License 2.0 6 votes vote down vote up
/**
 * @param builder authorization code flow builder
 *
 * @since 1.14
 */
protected AuthorizationCodeFlow(Builder builder) {
  method = Preconditions.checkNotNull(builder.method);
  transport = Preconditions.checkNotNull(builder.transport);
  jsonFactory = Preconditions.checkNotNull(builder.jsonFactory);
  tokenServerEncodedUrl = Preconditions.checkNotNull(builder.tokenServerUrl).build();
  clientAuthentication = builder.clientAuthentication;
  clientId = Preconditions.checkNotNull(builder.clientId);
  authorizationServerEncodedUrl =
      Preconditions.checkNotNull(builder.authorizationServerEncodedUrl);
  requestInitializer = builder.requestInitializer;
  credentialStore = builder.credentialStore;
  credentialDataStore = builder.credentialDataStore;
  scopes = Collections.unmodifiableCollection(builder.scopes);
  clock = Preconditions.checkNotNull(builder.clock);
  credentialCreatedListener = builder.credentialCreatedListener;
  refreshListeners = Collections.unmodifiableCollection(builder.refreshListeners);
  pkce = builder.pkce;
}
 
Example #8
Source File: JsonObjectParser.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize the parser to skip to wrapped keys (if any).
 *
 * @param parser JSON parser
 */
private void initializeParser(JsonParser parser) throws IOException {
  if (wrapperKeys.isEmpty()) {
    return;
  }
  boolean failed = true;
  try {
    String match = parser.skipToKey(wrapperKeys);
    Preconditions.checkArgument(
        match != null && parser.getCurrentToken() != JsonToken.END_OBJECT,
        "wrapper key(s) not found: %s",
        wrapperKeys);
    failed = false;
  } finally {
    if (failed) {
      parser.close();
    }
  }
}
 
Example #9
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 #10
Source File: GoogleCredential.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
/**
 * {@link Beta} <br/>
 * Return a credential defined by a Json file.
 *
 * @param credentialStream the stream with the credential definition.
 * @param transport the transport for Http calls.
 * @param jsonFactory the factory for Json parsing and formatting.
 * @return the credential defined by the credentialStream.
 * @throws IOException if the credential cannot be created from the stream.
 */
@Beta
public static GoogleCredential fromStream(InputStream credentialStream, HttpTransport transport,
    JsonFactory jsonFactory) throws IOException {
  Preconditions.checkNotNull(credentialStream);
  Preconditions.checkNotNull(transport);
  Preconditions.checkNotNull(jsonFactory);

  JsonObjectParser parser = new JsonObjectParser(jsonFactory);
  GenericJson fileContents = parser.parseAndClose(
      credentialStream, OAuth2Utils.UTF_8, GenericJson.class);
  String fileType = (String) fileContents.get("type");
  if (fileType == null) {
    throw new IOException("Error reading credentials from stream, 'type' field not specified.");
  }
  if (USER_FILE_TYPE.equals(fileType)) {
    return fromStreamUser(fileContents, transport, jsonFactory);
  }
  if (SERVICE_ACCOUNT_FILE_TYPE.equals(fileType)) {
    return fromStreamServiceAccount(fileContents, transport, jsonFactory);
  }
  throw new IOException(String.format(
      "Error reading credentials from stream, 'type' value '%s' not recognized."
          + " Expecting '%s' or '%s'.",
      fileType, USER_FILE_TYPE, SERVICE_ACCOUNT_FILE_TYPE));
}
 
Example #11
Source File: MockHttpTransport.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
@Override
public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
  Preconditions.checkArgument(supportsMethod(method), "HTTP method %s not supported", method);
  if (lowLevelHttpRequest != null) {
    return lowLevelHttpRequest;
  }
  lowLevelHttpRequest = new MockLowLevelHttpRequest(url);
  if (lowLevelHttpResponse != null) {
    lowLevelHttpRequest.setResponse(lowLevelHttpResponse);
  }
  return lowLevelHttpRequest;
}
 
Example #12
Source File: SharedPreferencesCredentialStore.java    From mirror with Apache License 2.0 5 votes vote down vote up
@Override
public void store(String userId, Credential credential) throws IOException {
    Preconditions.checkNotNull(userId);
    FilePersistedCredential fileCredential = new FilePersistedCredential();
    fileCredential.store(credential);
    String credentialJson = jsonFactory.toString(fileCredential);
    prefs.edit().putString(userId, credentialJson).apply();
}
 
Example #13
Source File: DateRange.java    From adwords-alerting with Apache License 2.0 5 votes vote down vote up
/**
 * Factory method to create a DataRange instance.
 * @param dateRange the date range string, either in "yyyyMMdd,yyyyMMdd" format, or some
 *                  ReportDefinitionDateRangeType enum value (such as "LAST_7_DAYS")
 * @return the DateRange object
 */
public static DateRange fromString(String dateRange) {
  Preconditions.checkNotNull(dateRange, "DateRange cannot be null!");
  Preconditions.checkArgument(!dateRange.isEmpty(), "DateRange cannot be empty!");

  return dateRange.contains(",") ? parseCustomFormat(dateRange) : parseEnumFormat(dateRange);
}
 
Example #14
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 #15
Source File: DateRange.java    From adwords-alerting with Apache License 2.0 5 votes vote down vote up
/**
 * Parse DateRange in "yyyyMMdd,yyyyMMdd" format.
 */
private static DateRange parseCustomFormat(String dateRange) {
  String[] dates = dateRange.split(",");
  Preconditions.checkArgument(dates.length == 2, "Unknown DateRange format: %s.", dateRange);

  // Just throws exception if argument is not in proper format "yyyyMMdd"
  LocalDate startDate = formatter.parseLocalDate(dates[0].trim());
  LocalDate endDate = formatter.parseLocalDate(dates[1].trim());
  return new DateRange(startDate, endDate);
}
 
Example #16
Source File: DateRangeAndType.java    From aw-reporting with Apache License 2.0 5 votes vote down vote up
/**
 * Parse DateRange in "yyyyMMdd,yyyyMMdd" format.
 */
private static DateRangeAndType parseCustomFormat(final String dateRange) {
  String[] dates = dateRange.split(",");
  Preconditions.checkArgument(dates.length == 2, "Unknown DateRange format: '%s.'", dateRange);

  // Just throws exception if argument is not in proper format "yyyyMMdd"
  LocalDate startDate = DATE_FORMMATER.parseLocalDate(dates[0].trim());
  LocalDate endDate = DATE_FORMMATER.parseLocalDate(dates[1].trim());

  return new DateRangeAndType(startDate, endDate, ReportDefinitionDateRangeType.CUSTOM_DATE);
}
 
Example #17
Source File: AndroidUtils.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Throws an {@link IllegalArgumentException} if {@link #isMinimumSdkLevel(int)} is {@code false}
 * on the given level.
 *
 * @see android.os.Build.VERSION_CODES
 */
public static void checkMinimumSdkLevel(int minimumSdkLevel) {
  Preconditions.checkArgument(
      isMinimumSdkLevel(minimumSdkLevel),
      "running on Android SDK level %s but requires minimum %s",
      Build.VERSION.SDK_INT,
      minimumSdkLevel);
}
 
Example #18
Source File: TweetsLoadable.java    From android-oauth-client with Apache License 2.0 5 votes vote down vote up
TweetsLoadable(LoaderManager loaderManager, int loaderId,
        LoaderCallbacks<Result<Timeline>> callbacks) {
    super();
    this.mLoaderManager = Preconditions.checkNotNull(loaderManager);
    this.mLoaderId = loaderId;
    this.mCallbacks = callbacks;
}
 
Example #19
Source File: DialogFragmentController.java    From android-oauth-client with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param fragmentManager
 * @param fullScreen
 * @param horizontalProgress
 * @param hideFullScreenTitle if you set this flag to true, {@param horizontalProgress} will be ignored
 */
public DialogFragmentController(android.support.v4.app.FragmentManager fragmentManager, boolean fullScreen,
    boolean horizontalProgress, boolean hideFullScreenTitle) {
    super();
    this.uiHandler = new Handler(Looper.getMainLooper());
    this.fragmentManager =
            new FragmentManagerCompat(Preconditions.checkNotNull(fragmentManager));
    this.fullScreen = fullScreen;
    this.horizontalProgress = horizontalProgress;
    this.hideFullScreenTitle = hideFullScreenTitle;
}
 
Example #20
Source File: AbstractMemoryDataStore.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public final DataStore<V> set(String key, V value) throws IOException {
  Preconditions.checkNotNull(key);
  Preconditions.checkNotNull(value);
  lock.lock();
  try {
    keyValueMap.put(key, IOUtils.serialize(value));
    save();
  } finally {
    lock.unlock();
  }
  return this;
}
 
Example #21
Source File: OAuthManager.java    From android-oauth-client with Apache License 2.0 5 votes vote down vote up
public OAuthManager(AuthorizationFlow flow, AuthorizationUIController uiController,
        ExecutorService executor) {
    super();
    this.mFlow = flow;
    this.mUIController = uiController;
    this.mExecutor = Preconditions.checkNotNull(executor);
}
 
Example #22
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 #23
Source File: LenientTokenResponseException.java    From android-oauth-client with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new instance of {@link LenientTokenResponseException}.
 * <p>
 * If there is a JSON error response, it is parsed using
 * {@link TokenErrorResponse}, which can be inspected using
 * {@link #getDetails()}. Otherwise, the full response content is read and
 * included in the exception message.
 * </p>
 * 
 * @param jsonFactory JSON factory
 * @param readResponse an HTTP response that has already been read
 * @param responseContent the content String of the HTTP response
 * @return new instance of {@link TokenErrorResponse}
 */
public static LenientTokenResponseException from(JsonFactory jsonFactory,
        HttpResponse readResponse, String responseContent) {
    HttpResponseException.Builder builder = new HttpResponseException.Builder(
            readResponse.getStatusCode(), readResponse.getStatusMessage(),
            readResponse.getHeaders());
    // details
    Preconditions.checkNotNull(jsonFactory);
    TokenErrorResponse details = null;
    String detailString = null;
    String contentType = readResponse.getContentType();
    try {
        if (/* !response.isSuccessStatusCode() && */true
                && contentType != null
                && HttpMediaType.equalsIgnoreParameters(Json.MEDIA_TYPE, contentType)) {
            details = readResponse
                    .getRequest()
                    .getParser()
                    .parseAndClose(new StringReader(responseContent), TokenErrorResponse.class);
            detailString = details.toPrettyString();
        } else {
            detailString = responseContent;
        }
    } catch (IOException exception) {
        // it would be bad to throw an exception while throwing an exception
        exception.printStackTrace();
    }
    // message
    StringBuilder message = HttpResponseException.computeMessageBuffer(readResponse);
    if (!com.google.api.client.util.Strings.isNullOrEmpty(detailString)) {
        message.append(StringUtils.LINE_SEPARATOR).append(detailString);
        builder.setContent(detailString);
    }
    builder.setMessage(message.toString());
    return new LenientTokenResponseException(builder, details);
}
 
Example #24
Source File: GoogleCredential.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
@Override
public GoogleCredential setRefreshToken(String refreshToken) {
  if (refreshToken != null) {
    Preconditions.checkArgument(
        getJsonFactory() != null && getTransport() != null && getClientAuthentication() != null,
        "Please use the Builder and call setJsonFactory, setTransport and setClientSecrets");
  }
  return (GoogleCredential) super.setRefreshToken(refreshToken);
}
 
Example #25
Source File: JsonParser.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
/** Starts parsing that handles start of input by calling {@link #nextToken()}. */
private JsonToken startParsing() throws IOException {
  JsonToken currentToken = getCurrentToken();
  // token is null at start, so get next token
  if (currentToken == null) {
    currentToken = nextToken();
  }
  Preconditions.checkArgument(currentToken != null, "no JSON input found");
  return currentToken;
}
 
Example #26
Source File: GoogleAuthorizationCodeTokenRequest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
@Override
public GoogleAuthorizationCodeTokenRequest setClientAuthentication(
    HttpExecuteInterceptor clientAuthentication) {
  Preconditions.checkNotNull(clientAuthentication);
  return (GoogleAuthorizationCodeTokenRequest) super.setClientAuthentication(
      clientAuthentication);
}
 
Example #27
Source File: HttpHeaders.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
static void serializeHeaders(
    HttpHeaders headers,
    StringBuilder logbuf,
    StringBuilder curlbuf,
    Logger logger,
    LowLevelHttpRequest lowLevelHttpRequest,
    Writer writer)
    throws IOException {
  HashSet<String> headerNames = new HashSet<String>();
  for (Map.Entry<String, Object> headerEntry : headers.entrySet()) {
    String name = headerEntry.getKey();
    Preconditions.checkArgument(
        headerNames.add(name),
        "multiple headers of the same name (headers are case insensitive): %s",
        name);
    Object value = headerEntry.getValue();
    if (value != null) {
      // compute the display name from the declared field name to fix capitalization
      String displayName = name;
      FieldInfo fieldInfo = headers.getClassInfo().getFieldInfo(name);
      if (fieldInfo != null) {
        displayName = fieldInfo.getName();
      }
      Class<? extends Object> valueClass = value.getClass();
      if (value instanceof Iterable<?> || valueClass.isArray()) {
        for (Object repeatedValue : Types.iterableOf(value)) {
          addHeader(
              logger, logbuf, curlbuf, lowLevelHttpRequest, displayName, repeatedValue, writer);
        }
      } else {
        addHeader(logger, logbuf, curlbuf, lowLevelHttpRequest, displayName, value, writer);
      }
    }
  }
  if (writer != null) {
    writer.flush();
  }
}
 
Example #28
Source File: ByteArrayContent.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor from byte array content that has already been encoded, specifying a range of bytes
 * to read from the input byte array.
 *
 * @param type content type or {@code null} for none
 * @param array byte array content
 * @param offset starting offset into the byte array
 * @param length of bytes to read from byte array
 * @since 1.7
 */
public ByteArrayContent(String type, byte[] array, int offset, int length) {
  super(type);
  this.byteArray = Preconditions.checkNotNull(array);
  Preconditions.checkArgument(
      offset >= 0 && length >= 0 && offset + length <= array.length,
      "offset %s, length %s, array length %s",
      offset,
      length,
      array.length);
  this.offset = offset;
  this.length = length;
}
 
Example #29
Source File: DialogFragmentController.java    From android-oauth-client with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param fragmentManager
 * @param fullScreen
 * @param horizontalProgress
 * @param hideFullScreenTitle if you set this flag to true, {@param horizontalProgress} will be ignored
 */
public DialogFragmentController(android.app.FragmentManager fragmentManager, boolean fullScreen,
    boolean horizontalProgress, boolean hideFullScreenTitle) {
    super();
    this.uiHandler = new Handler(Looper.getMainLooper());
    this.fragmentManager =
            new FragmentManagerCompat(Preconditions.checkNotNull(fragmentManager));
    this.fullScreen = fullScreen;
    this.horizontalProgress = horizontalProgress;
    this.hideFullScreenTitle = hideFullScreenTitle;
}
 
Example #30
Source File: FileCredentialStore.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * @param file File to store user credentials
 * @param jsonFactory JSON factory to serialize user credentials
 */
public FileCredentialStore(File file, JsonFactory jsonFactory) throws IOException {
  this.file = Preconditions.checkNotNull(file);
  this.jsonFactory = Preconditions.checkNotNull(jsonFactory);
  // create parent directory (if necessary)
  File parentDir = file.getCanonicalFile().getParentFile();
  if (parentDir != null && !parentDir.exists() && !parentDir.mkdirs()) {
    throw new IOException("unable to create parent directory: " + parentDir);
  }
  // error if it is a symbolic link
  if (isSymbolicLink(file)) {
    throw new IOException("unable to use a symbolic link: " + file);
  }
  // create new file (if necessary)
  if (!file.createNewFile()) {
    // load credentials from existing file
    loadCredentials(file);
  } else {
    // disable access by other users if O/S allows it
    if (!file.setReadable(false, false) || !file.setWritable(false, false)
        || !file.setExecutable(false, false)) {
      LOGGER.warning("unable to change file permissions for everybody: " + file);
    }
    // set file permissions to readable and writable by user
    if (!file.setReadable(true) || !file.setWritable(true)) {
      throw new IOException("unable to set file permissions: " + file);
    }
    // save the credentials to create a new file
    save();
  }
}