Java Code Examples for com.google.api.client.json.jackson2.JacksonFactory#getDefaultInstance()

The following examples show how to use com.google.api.client.json.jackson2.JacksonFactory#getDefaultInstance() . 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: 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 List<DeviceState> getDeviceStates(
    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 states " + devicePath);

  ListDeviceStatesResponse resp =
      service.projects().locations().registries().devices().states().list(devicePath).execute();

  return resp.getDeviceStates();
}
 
Example 2
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 3
Source File: DriveSyncProvider.java    From science-journal with Apache License 2.0 6 votes vote down vote up
private void addServiceForAccount(AppAccount appAccount) {


    HttpTransport transport = AndroidHttp.newCompatibleTransport();
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    accountMap.put(
        appAccount,
        new DriveSyncManager(
            appAccount,
            AppSingleton.getInstance(applicationContext).getDataController(appAccount),
            transport,
            jsonFactory,
            applicationContext,
            driveSupplier,
            AppSingleton.getInstance(applicationContext)
                .getSensorEnvironment()
                .getDataController(appAccount)));
  }
 
Example 4
Source File: CloudiotPubsubExampleServer.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/** Delete this device from Cloud IoT. */
public static void deleteDevice(
    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("Deleting device " + devicePath);
  service.projects().locations().registries().devices().delete(devicePath).execute();
}
 
Example 5
Source File: DeviceRegistryExample.java    From java-docs-samples with 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 6
Source File: DeviceRegistryExample.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/** Retrieves IAM permissions for the given registry. */
protected static void getIamPermissions(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 registryPath =
      String.format(
          "projects/%s/locations/%s/registries/%s", projectId, cloudRegion, registryName);

  com.google.api.services.cloudiot.v1.model.Policy policy =
      service
          .projects()
          .locations()
          .registries()
          .getIamPolicy(registryPath, new GetIamPolicyRequest())
          .execute();

  System.out.println("Policy ETAG: " + policy.getEtag());

  if (policy.getBindings() != null) {
    for (com.google.api.services.cloudiot.v1.model.Binding binding : policy.getBindings()) {
      System.out.println(String.format("Role: %s", binding.getRole()));
      System.out.println("Binding members: ");
      for (String member : binding.getMembers()) {
        System.out.println(String.format("\t%s", member));
      }
    }
  } else {
    System.out.println(String.format("No policy bindings for %s", registryName));
  }
}
 
Example 7
Source File: FaceDetectApp.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/** Connects to the Vision API using Application Default Credentials. */
public static Vision getVisionService() throws IOException, GeneralSecurityException {
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault().createScoped(VisionScopes.all());
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  return new Vision.Builder(
          GoogleNetHttpTransport.newTrustedTransport(),
          jsonFactory,
          new HttpCredentialsAdapter(credential))
      .setApplicationName(APPLICATION_NAME)
      .build();
}
 
Example 8
Source File: DirectoryFacade.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Builder for DirectoryFacade objects.
 *
 * @param serviceKeyStream {@link InputStream} for the JSON file containing the service account
 *   key to authenticate with the Cloud Identity service.
 * @param adminEmail the email of the domain's admin account
 * @param domain the organization's domain
 */

static DirectoryFacade create(
    InputStream serviceKeyStream, String adminEmail, String domain)
    throws IOException, GeneralSecurityException {
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
  GoogleCredential credential = GoogleCredential
      .fromStream(serviceKeyStream)
      .createScoped(ADMIN_SCOPES);
  Credential adminCredential = new GoogleCredential.Builder()
      .setTransport(httpTransport)
      .setJsonFactory(jsonFactory)
      .setServiceAccountId(credential.getServiceAccountId())
      .setServiceAccountPrivateKey(credential.getServiceAccountPrivateKey())
      .setServiceAccountScopes(ADMIN_SCOPES)
      .setServiceAccountUser(adminEmail)
      .build();
  // 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);
  Directory.Builder directoryBuilder = new Directory.Builder(
      httpTransport, jsonFactory, request -> {
    adminCredential.initialize(request);
    requestInitializer.initialize(request);
  });
  Directory directory = directoryBuilder.build();
  return new DirectoryFacade(directory, domain);
}
 
Example 9
Source File: DeviceRegistryExample.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/** Print all of the devices in this registry to standard out. */
protected static void listDevices(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 registryPath =
      String.format(
          "projects/%s/locations/%s/registries/%s", projectId, cloudRegion, registryName);

  List<Device> devices =
      service
          .projects()
          .locations()
          .registries()
          .devices()
          .list(registryPath)
          .execute()
          .getDevices();

  if (devices != null) {
    System.out.println("Found " + devices.size() + " devices");
    for (Device d : devices) {
      System.out.println("Id: " + d.getId());
      if (d.getConfig() != null) {
        // Note that this will show the device config in Base64 encoded format.
        System.out.println("Config: " + d.getConfig().toPrettyString());
      }
      System.out.println();
    }
  } else {
    System.out.println("Registry has no devices.");
  }
}
 
Example 10
Source File: DeviceRegistryExample.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/** Lists all of the registries associated with the given project. */
protected static void listRegistries(String projectId, String cloudRegion)
    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 projectPath = "projects/" + projectId + "/locations/" + cloudRegion;

  List<DeviceRegistry> registries =
      service
          .projects()
          .locations()
          .registries()
          .list(projectPath)
          .execute()
          .getDeviceRegistries();

  if (registries != null) {
    System.out.println("Found " + registries.size() + " registries");
    for (DeviceRegistry r : registries) {
      System.out.println("Id: " + r.getId());
      System.out.println("Name: " + r.getName());
      if (r.getMqttConfig() != null) {
        System.out.println("Config: " + r.getMqttConfig().toPrettyString());
      }
      System.out.println();
    }
  } else {
    System.out.println("Project has no registries.");
  }
}
 
Example 11
Source File: DeviceRegistryExample.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/** Create a registry for Cloud IoT. */
protected static void createRegistry(
    String cloudRegion, String projectId, String registryName, String pubsubTopicPath)
    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 projectPath = "projects/" + projectId + "/locations/" + cloudRegion;
  final String fullPubsubPath = "projects/" + projectId + "/topics/" + pubsubTopicPath;

  DeviceRegistry registry = new DeviceRegistry();
  EventNotificationConfig notificationConfig = new EventNotificationConfig();
  notificationConfig.setPubsubTopicName(fullPubsubPath);
  List<EventNotificationConfig> notificationConfigs = new ArrayList<EventNotificationConfig>();
  notificationConfigs.add(notificationConfig);
  registry.setEventNotificationConfigs(notificationConfigs);
  registry.setId(registryName);

  DeviceRegistry reg =
      service.projects().locations().registries().create(projectPath, registry).execute();
  System.out.println("Created registry: " + reg.getName());
}
 
Example 12
Source File: DeviceRegistryExample.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
protected static void unbindDeviceFromGateway(
    String projectId, String cloudRegion, String registryName, String deviceId, String gatewayId)
    throws GeneralSecurityException, IOException {
  // [START iot_unbind_device_from_gateway]
  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 registryPath =
      String.format(
          "projects/%s/locations/%s/registries/%s", projectId, cloudRegion, registryName);

  UnbindDeviceFromGatewayRequest request = new UnbindDeviceFromGatewayRequest();
  request.setDeviceId(deviceId);
  request.setGatewayId(gatewayId);

  UnbindDeviceFromGatewayResponse response =
      service
          .projects()
          .locations()
          .registries()
          .unbindDeviceFromGateway(registryPath, request)
          .execute();

  System.out.println(String.format("Device unbound: %s", response.toPrettyString()));
  // [END iot_unbind_device_from_gateway]
}
 
Example 13
Source File: CloudiotPubsubExampleServer.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/** Create a registry for Cloud IoT. */
public static void createRegistry(
    String cloudRegion, String projectId, String registryName, String pubsubTopicPath)
    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 projectPath = "projects/" + projectId + "/locations/" + cloudRegion;
  final String fullPubsubPath = "projects/" + projectId + "/topics/" + pubsubTopicPath;

  DeviceRegistry registry = new DeviceRegistry();
  EventNotificationConfig notificationConfig = new EventNotificationConfig();
  notificationConfig.setPubsubTopicName(fullPubsubPath);
  List<EventNotificationConfig> notificationConfigs = new ArrayList<EventNotificationConfig>();
  notificationConfigs.add(notificationConfig);
  registry.setEventNotificationConfigs(notificationConfigs);
  registry.setId(registryName);

  DeviceRegistry reg =
      service.projects().locations().registries().create(projectPath, registry).execute();
  System.out.println("Created registry: " + reg.getName());
}
 
Example 14
Source File: DeviceRegistryExample.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/** Send a command to a device. * */
// [START iot_send_command]
protected static void sendCommand(
    String deviceId, String projectId, String cloudRegion, String registryName, String data)
    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);

  SendCommandToDeviceRequest req = new SendCommandToDeviceRequest();

  // Data sent through the wire has to be base64 encoded.
  Base64.Encoder encoder = Base64.getEncoder();
  String encPayload = encoder.encodeToString(data.getBytes(StandardCharsets.UTF_8.name()));
  req.setBinaryData(encPayload);
  System.out.printf("Sending command to %s%n", devicePath);

  service
      .projects()
      .locations()
      .registries()
      .devices()
      .sendCommandToDevice(devicePath, req)
      .execute();

  System.out.println("Command response: sent");
}
 
Example 15
Source File: DeviceRegistryExample.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
/** Patch the device to add an ES256 key for authentication. */
protected static void patchEs256ForAuth(
    String deviceId,
    String publicKeyFilePath,
    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);

  PublicKeyCredential publicKeyCredential = new PublicKeyCredential();
  String key = Files.toString(new File(publicKeyFilePath), Charsets.UTF_8);
  publicKeyCredential.setKey(key);
  publicKeyCredential.setFormat("ES256_PEM");

  DeviceCredential devCredential = new DeviceCredential();
  devCredential.setPublicKey(publicKeyCredential);

  Device device = new Device();
  device.setCredentials(Collections.singletonList(devCredential));

  Device patchedDevice =
      service
          .projects()
          .locations()
          .registries()
          .devices()
          .patch(devicePath, device)
          .setUpdateMask("credentials")
          .execute();

  System.out.println("Patched device is " + patchedDevice.toPrettyString());
}
 
Example 16
Source File: Modules.java    From nomulus with Apache License 2.0 4 votes vote down vote up
@Provides
static JsonFactory provideJsonFactory() {
  return JacksonFactory.getDefaultInstance();
}
 
Example 17
Source File: DeviceRegistryExample.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
/** Create a device that is authenticated using ES256. */
protected static void createDeviceWithEs256(
    String deviceId,
    String publicKeyFilePath,
    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 registryPath =
      String.format(
          "projects/%s/locations/%s/registries/%s", projectId, cloudRegion, registryName);

  PublicKeyCredential publicKeyCredential = new PublicKeyCredential();
  final String key = Files.toString(new File(publicKeyFilePath), Charsets.UTF_8);
  publicKeyCredential.setKey(key);
  publicKeyCredential.setFormat("ES256_PEM");

  DeviceCredential devCredential = new DeviceCredential();
  devCredential.setPublicKey(publicKeyCredential);

  System.out.println("Creating device with id: " + deviceId);
  Device device = new Device();
  device.setId(deviceId);
  device.setCredentials(Collections.singletonList(devCredential));

  Device createdDevice =
      service
          .projects()
          .locations()
          .registries()
          .devices()
          .create(registryPath, device)
          .execute();

  System.out.println("Created device: " + createdDevice.toPrettyString());
}
 
Example 18
Source File: DeviceRegistryExample.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
/** Patch the device to add an RSA256 key for authentication. */
protected static void patchRsa256ForAuth(
    String deviceId,
    String publicKeyFilePath,
    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);

  PublicKeyCredential publicKeyCredential = new PublicKeyCredential();
  String key = Files.toString(new File(publicKeyFilePath), Charsets.UTF_8);
  publicKeyCredential.setKey(key);
  publicKeyCredential.setFormat("RSA_X509_PEM");

  DeviceCredential devCredential = new DeviceCredential();
  devCredential.setPublicKey(publicKeyCredential);

  Device device = new Device();
  device.setCredentials(Collections.singletonList(devCredential));

  Device patchedDevice =
      service
          .projects()
          .locations()
          .registries()
          .devices()
          .patch(devicePath, device)
          .setUpdateMask("credentials")
          .execute();

  System.out.println("Patched device is " + patchedDevice.toPrettyString());
}
 
Example 19
Source File: CloudiotPubsubExampleServer.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
/** Create a device to bind to a gateway. */
public static void createDevice(
    String projectId, String cloudRegion, String registryName, String deviceId)
    throws GeneralSecurityException, IOException {
  // [START create_device]
  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 registryPath =
      String.format(
          "projects/%s/locations/%s/registries/%s", projectId, cloudRegion, registryName);

  List<Device> devices =
      service
          .projects()
          .locations()
          .registries()
          .devices()
          .list(registryPath)
          .setFieldMask("config,gatewayConfig")
          .execute()
          .getDevices();

  if (devices != null) {
    System.out.println("Found " + devices.size() + " devices");
    for (Device d : devices) {
      if ((d.getId() != null && d.getId().equals(deviceId))
          || (d.getName() != null && d.getName().equals(deviceId))) {
        System.out.println("Device exists, skipping.");
        return;
      }
    }
  }

  System.out.println("Creating device with id: " + deviceId);
  Device device = new Device();
  device.setId(deviceId);

  GatewayConfig gwConfig = new GatewayConfig();
  gwConfig.setGatewayType("NON_GATEWAY");
  gwConfig.setGatewayAuthMethod("ASSOCIATION_ONLY");

  device.setGatewayConfig(gwConfig);
  Device createdDevice =
      service
          .projects()
          .locations()
          .registries()
          .devices()
          .create(registryPath, device)
          .execute();

  System.out.println("Created device: " + createdDevice.toPrettyString());
  // [END create_device]
}
 
Example 20
Source File: IndexingServiceTest.java    From connector-sdk with Apache License 2.0 4 votes vote down vote up
@Test
@Parameters({"SYNCHRONOUS", "ASYNCHRONOUS"})
public void fromConfiguration_apiDefaultRequestMode_isSet(String testRequestMode)
    throws Exception {
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  CredentialFactory credentialFactory =
      scopes ->
          new MockGoogleCredential.Builder()
              .setTransport(transport)
              .setJsonFactory(jsonFactory)
              .build();
  Properties config = new Properties();
  config.put(IndexingServiceImpl.SOURCE_ID, "sourceId");
  config.put(IndexingServiceImpl.IDENTITY_SOURCE_ID, "identitySourceId");
  File serviceAcctFile = temporaryFolder.newFile("serviceaccount.json");
  config.put(
      LocalFileCredentialFactory.SERVICE_ACCOUNT_KEY_FILE_CONFIG,
      serviceAcctFile.getAbsolutePath());
  config.put(IndexingServiceImpl.INDEXING_SERVICE_REQUEST_MODE, testRequestMode);
  setupConfig.initConfig(config);
  ListenableFuture<Operation> expected = Futures.immediateFuture(new Operation());
  when(batchingService.indexItem(any())).thenReturn(expected);

  IndexingServiceImpl.Builder indexingServiceBuilder =
      IndexingServiceImpl.Builder.fromConfiguration(Optional.empty(), "unitTest");
  this.indexingService = indexingServiceBuilder
      .setTransport(transport)
      .setCredentialFactory(credentialFactory)
      .setService(cloudSearch)
      .setBatchingIndexingService(batchingService)
      .setContentUploadService(contentUploadService)
      .setContentUploadThreshold(CONTENT_UPLOAD_THRESHOLD)
      .setServiceManagerHelper(serviceManagerHelper)
      .setQuotaServer(quotaServer)
      .build();
  this.indexingService.startAsync().awaitRunning();

  indexingService.deleteItem(GOOD_ID, "abc".getBytes(UTF_8), RequestMode.UNSPECIFIED);
  verify(batchingService).deleteItem(deleteCaptor.capture());
  Items.Delete deleteRequest = deleteCaptor.getValue();
  assertEquals(testRequestMode, deleteRequest.getMode());

  indexingService.indexItem(new Item().setName(GOOD_ID), RequestMode.UNSPECIFIED);
  verify(batchingService).indexItem(indexCaptor.capture());
  Items.Index updateRequest = indexCaptor.getValue();
  IndexItemRequest indexItemRequest = (IndexItemRequest) updateRequest.getJsonContent();
  assertEquals(testRequestMode, indexItemRequest.getMode());
}