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.service.measurement.reporting; 18 19 import android.annotation.NonNull; 20 import android.annotation.Nullable; 21 import android.net.Uri; 22 import android.util.Pair; 23 24 import com.android.adservices.service.measurement.util.UnsignedLong; 25 26 import org.json.JSONArray; 27 28 import java.util.ArrayList; 29 import java.util.Comparator; 30 import java.util.List; 31 import java.util.stream.Collectors; 32 33 /** Report related utility methods. */ 34 public class ReportUtil { 35 /** 36 * Prepares an alphabetical ordered list of attribution destinations for report JSON. If any 37 * elements are found to be null, they are added at last. 38 * 39 * @param destinations a list of attribution destinations 40 * @return an Object that is either String or JSONArray 41 */ 42 @Nullable serializeAttributionDestinations(@onNull List<Uri> destinations)43 public static Object serializeAttributionDestinations(@NonNull List<Uri> destinations) { 44 if (destinations.size() == 0) { 45 throw new IllegalArgumentException("Destinations list is empty"); 46 } 47 48 if (destinations.size() == 1) { 49 return destinations.get(0).toString(); 50 } else { 51 List<Uri> sortedDestinations = new ArrayList<>(destinations); 52 sortedDestinations.sort(Comparator.comparing(Uri::toString)); 53 return new JSONArray( 54 sortedDestinations.stream().map(Uri::toString).collect(Collectors.toList())); 55 } 56 } 57 58 /** 59 * Prepares a list of {@code UnsignedLong}s for report JSON. 60 * 61 * @param unsignedLongs a list of {@code UnsignedLong}s 62 * @return a JSONArray 63 */ 64 @Nullable serializeUnsignedLongs(@onNull List<UnsignedLong> unsignedLongs)65 public static JSONArray serializeUnsignedLongs(@NonNull List<UnsignedLong> unsignedLongs) { 66 return new JSONArray( 67 unsignedLongs.stream().map(UnsignedLong::toString).collect(Collectors.toList())); 68 } 69 70 /** 71 * Prepare summary bucket for report JSON 72 * 73 * @param summaryBucket the summary bucket 74 * @return the encoded summary bucket in format [start, end] 75 */ 76 @Nullable serializeSummaryBucket(@onNull Pair<Long, Long> summaryBucket)77 public static JSONArray serializeSummaryBucket(@NonNull Pair<Long, Long> summaryBucket) { 78 JSONArray result = new JSONArray(); 79 result.put(summaryBucket.first); 80 result.put(summaryBucket.second); 81 return result; 82 } 83 } 84