1 /*
2  * Copyright (C) 2023 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.adservices.cobalt;
18 
19 import android.annotation.NonNull;
20 import android.content.Context;
21 import android.content.res.AssetManager;
22 
23 import com.android.cobalt.domain.Project;
24 import com.android.internal.annotations.VisibleForTesting;
25 
26 import com.google.cobalt.CobaltRegistry;
27 import com.google.common.io.ByteStreams;
28 
29 import java.io.InputStream;
30 
31 /** Loads the Cobalt registry from a APK asset. */
32 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
33 public final class CobaltRegistryLoader {
34     private static final String REGISTRY_ASSET_FILE = "cobalt/cobalt_registry.binarypb";
35 
36     /**
37      * Get the Cobalt registry from the APK asset directory.
38      *
39      * @return the CobaltRegistry
40      */
41     @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
getRegistry(@onNull Context context)42     public static Project getRegistry(@NonNull Context context)
43             throws CobaltInitializationException {
44         if (!CobaltRegistryValidated.IS_REGISTRY_VALIDATED) {
45             throw new AssertionError(
46                     "Cobalt registry was not validated at build time, something is very wrong");
47         }
48 
49         AssetManager assetManager = context.getAssets();
50         try (InputStream inputStream = assetManager.open(REGISTRY_ASSET_FILE)) {
51             CobaltRegistry registry =
52                     CobaltRegistry.parseFrom(ByteStreams.toByteArray(inputStream));
53             return Project.create(registry);
54         } catch (Exception e) {
55             throw new CobaltInitializationException("Exception while reading registry", e);
56         }
57     }
58 }
59