• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright 2017 Google Inc. All Rights Reserved.
3  *
4  * <p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
5  * except in compliance with the License. You may obtain a copy of the License at
6  *
7  * <p>http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * <p>Unless required by applicable law or agreed to in writing, software distributed under the
10  * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
11  * express or implied. See the License for the specific language governing permissions and
12  * limitations under the License.
13  */
14 package com.android.vts.util;
15 
16 import java.net.MalformedURLException;
17 import java.net.URI;
18 import java.net.URISyntaxException;
19 import java.net.URL;
20 
21 /** UrlUtil, a helper class for formatting and validating URLs. */
22 public class UrlUtil {
23     private static final String HTTPS = "https";
24 
25     public static class LinkDisplay {
26         public final String name;
27         public final String url;
28 
29         /**
30          * Create a link display object.
31          *
32          * @param uri The hyperlink URI.
33          */
LinkDisplay(URI uri)34         public LinkDisplay(URI uri) {
35             this.url = uri.toString();
36 
37             // Parse the name from the URI path
38             int lastSeparator = uri.getPath().lastIndexOf('/');
39             if (lastSeparator < 0) {
40                 this.name = uri.toString();
41             } else {
42                 this.name = uri.getPath().substring(lastSeparator + 1);
43             }
44         }
45     }
46 
47     /**
48      * Validates and formats a URL.
49      *
50      * <p>Ensures that the protocol is HTTPs and the URL is properly formatted. This avoids link
51      * issues in the UI and possible vulnerabilities due to embedded JS in URLs.
52      *
53      * @param urlString The url string to validate.
54      * @returns The validated LinkDisplay object.
55      */
processUrl(String urlString)56     public static LinkDisplay processUrl(String urlString) {
57         try {
58             URL url = new URL(urlString);
59             String scheme = url.getProtocol();
60             String userInfo = url.getUserInfo();
61             String host = url.getHost();
62             int port = url.getPort();
63             String path = url.getPath();
64             String query = url.getQuery();
65             String fragment = url.getRef();
66             if (!url.getProtocol().equals(HTTPS))
67                 throw new MalformedURLException();
68             URI uri = new URI(scheme, userInfo, host, port, path, query, fragment);
69             return new LinkDisplay(uri);
70         } catch (MalformedURLException | URISyntaxException e) {
71             return null;
72         }
73     }
74 }
75