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.measurement.util; 18 19 import android.net.Uri; 20 21 import com.google.common.net.InternetDomainName; 22 23 import java.util.Optional; 24 25 /** Web utilities for measurement. */ 26 public final class Web { 27 Web()28 private Web() { } 29 30 /** 31 * Returns a {@code Uri} of the scheme concatenated with the first subdomain of the provided URL 32 * that is beneath the public suffix. 33 * 34 * @param uri the Uri to parse. 35 */ topPrivateDomainAndScheme(Uri uri)36 public static Optional<Uri> topPrivateDomainAndScheme(Uri uri) { 37 return domainAndScheme(uri, false); 38 } 39 40 /** 41 * Returns an origin of {@code Uri} that is defined by the concatenation of scheme (protocol), 42 * hostname (domain), and port. 43 * 44 * @param uri the Uri to parse. 45 * @return 46 */ originAndScheme(Uri uri)47 public static Optional<Uri> originAndScheme(Uri uri) { 48 return domainAndScheme(uri, true); 49 } 50 51 /** 52 * Returns an origin of {@code Uri} that is defined by the concatenation of scheme (protocol), 53 * hostname (domain), and port if useOrigin is true. If useOrigin is false the method returns 54 * the scheme concatenation of first subdomain that is beneath the public suffix. 55 * 56 * @param uri the Uri to parse 57 * @param useOrigin true if extract origin, false if extract only top domain 58 */ domainAndScheme(Uri uri, boolean useOrigin)59 private static Optional<Uri> domainAndScheme(Uri uri, boolean useOrigin) { 60 String scheme = uri.getScheme(); 61 String host = uri.getHost(); 62 int port = uri.getPort(); 63 64 if (scheme == null || host == null) { 65 return Optional.empty(); 66 } 67 68 try { 69 InternetDomainName domainName = InternetDomainName.from(host); 70 InternetDomainName domain = useOrigin ? domainName : domainName.topPrivateDomain(); 71 String url = scheme + "://" + domain; 72 if (useOrigin && port >= 0) { 73 url += ":" + port; 74 } 75 return Optional.of(Uri.parse(url)); 76 } catch (IllegalArgumentException | IllegalStateException e) { 77 return Optional.empty(); 78 } 79 } 80 } 81