1 /*
2  * Copyright (C) 2022 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.service.topics;
18 
19 import android.content.Context;
20 
21 import com.android.adservices.data.topics.Topic;
22 
23 import com.google.common.collect.ImmutableList;
24 
25 import java.util.Locale;
26 import java.util.stream.Collectors;
27 
28 /**
29  * Utility class providing static methods to map {@link Topic#getTopicId()} to Android resource
30  * string (R). This is possible because the names of the topics are formatted: "topic{topicId}".
31  *
32  * <p>E.g. <string name="topic10001">/Arts &amp; Entertainment</string>
33  */
34 public class TopicsMapper {
35 
36     /** @return a Android resource Id for provided {@link Topic} or 0 if it doesn't exist. */
getResourceIdByTopic(Topic topic, Context context)37     public static int getResourceIdByTopic(Topic topic, Context context) {
38         return context.getResources()
39                 .getIdentifier(
40                         String.format(Locale.ENGLISH, "topic%d", topic.getTopic()),
41                         "string",
42                         context.getPackageName());
43     }
44 
45     /**
46      * @return an {@link ImmutableList<Integer>} containing Android resource Ids generated from
47      *     provided {@link ImmutableList<Topic>}.
48      */
getResourcesIdMapByTopicsList( ImmutableList<Topic> topics, Context context)49     public static ImmutableList<Integer> getResourcesIdMapByTopicsList(
50             ImmutableList<Topic> topics, Context context) {
51         return ImmutableList.copyOf(
52                 topics.stream()
53                         .map(topic -> getResourceIdByTopic(topic, context))
54                         .collect(Collectors.toList()));
55     }
56 }
57