com.google.api.client.json.JsonFactory Java Examples

The following examples show how to use com.google.api.client.json.JsonFactory. 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: AbstractJsonFactoryTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testParser_heterogeneousSchema_withArrays() throws Exception {
  JsonFactory factory = newFactory();
  JsonParser parser = factory.createJsonParser(DOG_WITH_FAMILY);
  Animal dog = parser.parse(DogWithFamily.class);
  assertEquals(DOG_WITH_FAMILY, factory.toString(dog));
  assertEquals(DogWithFamily.class, dog.getClass());
  assertEquals("Bob", dog.name);
  assertEquals("dogwithfamily", dog.type);
  assertEquals(4, dog.numberOfLegs);
  assertEquals(10, ((DogWithFamily) dog).tricksKnown);
  String[] nicknames = {"Fluffy", "Hey, you"};
  assertTrue(Arrays.equals(nicknames, ((DogWithFamily) dog).nicknames));
  Animal child = ((DogWithFamily) dog).children[0];
  assertEquals("Fido", child.name);
  assertEquals(3, ((Dog) child).tricksKnown);
  Animal child2 = ((DogWithFamily) dog).children[1];
  assertEquals("Mr. Icky", child2.name);
  assertEquals(68, ((Centipede) child2).numberOfLegs);
}
 
Example #2
Source File: InjectorUtils.java    From beam with Apache License 2.0 6 votes vote down vote up
/** Builds a new Pubsub client and returns it. */
public static Pubsub getClient(final HttpTransport httpTransport, final JsonFactory jsonFactory)
    throws IOException {
  checkNotNull(httpTransport);
  checkNotNull(jsonFactory);
  GoogleCredential credential =
      GoogleCredential.getApplicationDefault(httpTransport, jsonFactory);
  if (credential.createScopedRequired()) {
    credential = credential.createScoped(PubsubScopes.all());
  }
  if (credential.getClientAuthentication() != null) {
    System.out.println(
        "\n***Warning! You are not using service account credentials to "
            + "authenticate.\nYou need to use service account credentials for this example,"
            + "\nsince user-level credentials do not have enough pubsub quota,\nand so you will run "
            + "out of PubSub quota very quickly.\nSee "
            + "https://developers.google.com/identity/protocols/application-default-credentials.");
    System.exit(1);
  }
  HttpRequestInitializer initializer = new RetryHttpInitializerWrapper(credential);
  return new Pubsub.Builder(httpTransport, jsonFactory, initializer)
      .setApplicationName(APP_NAME)
      .build();
}
 
Example #3
Source File: LocalFileCredentialFactoryTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testfromConfigurationCredentialP12() throws Exception {
  File tmpfile = temporaryFolder
      .newFile("testfromConfigurationCredentialP12" + SERVICE_ACCOUNT_FILE_P12);
  createConfig(tmpfile.getAbsolutePath(), "ServiceAccount");
  GoogleCredential mockCredential = new MockGoogleCredential.Builder().build();
  List<String> scopes = Arrays.asList("profile, calendar");
  when(mockCredentialHelper.getP12Credential(
      eq("ServiceAccount"),
      eq(tmpfile.toPath()),
      any(HttpTransport.class),
      any(JsonFactory.class),
      any(HttpRequestInitializer.class),
      eq(scopes)))
      .thenReturn(mockCredential);
  LocalFileCredentialFactory credentialFactory = LocalFileCredentialFactory.fromConfiguration();
  assertEquals(mockCredential, credentialFactory.getCredential(scopes));
}
 
Example #4
Source File: AbstractJsonFactoryTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testParser_heterogeneousSchema_withObject() throws Exception {
  JsonFactory factory = newFactory();
  JsonParser parser = factory.createJsonParser(HUMAN);
  Animal human = parser.parse(Animal.class);
  assertEquals(HUMAN, factory.toString(human));
  Dog dog = ((Human) human).bestFriend;
  assertEquals(DOG, factory.toString(dog));
  assertEquals(Dog.class, dog.getClass());
  assertEquals("Fido", dog.name);
  assertEquals("dog", dog.type);
  assertEquals(4, dog.numberOfLegs);
  assertEquals(3, dog.tricksKnown);
  assertEquals("Joe", human.name);
  assertEquals(2, human.numberOfLegs);
  assertEquals("human", human.type);
}
 
Example #5
Source File: ContentWorkflowSample.java    From googleads-shopping-samples with Apache License 2.0 6 votes vote down vote up
protected static ShoppingContent.Builder createStandardBuilder(
    CommandLine parsedArgs, ContentConfig config) throws IOException {
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  HttpTransport httpTransport = null;
  try {
    httpTransport = GoogleNetHttpTransport.newTrustedTransport();
  } catch (GeneralSecurityException e) {
    e.printStackTrace();
    System.exit(1);
  }
  Authenticator authenticator =
      new Authenticator(httpTransport, jsonFactory, ShoppingContentScopes.all(), config);
  Credential credential = authenticator.authenticate();

  return new ShoppingContent.Builder(
          httpTransport, jsonFactory, BaseOption.installLogging(credential, parsedArgs))
      .setApplicationName("Content API for Shopping Samples");
}
 
Example #6
Source File: AppIdentityCredentialTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
public void testAppEngineCredentialWrapperGetAccessToken() throws IOException {
  final String expectedAccessToken = "ExpectedAccessToken";

  HttpTransport transport = new MockHttpTransport();
  JsonFactory jsonFactory = new JacksonFactory();

  MockAppIdentityService appIdentity = new MockAppIdentityService();
  appIdentity.setAccessTokenText(expectedAccessToken);

  AppIdentityCredential.Builder builder = new AppIdentityCredential.Builder(SCOPES);
  builder.setAppIdentityService(appIdentity);
  AppIdentityCredential appCredential = builder.build();

  GoogleCredential wrapper = new
      AppIdentityCredential.AppEngineCredentialWrapper(appCredential, transport, jsonFactory);
  assertTrue(wrapper.refreshToken());
  assertEquals(expectedAccessToken, wrapper.getAccessToken());
}
 
Example #7
Source File: AuthorizationFlow.java    From mirror with Apache License 2.0 6 votes vote down vote up
/**
 * @param method                        method of presenting the access token to the resource
 *                                      server (for example
 *                                      {@link BearerToken#authorizationHeaderAccessMethod})
 * @param transport                     HTTP transport
 * @param jsonFactory                   JSON factory
 * @param tokenServerUrl                token server URL
 * @param clientAuthentication          client authentication or {@code null} for
 *                                      none (see
 *                                      {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}
 *                                      )
 * @param clientId                      client identifier
 * @param authorizationServerEncodedUrl authorization server encoded URL
 */
public Builder(AccessMethod method,
               HttpTransport transport,
               JsonFactory jsonFactory,
               GenericUrl tokenServerUrl,
               HttpExecuteInterceptor clientAuthentication,
               String clientId,
               String authorizationServerEncodedUrl) {
    super(method,
            transport,
            jsonFactory,
            tokenServerUrl,
            clientAuthentication,
            clientId,
            authorizationServerEncodedUrl);
}
 
Example #8
Source File: LocalFileCredentialFactoryTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testfromConfigurationJsonKey() throws Exception {
  File tmpfile = temporaryFolder.newFile("testfromConfiguration" + SERVICE_ACCOUNT_FILE_JSON);
  createConfig(tmpfile.getAbsolutePath(), "");
  GoogleCredential mockCredential = new MockGoogleCredential.Builder().build();
  List<String> scopes = Arrays.asList("profile");
  when(mockCredentialHelper.getJsonCredential(
      eq(tmpfile.toPath()),
      any(HttpTransport.class),
      any(JsonFactory.class),
      any(HttpRequestInitializer.class),
      eq(scopes)))
      .thenReturn(mockCredential);
  LocalFileCredentialFactory credentialFactory = LocalFileCredentialFactory.fromConfiguration();
  assertEquals(mockCredential, credentialFactory.getCredential(scopes));
}
 
Example #9
Source File: AbstractJsonFactoryTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testParser_hashmapForMapType() throws Exception {
  // parse
  JsonFactory factory = newFactory();
  JsonParser parser;
  parser = factory.createJsonParser(MAP_TYPE);
  parser.nextToken();
  @SuppressWarnings("unchecked")
  HashMap<String, ArrayList<ArrayMap<String, ArrayMap<String, BigDecimal>>>> result =
      parser.parse(HashMap.class);
  // serialize
  assertEquals(MAP_TYPE, factory.toString(result));
  // check parsed result
  ArrayList<ArrayMap<String, ArrayMap<String, BigDecimal>>> value = result.get("value");
  ArrayMap<String, ArrayMap<String, BigDecimal>> firstMap = value.get(0);
  ArrayMap<String, BigDecimal> map1 = firstMap.get("map1");
  BigDecimal integer = map1.get("k1");
  assertEquals(1, integer.intValue());
}
 
Example #10
Source File: FirebaseUserManagerTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testImportUsers() throws Exception {
  TestResponseInterceptor interceptor = initializeAppForUserManagement("{}");
  ImportUserRecord user1 = ImportUserRecord.builder().setUid("user1").build();
  ImportUserRecord user2 = ImportUserRecord.builder().setUid("user2").build();

  List<ImportUserRecord> users = ImmutableList.of(user1, user2);
  UserImportResult result = FirebaseAuth.getInstance().importUsersAsync(users, null).get();
  checkRequestHeaders(interceptor);
  assertEquals(2, result.getSuccessCount());
  assertEquals(0, result.getFailureCount());
  assertTrue(result.getErrors().isEmpty());

  ByteArrayOutputStream out = new ByteArrayOutputStream();
  interceptor.getResponse().getRequest().getContent().writeTo(out);
  JsonFactory jsonFactory = Utils.getDefaultJsonFactory();
  GenericJson parsed = jsonFactory.fromString(new String(out.toByteArray()), GenericJson.class);
  assertEquals(1, parsed.size());
  List<Map<String, Object>> expected = ImmutableList.of(
      user1.getProperties(jsonFactory),
      user2.getProperties(jsonFactory)
  );
  assertEquals(expected, parsed.get("users"));
}
 
Example #11
Source File: CloudIdentityFacade.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
static CloudIdentityFacade create(
    String identitySource, InputStream serviceKeyStream, String appName)
    throws GeneralSecurityException, IOException {
  Credential credential = authorize(serviceKeyStream);
  // Google services are rate-limited. The RetryPolicy allows to rety when a
  // 429 HTTP status response (Too Many Requests) is received.
  RetryPolicy retryPolicy = new RetryPolicy.Builder().build();
  RetryRequestInitializer requestInitializer = new RetryRequestInitializer(retryPolicy);
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
  CloudIdentity.Builder serviceBuilder = new CloudIdentity.Builder(transport, jsonFactory,
      request -> {
        credential.initialize(request);
        requestInitializer.initialize(request);
      });
  serviceBuilder.setApplicationName(appName).build();
  CloudIdentity service = serviceBuilder.build();
  return new CloudIdentityFacade(identitySource, service);
}
 
Example #12
Source File: AbstractJsonFactoryTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testParser_arrayType() throws Exception {
  JsonFactory factory = newFactory();
  JsonParser parser;
  parser = factory.createJsonParser(ARRAY_TYPE);
  parser.nextToken();
  ArrayType result = parser.parse(ArrayType.class);
  assertEquals(ARRAY_TYPE, factory.toString(result));
  // check types and values
  int[] arr = result.arr;
  assertTrue(Arrays.equals(new int[] {4, 5}, arr));
  int[][] arr2 = result.arr2;
  assertEquals(2, arr2.length);
  int[] arr20 = arr2[0];
  assertEquals(2, arr20.length);
  int arr200 = arr20[0];
  assertEquals(1, arr200);
  assertEquals(2, arr20[1]);
  int[] arr21 = arr2[1];
  assertEquals(1, arr21.length);
  assertEquals(3, arr21[0]);
  Integer[] integerArr = result.integerArr;
  assertEquals(2, integerArr.length);
  assertEquals(6, integerArr[0].intValue());
}
 
Example #13
Source File: CloudIotManager.java    From daq with Apache License 2.0 6 votes vote down vote up
private void initializeCloudIoT() {
  projectPath = "projects/" + projectId + "/locations/" + cloudRegion;
  try {
    System.err.println("Initializing with default credentials...");
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all());
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    HttpRequestInitializer init = new HttpCredentialsAdapter(credential);
    cloudIotService =
        new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, init)
            .setApplicationName("com.google.iot.bos")
            .build();
    cloudIotRegistries = cloudIotService.projects().locations().registries();
    System.err.println("Created service for project " + projectPath);
  } catch (Exception e) {
    throw new RuntimeException("While initializing Cloud IoT project " + projectPath, e);
  }
}
 
Example #14
Source File: DeviceRegistryExample.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/** Retrieves device metadata from a registry. * */
protected static Device getDevice(
    String deviceId, String projectId, String cloudRegion, String registryName)
    throws GeneralSecurityException, IOException {
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all());
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  HttpRequestInitializer init = new HttpCredentialsAdapter(credential);
  final CloudIot service =
      new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, init)
          .setApplicationName(APP_NAME)
          .build();

  final String devicePath =
      String.format(
          "projects/%s/locations/%s/registries/%s/devices/%s",
          projectId, cloudRegion, registryName, deviceId);

  System.out.println("Retrieving device " + devicePath);
  return service.projects().locations().registries().devices().get(devicePath).execute();
}
 
Example #15
Source File: AbstractJsonFactoryTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testParser_polymorphicClass_mapOfPolymorphicClasses() throws Exception {
  JsonFactory factory = newFactory();
  JsonParser parser = factory.createJsonParser(HUMAN_WITH_PETS);
  Animal human = parser.parse(Animal.class);
  assertEquals(HumanWithPets.class, human.getClass());
  assertEquals(HUMAN_WITH_PETS_PARSED, factory.toString(human));
  assertEquals(2, human.numberOfLegs);
  assertEquals("human with pets", human.type);
  HumanWithPets humanWithPets = (HumanWithPets) human;
  assertEquals("Fido", humanWithPets.bestFriend.name);
  assertEquals(3, humanWithPets.bestFriend.tricksKnown);
  assertEquals("Mr. Icky", humanWithPets.pets.get("first").name);
  assertEquals("bug", humanWithPets.pets.get("first").type);
  assertEquals(68, humanWithPets.pets.get("first").numberOfLegs);
  assertEquals("green", ((Centipede) humanWithPets.pets.get("first")).color);
  assertEquals("dog", humanWithPets.pets.get("second").type);
  assertEquals(0, ((Dog) humanWithPets.pets.get("second")).tricksKnown);
  assertEquals(2, humanWithPets.pets.size());
}
 
Example #16
Source File: GCPProject.java    From policyscanner with Apache License 2.0 6 votes vote down vote up
/**
 * Return the Projects api object used for accessing the Cloud Resource Manager Projects API.
 * @return Projects api object used for accessing the Cloud Resource Manager Projects API
 * @throws GeneralSecurityException Thrown if there's a permissions error.
 * @throws IOException Thrown if there's an IO error initializing the API object.
 */
public static synchronized Projects getProjectsApiStub()
    throws GeneralSecurityException, IOException {
  if (projectApiStub != null) {
    return projectApiStub;
  }
  HttpTransport transport;
  GoogleCredential credential;
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  transport = GoogleNetHttpTransport.newTrustedTransport();
  credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
  if (credential.createScopedRequired()) {
    Collection<String> scopes = CloudResourceManagerScopes.all();
    credential = credential.createScoped(scopes);
  }
  projectApiStub = new CloudResourceManager
      .Builder(transport, jsonFactory, credential)
      .build()
      .projects();
  return projectApiStub;
}
 
Example #17
Source File: BuyerServiceHelper.java    From googleads-adxbuyer-examples with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new API service
 * @return the new, authenticated and authorized service
 * @throws GeneralSecurityException
 * @throws IOException
 */
protected static AdExchangeBuyer getNewService() throws GeneralSecurityException, IOException {
  /** Global instance of the HTTP transport. */
  HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();

  /** Global instance of the JSON factory. */
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

  Credential credential = GoogleCredential.fromStream(new FileInputStream(JSON_FILE))
      .createScoped(AdExchangeBuyerScopes.all());

  String applicationName = String.format(APPLICATION_NAME_TEMPLATE, APPLICATION_NAME);

  return new AdExchangeBuyer.Builder(httpTransport, jsonFactory, credential).setApplicationName(
      applicationName).build();
}
 
Example #18
Source File: PubsubUtils.java    From cloud-pubsub-samples-java with Apache License 2.0 6 votes vote down vote up
/**
 * Builds a new Pubsub client and returns it.
 *
 * @param httpTransport HttpTransport for Pubsub client.
 * @param jsonFactory JsonFactory for Pubsub client.
 * @return Pubsub client.
 * @throws IOException when we can not get the default credentials.
 */
public static Pubsub getClient(final HttpTransport httpTransport,
                               final JsonFactory jsonFactory)
        throws IOException {
    Preconditions.checkNotNull(httpTransport);
    Preconditions.checkNotNull(jsonFactory);
    GoogleCredential credential = GoogleCredential.getApplicationDefault();
    if (credential.createScopedRequired()) {
        credential = credential.createScoped(PubsubScopes.all());
    }
    // Please use custom HttpRequestInitializer for automatic
    // retry upon failures.
    HttpRequestInitializer initializer =
            new RetryHttpInitializerWrapper(credential);
    return new Pubsub.Builder(httpTransport, jsonFactory, initializer)
            .setApplicationName(APPLICATION_NAME)
            .build();
}
 
Example #19
Source File: AbstractJsonFactoryTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testParser_mapType() throws Exception {
  // parse
  JsonFactory factory = newFactory();
  JsonParser parser;
  parser = factory.createJsonParser(MAP_TYPE);
  parser.nextToken();
  MapOfMapType result = parser.parse(MapOfMapType.class);
  // serialize
  assertEquals(MAP_TYPE, factory.toString(result));
  // check parsed result
  Map<String, Map<String, Integer>>[] value = result.value;
  Map<String, Map<String, Integer>> firstMap = value[0];
  Map<String, Integer> map1 = firstMap.get("map1");
  Integer integer = map1.get("k1");
  assertEquals(1, integer.intValue());
  Map<String, Integer> map2 = firstMap.get("map2");
  assertEquals(3, map2.get("kk1").intValue());
  assertEquals(4, map2.get("kk2").intValue());
}
 
Example #20
Source File: DevelopersSharedModule.java    From HotswapAgentExamples with GNU General Public License v2.0 6 votes vote down vote up
@Override
	public void configure(Binder binder) {

//		binder.bind(HttpTransport.class).toInstance(new UrlFetchTransport());
		binder.bind(HttpTransport.class).toInstance(new NetHttpTransport());

		/*
		 * TODO HH?
		 */
		binder.bind(DateFormat.class).toInstance(
				new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS'Z'"));

		binder.bind(JsonFactory.class).toInstance(
				JacksonFactory.getDefaultInstance());

		/*
		 * Global instance of the {@link DataStoreFactory}. The best practice is
		 * to make it a single globally shared instance across your application.
		 */
		binder.bind(DataStoreFactory.class).toInstance(
				AppEngineDataStoreFactory.getDefaultInstance());
		binder.bind(AppEngineDataStoreFactory.class).in(Singleton.class);
	}
 
Example #21
Source File: AbstractJsonFactoryTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public void testParser_integerTypeVariableType() throws Exception {
  // parse
  JsonFactory factory = newFactory();
  JsonParser parser;
  parser = factory.createJsonParser(INTEGER_TYPE_VARIABLE_TYPE);
  parser.nextToken();
  IntegerTypeVariableType result = parser.parse(IntegerTypeVariableType.class);
  // serialize
  assertEquals(INTEGER_TYPE_VARIABLE_TYPE, factory.toString(result));
  // check parsed result
  // array
  Integer[][] arr = result.arr;
  assertEquals(2, arr.length);
  assertEquals(Data.nullOf(Integer[].class), arr[0]);
  Integer[] subArr = arr[1];
  assertEquals(2, subArr.length);
  assertEquals(Data.NULL_INTEGER, subArr[0]);
  Integer arrValue = subArr[1];
  assertEquals(1, arrValue.intValue());
  // collection
  LinkedList<LinkedList<Integer>> list = result.list;
  assertEquals(2, list.size());
  assertEquals(Data.nullOf(LinkedList.class), list.get(0));
  LinkedList<Integer> subList = list.get(1);
  assertEquals(2, subList.size());
  assertEquals(Data.NULL_INTEGER, subList.get(0));
  arrValue = subList.get(1);
  assertEquals(1, arrValue.intValue());
  // null value
  Integer nullValue = result.nullValue;
  assertEquals(Data.NULL_INTEGER, nullValue);
  // value
  Integer value = result.value;
  assertEquals(1, value.intValue());
}
 
Example #22
Source File: CheckupReminders.java    From Crimson with Apache License 2.0 5 votes vote down vote up
public MakeRequestTask(GoogleAccountCredential credential) {
    HttpTransport transport = AndroidHttp.newCompatibleTransport();
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    mService = new com.google.api.services.calendar.Calendar.Builder(
            transport, jsonFactory, credential)
            .setApplicationName("Google Calendar API Android Quickstart")
            .build();
}
 
Example #23
Source File: GoogleAppSecretDecrypter.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
@Inject
GoogleAppSecretDecrypter(
    HttpTransport transport, JsonFactory jsonFactory, @ProjectId String projectId)
    throws GoogleCredentialException {
  GoogleCredential credential;
  try {
    credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
  } catch (IOException e) {
    throw new GoogleCredentialException(
        "Problem obtaining credentials via GoogleCredential.getApplicationDefault()");
  }
  if (credential.createScopedRequired()) {
    credential = credential.createScoped(CloudKMSScopes.all());
  }
  this.cloudKMS =
      new CloudKMS.Builder(transport, jsonFactory, credential)
          .setApplicationName("GoogleAppSecretDecrypter")
          .build();
  this.secretsCryptoKey = String.format(SECRETS_CRYPTO_KEY_FMT_STRING, projectId);
}
 
Example #24
Source File: OAuth2HelperTest.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  MockitoAnnotations.initMocks(this);
  credential =
      new Credential.Builder(BearerToken.authorizationHeaderAccessMethod())
          .setTransport(new NetHttpTransport())
          .setJsonFactory(Mockito.mock(JsonFactory.class))
          .setClientAuthentication(Mockito.mock(HttpExecuteInterceptor.class))
          .setTokenServerUrl(TOKEN_SERVER_URL).build();
  oAuth2Helper = spy(new OAuth2Helper(libLogger, REFRESH_WINDOW_SECS));
}
 
Example #25
Source File: OnlinePredictionSample.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  Discovery discovery = new Discovery.Builder(httpTransport, jsonFactory, null).build();

  RestDescription api = discovery.apis().getRest("ml", "v1").execute();
  RestMethod method = api.getResources().get("projects").getMethods().get("predict");

  JsonSchema param = new JsonSchema();
  String projectId = "YOUR_PROJECT_ID";
  // You should have already deployed a model and a version.
  // For reference, see https://cloud.google.com/ml-engine/docs/deploying-models.
  String modelId = "YOUR_MODEL_ID";
  String versionId = "YOUR_VERSION_ID";
  param.set(
      "name", String.format("projects/%s/models/%s/versions/%s", projectId, modelId, versionId));

  GenericUrl url =
      new GenericUrl(UriTemplate.expand(api.getBaseUrl() + method.getPath(), param, true));
  System.out.println(url);

  String contentType = "application/json";
  File requestBodyFile = new File("input.txt");
  HttpContent content = new FileContent(contentType, requestBodyFile);
  System.out.println(content.getLength());

  List<String> scopes = new ArrayList<>();
  scopes.add("https://www.googleapis.com/auth/cloud-platform");

  GoogleCredentials credential = GoogleCredentials.getApplicationDefault().createScoped(scopes);
  HttpRequestFactory requestFactory =
      httpTransport.createRequestFactory(new HttpCredentialsAdapter(credential));
  HttpRequest request = requestFactory.buildRequest(method.getHttpMethod(), url, content);

  String response = request.execute().parseAsString();
  System.out.println(response);
}
 
Example #26
Source File: UserRecord.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
UserRecord(User response, JsonFactory jsonFactory) {
  checkNotNull(response, "response must not be null");
  checkNotNull(jsonFactory, "jsonFactory must not be null");
  checkArgument(!Strings.isNullOrEmpty(response.getUid()), "uid must not be null or empty");
  this.uid = response.getUid();
  this.email = response.getEmail();
  this.phoneNumber = response.getPhoneNumber();
  this.emailVerified = response.isEmailVerified();
  this.displayName = response.getDisplayName();
  this.photoUrl = response.getPhotoUrl();
  this.disabled = response.isDisabled();
  if (response.getProviders() == null || response.getProviders().length == 0) {
    this.providers = new ProviderUserInfo[0];
  } else {
    this.providers = new ProviderUserInfo[response.getProviders().length];
    for (int i = 0; i < this.providers.length; i++) {
      this.providers[i] = new ProviderUserInfo(response.getProviders()[i]);
    }
  }
  this.tokensValidAfterTimestamp = response.getValidSince() * 1000;

  String lastRefreshAtRfc3339 = response.getLastRefreshAt();
  long lastRefreshAtMillis = 0;
  if (!Strings.isNullOrEmpty(lastRefreshAtRfc3339)) {
    lastRefreshAtMillis = DateTime.parseRfc3339(lastRefreshAtRfc3339).getValue();
  }

  this.userMetadata = new UserMetadata(
      response.getCreatedAt(), response.getLastLoginAt(), lastRefreshAtMillis);
  this.customClaims = parseCustomClaims(response.getCustomClaims(), jsonFactory);
}
 
Example #27
Source File: Authorizer.java    From mail-importer with Apache License 2.0 5 votes vote down vote up
private GoogleClientSecrets loadGoogleClientSecrets(JsonFactory jsonFactory)
    throws IOException {
  URL url = Resources.getResource("client_secret.json");
  CharSource inputSupplier =
      Resources.asCharSource(url, Charsets.UTF_8);
  return GoogleClientSecrets.load(jsonFactory, inputSupplier.openStream());
}
 
Example #28
Source File: AbstractJsonFactoryTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public void testParser_heterogeneousSchema_illegalValueType() throws Exception {
  JsonFactory factory = newFactory();
  JsonParser parser = factory.createJsonParser(POLYMORPHIC_NUMERIC_TYPE_1);
  try {
    parser.parse(PolymorphicWithIllegalValueType.class);
  } catch (IllegalArgumentException e) {
    return; // expected
  }
  fail("Expected IllegalArgumentException on class with illegal @JsonPolymorphicTypeMap type");
}
 
Example #29
Source File: ExportedUserRecord.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
ExportedUserRecord(User response, JsonFactory jsonFactory) {
  super(response, jsonFactory);
  String passwordHash = response.getPasswordHash();
  if (passwordHash != null && !passwordHash.equals(REDACTED_BASE64)) {
    this.passwordHash = passwordHash;
  } else {
    this.passwordHash = null;
  }
  this.passwordSalt = response.getPasswordSalt();
}
 
Example #30
Source File: AuthenticatorFactoryTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Override
CloudResourceManager buildCloudResourceManager(HttpTransport httpTransport,
                                               JsonFactory jsonFactory,
                                               GoogleCredential credential,
                                               String service) {
  return cloudResourceManager;
}