Merchant API code sample to update a data source.

### Java

    // Copyright 2024 Google LLC
    //
    // Licensed under the Apache License, Version 2.0 (the "License");
    // you may not use this file except in compliance with the License.
    // You may obtain a copy of the License at
    //
    //     https://www.apache.org/licenses/LICENSE-2.0
    //
    // Unless required by applicable law or agreed to in writing, software
    // distributed under the License is distributed on an "AS IS" BASIS,
    // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    // See the License for the specific language governing permissions and
    // limitations under the License.

    package shopping.merchant.samples.datasources.v1;
    import com.google.api.gax.core.FixedCredentialsProvider;
    import com.google.auth.oauth2.GoogleCredentials;
    import com.google.protobuf.FieldMask;
    import com.google.shopping.merchant.datasources.v1.DataSource;
    import com.google.shopping.merchant.datasources.v1.DataSourceName;
    import com.google.shopping.merchant.datasources.v1.DataSourceReference;
    import com.google.shopping.merchant.datasources.v1.DataSourcesServiceClient;
    import com.google.shopping.merchant.datasources.v1.DataSourcesServiceSettings;
    import com.google.shopping.merchant.datasources.v1.PrimaryProductDataSource;
    import com.google.shopping.merchant.datasources.v1.PrimaryProductDataSource.DefaultRule;
    import com.google.shopping.merchant.datasources.v1.UpdateDataSourceRequest;
    import shopping.merchant.samples.utils.Authenticator;
    import shopping.merchant.samples.utils.Config;

    /**
     * This class demonstrates how to update a datasource to change its name in the MC UI. It also
     * demonstrates how to update a primary datasource to add supplemental datasources to its default
     * rule (https://support.google.com/merchants/answer/7450276).
     */
    public class UpdateDataSourceSample {

      public static String updateDataSource(Config config, String displayName, String dataSourceId)
          throws Exception {
        GoogleCredentials credential = new Authenticator().authenticate();

        DataSourcesServiceSettings dataSourcesServiceSettings =
            DataSourcesServiceSettings.newBuilder()
                .setCredentialsProvider(FixedCredentialsProvider.create(credential))
                .build();

        // Creates datasource name to identify datasource.
        String name =
            DataSourceName.newBuilder()
                .setAccount(config.getAccountId().toString())
                .setDatasource(dataSourceId)
                .build()
                .toString();

        DataSource dataSource =
            DataSource.newBuilder()
                // Update the datasource to have the new display name
                .setDisplayName(displayName)
                .setName(name)
                .build();

        FieldMask fieldMask = FieldMask.newBuilder().addPaths("display_name").build();

        try (DataSourcesServiceClient dataSourcesServiceClient =
            DataSourcesServiceClient.create(dataSourcesServiceSettings)) {

          UpdateDataSourceRequest request =
              UpdateDataSourceRequest.newBuilder()
                  .setDataSource(dataSource)
                  .setUpdateMask(fieldMask)
                  .build();

          System.out.println("Sending Update DataSource request");
          DataSource response = dataSourcesServiceClient.updateDataSource(request);
          System.out.println("Updated DataSource Name below");
          System.out.println(response.getName());
          return response.getName();
        } catch (Exception e) {
          System.out.println(e);
          System.exit(1);
          return null;
        }
      }

      public String updateDataSource(
          Config config,
          String primaryDataSourceName,
          String firstSupplementalDataSourceName,
          String secondSupplementalDataSourceName)
          throws Exception {
        GoogleCredentials credential = new Authenticator().authenticate();

        DataSourcesServiceSettings dataSourcesServiceSettings =
            DataSourcesServiceSettings.newBuilder()
                .setCredentialsProvider(FixedCredentialsProvider.create(credential))
                .build();

        // Setting self to 'true' refers to the primary datasource itself.
        DataSourceReference dataSourceReferenceSelf =
            DataSourceReference.newBuilder().setSelf(true).build();
        DataSourceReference firstSupplementalDataSourceReference =
            DataSourceReference.newBuilder()
                .setSupplementalDataSourceName(firstSupplementalDataSourceName)
                .build();
        DataSourceReference secondSupplementalDataSourceReference =
            DataSourceReference.newBuilder()
                .setSupplementalDataSourceName(secondSupplementalDataSourceName)
                .build();

        // The attributes will first be taken from the primary DataSource.
        // Then the first supplemental DataSource if the attribute is not in the primary DataSource
        // And finally the second supplemental DataSource if not in the first two DataSources.
        // Note that CustomRules could change the behavior of how updates are applied.
        DefaultRule defaultRule =
            DefaultRule.newBuilder()
                .addTakeFromDataSources(dataSourceReferenceSelf)
                .addTakeFromDataSources(firstSupplementalDataSourceReference)
                .addTakeFromDataSources(secondSupplementalDataSourceReference)
                .build();

        // The type of data that this datasource will receive.
        PrimaryProductDataSource primaryProductDataSource =
            PrimaryProductDataSource.newBuilder().setDefaultRule(defaultRule).build();

        DataSource dataSource =
            DataSource.newBuilder()
                // Update the primary datasource to have the default rule datasources in the correct
                // order.
                .setPrimaryProductDataSource(primaryProductDataSource)
                .setName(primaryDataSourceName)
                .build();

        // The '.' signifies a nested field.
        FieldMask fieldMask =
            FieldMask.newBuilder().addPaths("primary_product_data_source.default_rule").build();

        try (DataSourcesServiceClient dataSourcesServiceClient =
            DataSourcesServiceClient.create(dataSourcesServiceSettings)) {

          UpdateDataSourceRequest request =
              UpdateDataSourceRequest.newBuilder()
                  .setDataSource(dataSource)
                  .setUpdateMask(fieldMask)
                  .build();

          System.out.println("Sending Update DataSource request");
          DataSource response = dataSourcesServiceClient.updateDataSource(request);
          System.out.println("Updated DataSource Name below");
          System.out.println(response.getName());
          return response.getName();
        } catch (Exception e) {
          System.out.println(e);
          System.exit(1);
          return null;
        }
      }

      public static void main(String[] args) throws Exception {
        Config config = Config.load();
        // The updated displayed datasource name in the Merchant Center UI.
        String displayName = "Great Britain Primary Product Data";

        // The ID of the datasource to update
        String dataSourceId = "11111111"; // Replace with your datasource ID.

        updateDataSource(config, displayName, dataSourceId);
      }
    }

### PHP

    <?php
    /**
     * Copyright 2024 Google LLC
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *     https://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */

    require_once __DIR__ . '/../../../vendor/autoload.php';
    require_once __DIR__ . '/../../Authentication/Authentication.php';
    require_once __DIR__ . '/../../Authentication/Config.php';
    use Google\ApiCore\ApiException;
    use Google\Protobuf\FieldMask;
    use Google\Shopping\Merchant\DataSources\V1\Client\DataSourcesServiceClient;
    use Google\Shopping\Merchant\DataSources\V1\DataSource;
    use Google\Shopping\Merchant\DataSources\V1\UpdateDataSourceRequest;

    /**
     * Class to demonstrate updating a datasource to change its name in the MC UI.
     */
    class UpdateDataSourceSample
    {
        // ENSURE you fill in the datasource ID for the sample to work.
        private const DATASOURCE_ID = 'INSERT_DATASOURCE_ID';

        /**
         * Updates a DataSource.
         *
         * @param int $merchantId The Merchant Center Account ID.
         * @param string $displayName The new display name of the data source.
         * @param string $dataSourceId The data source ID.
         * @return string The name of the updated data source.
         */
        public function updateDataSource(int $merchantId, string $displayName, string $dataSourceId): string
        {
            // Gets the OAuth credentials to make the request.
            $credentials = Authentication::useServiceAccountOrTokenFile();

            // Creates options config containing credentials for the client to use.
            $options = ['credentials' => $credentials];

            // Creates a client.
            $dataSourcesServiceClient = new DataSourcesServiceClient($options);

            // Creates the data source name.
            $name = sprintf('accounts/%s/dataSources/%s', $merchantId, $dataSourceId);

            // Creates the data source.
            $dataSource = (new DataSource())
                ->setDisplayName($displayName)
                ->setName($name);

            // Creates a FieldMask to specify which fields to update.
            $updateMask = new FieldMask([
                'paths' => ['display_name']
            ]);

            // Creates the request.
            $request = (new UpdateDataSourceRequest())
                ->setDataSource($dataSource)
                ->setUpdateMask($updateMask);

            print('Sending Update DataSource request' . PHP_EOL);

            // Calls the API and catches and prints any network failures/errors.
            try {
                $response = $dataSourcesServiceClient->updateDataSource($request);
                print('Updated DataSource Name below' . PHP_EOL);
                print($response->getName() . PHP_EOL);
                return $response->getName();
            } catch (ApiException $ex) {
                print('Call failed with message: ' . $ex->getMessage() . PHP_EOL);
                return '';
            }
        }

        // Helper to execute the sample.
        public function callSample(): void
        {
            $config = Config::generateConfig();
            // The Merchant Center Account ID.
            $merchantId = $config['accountId'];

            // The updated displayed datasource name in the Merchant Center UI.
            $displayName = 'new name';

            self::updateDataSource($merchantId, $displayName, self::DATASOURCE_ID);
        }
    }

    $sample = new UpdateDataSourceSample();
    $sample->callSample();

### Python

    # -*- coding: utf-8 -*-
    # Copyright 2024 Google LLC
    #
    # Licensed under the Apache License, Version 2.0 (the "License");
    # you may not use this file except in compliance with the License.
    # You may obtain a copy of the License at
    #
    #     http://www.apache.org/licenses/LICENSE-2.0
    #
    # Unless required by applicable law or agreed to in writing, software
    # distributed under the License is distributed on an "AS IS" BASIS,
    # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    # See the License for the specific language governing permissions and
    # limitations under the License.
    """A module to update a DataSource."""

    from examples.authentication import configuration
    from examples.authentication import generate_user_credentials
    from google.protobuf import field_mask_pb2
    from google.shopping import merchant_datasources_v1

    # ENSURE you fill in the datasource ID for the sample to
    # work.
    _ACCOUNT = configuration.Configuration().read_merchant_info()
    # An ID automatically assigned to the datasource after creation by Google.
    _DATASOURCE = "[INSERT_DATASOURCE_HERE]"
    _NAME = f"accounts/{_ACCOUNT}/dataSources/{_DATASOURCE}"


    def update_data_source():
      """Updates the specified `DataSource` resource."""

      # Gets OAuth Credentials.
      credentials = generate_user_credentials.main()

      # Creates a client.
      client = merchant_datasources_v1.DataSourcesServiceClient(
          credentials=credentials
      )

      # Creates a DataSource and populates its attributes.
      data_source = merchant_datasources_v1.DataSource()
      data_source.name = _NAME  # To identify the data source to update.
      data_source.display_name = "Example DataSource 2"

      # Sets field mask to include only the fields you want to update.
      field_mask = field_mask_pb2.FieldMask(paths=["display_name"])

      # Creates the request.
      request = merchant_datasources_v1.UpdateDataSourceRequest(
          data_source=data_source, update_mask=field_mask
      )

      # Makes the request and catch and print any error messages.
      try:
        client.update_data_source(request=request)
        print("Update successful")
      except RuntimeError as e:
        print("Update failed")
        print(e)


    if __name__ == "__main__":
      update_data_source()