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

The following examples show how to use com.google.api.client.json.JsonFactory. These examples are extracted from open source projects. 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 Project: mirror   Author: jreyes   File: AuthorizationFlow.java    License: 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 #2
Source Project: google-api-java-client   Author: googleapis   File: AppIdentityCredentialTest.java    License: 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 #3
Source Project: googleads-shopping-samples   Author: googleads   File: ContentWorkflowSample.java    License: 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 #4
Source Project: beam   Author: apache   File: InjectorUtils.java    License: 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 #5
Source Project: connector-sdk   Author: google-cloudsearch   File: LocalFileCredentialFactoryTest.java    License: 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 #6
Source Project: connector-sdk   Author: google-cloudsearch   File: LocalFileCredentialFactoryTest.java    License: 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 #7
Source Project: google-http-java-client   Author: googleapis   File: AbstractJsonFactoryTest.java    License: 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 #8
Source Project: cloud-pubsub-samples-java   Author: googlearchive   File: PubsubUtils.java    License: 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 #9
Source Project: connector-sdk   Author: google-cloudsearch   File: CloudIdentityFacade.java    License: 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 #10
Source Project: google-http-java-client   Author: googleapis   File: AbstractJsonFactoryTest.java    License: 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 #11
Source Project: daq   Author: faucetsdn   File: CloudIotManager.java    License: 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 #12
Source Project: policyscanner   Author: GoogleCloudPlatform   File: GCPProject.java    License: 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 #13
Source Project: google-http-java-client   Author: googleapis   File: AbstractJsonFactoryTest.java    License: 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 #14
Source Project: google-http-java-client   Author: googleapis   File: AbstractJsonFactoryTest.java    License: 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 #15
Source Project: googleads-adxbuyer-examples   Author: googleads   File: BuyerServiceHelper.java    License: 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 #16
Source Project: google-http-java-client   Author: googleapis   File: AbstractJsonFactoryTest.java    License: 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 #17
Source Project: java-docs-samples   Author: GoogleCloudPlatform   File: DeviceRegistryExample.java    License: 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 #18
Source Project: firebase-admin-java   Author: firebase   File: FirebaseUserManagerTest.java    License: 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 #19
Source Project: google-http-java-client   Author: googleapis   File: AbstractJsonFactoryTest.java    License: 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 #20
Source Project: HotswapAgentExamples   Author: HotswapProjects   File: DevelopersSharedModule.java    License: 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 Project: kayenta   Author: spinnaker   File: GoogleClientFactory.java    License: Apache License 2.0 5 votes vote down vote up
public Storage getStorage() throws IOException {
  HttpTransport httpTransport = buildHttpTransport();
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  GoogleCredentials credentials = getCredentials(StorageScopes.all());
  HttpRequestInitializer reqInit = setHttpTimeout(credentials);
  String applicationName = "Spinnaker/" + applicationVersion;

  return new Storage.Builder(httpTransport, jsonFactory, reqInit)
      .setApplicationName(applicationName)
      .build();
}
 
Example #22
Source Project: nomulus   Author: google   File: AuthModule.java    License: Apache License 2.0 5 votes vote down vote up
@Provides
public static GoogleAuthorizationCodeFlow provideAuthorizationCodeFlow(
    JsonFactory jsonFactory,
    GoogleClientSecrets clientSecrets,
    @Config("localCredentialOauthScopes") ImmutableList<String> requiredOauthScopes,
    AbstractDataStoreFactory dataStoreFactory) {
  try {
    return new GoogleAuthorizationCodeFlow.Builder(
        new NetHttpTransport(), jsonFactory, clientSecrets, requiredOauthScopes)
        .setDataStoreFactory(dataStoreFactory)
        .build();
  } catch (IOException ex) {
    throw new RuntimeException(ex);
  }
}
 
Example #23
Source Project: google-api-java-client   Author: googleapis   File: AbstractGoogleJsonClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param transport HTTP transport
 * @param jsonFactory JSON factory
 * @param rootUrl root URL of the service
 * @param servicePath service path
 * @param httpRequestInitializer HTTP request initializer or {@code null} for none
 * @param legacyDataWrapper whether using the legacy data wrapper in responses
 */
protected Builder(HttpTransport transport, JsonFactory jsonFactory, String rootUrl,
    String servicePath, HttpRequestInitializer httpRequestInitializer,
    boolean legacyDataWrapper) {
  super(transport, rootUrl, servicePath, new JsonObjectParser.Builder(
      jsonFactory).setWrapperKeys(
      legacyDataWrapper ? Arrays.asList("data", "error") : Collections.<String>emptySet())
      .build(), httpRequestInitializer);
}
 
Example #24
Source Project: policyscanner   Author: GoogleCloudPlatform   File: GCSFilesSource.java    License: Apache License 2.0 5 votes vote down vote up
private static Storage constructStorageApiStub() throws GeneralSecurityException, IOException {
  JsonFactory jsonFactory = new JacksonFactory();
  HttpTransport transport;
  transport = GoogleNetHttpTransport.newTrustedTransport();
  GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
  if (credential.createScopedRequired()) {
    Collection<String> scopes = StorageScopes.all();
    credential = credential.createScoped(scopes);
  }
  return new Storage.Builder(transport, jsonFactory, credential)
      .setApplicationName("GCS Samples")
      .build();
}
 
Example #25
Source Project: android-oauth-client   Author: wuman   File: FileCredentialStore.java    License: 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();
  }
}
 
Example #26
Source Project: google-http-java-client   Author: googleapis   File: AbstractJsonFactoryTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testParser_polymorphicClass_selfReferencing() throws Exception {
  JsonFactory factory = newFactory();
  JsonParser parser = factory.createJsonParser(POLYMORPHIC_SELF_REFERENCING);
  PolymorphicSelfReferencing p = parser.parse(PolymorphicSelfReferencing.class);
  assertEquals(PolymorphicSelfReferencing.class, p.getClass());
  assertEquals(POLYMORPHIC_SELF_REFERENCING, factory.toString(p));
  assertEquals("self", p.type);
  assertEquals("blah", p.info);
}
 
Example #27
Source Project: google-http-java-client   Author: googleapis   File: AbstractJsonFactoryTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testParser_polymorphicClass_noMatchingTypeKey() throws Exception {
  JsonFactory factory = newFactory();
  JsonParser parser = factory.createJsonParser(POLYMORPHIC_WITH_UNKNOWN_KEY);
  try {
    parser.parse(Animal.class);
  } catch (IllegalArgumentException e) {
    return; // expected
  }
  fail("Expected IllegalArgumentException when provided with unknown typeDef key");
}
 
Example #28
Source Project: java-docs-samples   Author: GoogleCloudPlatform   File: DeviceRegistryExample.java    License: Apache License 2.0 5 votes vote down vote up
/** List all of the configs for the given device. */
protected static void listDeviceConfigs(
    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("Listing device configs for " + devicePath);
  List<DeviceConfig> deviceConfigs =
      service
          .projects()
          .locations()
          .registries()
          .devices()
          .configVersions()
          .list(devicePath)
          .execute()
          .getDeviceConfigs();

  for (DeviceConfig config : deviceConfigs) {
    System.out.println("Config version: " + config.getVersion());
    System.out.println("Contents: " + config.getBinaryData());
    System.out.println();
  }
}
 
Example #29
Source Project: halyard   Author: spinnaker   File: GoogleProfileReader.java    License: Apache License 2.0 5 votes vote down vote up
private Storage createGoogleStorage(boolean useApplicationDefaultCreds) {
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  String applicationName = "Spinnaker/Halyard";
  HttpRequestInitializer requestInitializer = null;

  if (useApplicationDefaultCreds) {
    try {
      com.google.auth.oauth2.GoogleCredentials credentials =
          com.google.auth.oauth2.GoogleCredentials.getApplicationDefault();
      if (credentials.createScopedRequired()) {
        credentials =
            credentials.createScoped(
                Collections.singleton(StorageScopes.DEVSTORAGE_FULL_CONTROL));
      }
      requestInitializer = GoogleCredentials.setHttpTimeout(credentials);
      log.info("Loaded application default credential for reading BOMs & profiles.");
    } catch (Exception e) {
      log.debug(
          "No application default credential could be loaded for reading BOMs & profiles. Continuing unauthenticated: {}",
          e.getMessage());
    }
  }
  if (requestInitializer == null) {
    requestInitializer = GoogleCredentials.retryRequestInitializer();
  }

  return new Storage.Builder(
          GoogleCredentials.buildHttpTransport(), jsonFactory, requestInitializer)
      .setApplicationName(applicationName)
      .build();
}
 
Example #30
Source Project: google-http-java-client   Author: googleapis   File: AbstractJsonFactoryTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testParser_doubleListTypeVariableType() throws Exception {
  // parse
  JsonFactory factory = newFactory();
  JsonParser parser;
  parser = factory.createJsonParser(DOUBLE_LIST_TYPE_VARIABLE_TYPE);
  parser.nextToken();
  DoubleListTypeVariableType result = parser.parse(DoubleListTypeVariableType.class);
  // serialize
  assertEquals(DOUBLE_LIST_TYPE_VARIABLE_TYPE, factory.toString(result));
  // check parsed result
  // array
  List<Double>[][] arr = result.arr;
  assertEquals(2, arr.length);
  assertEquals(Data.nullOf(List[].class), arr[0]);
  List<Double>[] subArr = arr[1];
  assertEquals(2, subArr.length);
  assertEquals(Data.nullOf(ArrayList.class), subArr[0]);
  List<Double> arrValue = subArr[1];
  assertEquals(1, arrValue.size());
  Double dValue = arrValue.get(0);
  assertEquals(1.0, dValue);
  // collection
  LinkedList<LinkedList<List<Double>>> list = result.list;
  assertEquals(2, list.size());
  assertEquals(Data.nullOf(LinkedList.class), list.get(0));
  LinkedList<List<Double>> subList = list.get(1);
  assertEquals(2, subList.size());
  assertEquals(Data.nullOf(ArrayList.class), subList.get(0));
  arrValue = subList.get(1);
  assertEquals(ImmutableList.of(Double.valueOf(1)), arrValue);
  // null value
  List<Double> nullValue = result.nullValue;
  assertEquals(Data.nullOf(ArrayList.class), nullValue);
  // value
  List<Double> value = result.value;
  assertEquals(ImmutableList.of(Double.valueOf(1)), value);
}