diff --git a/android-studio-project/ExoPlayer-AirPlay-Receiver/src/main/java/com/github/warren_bank/exoplayer_airplay_receiver/exoplayer2/VideoSource.java b/android-studio-project/ExoPlayer-AirPlay-Receiver/src/main/java/com/github/warren_bank/exoplayer_airplay_receiver/exoplayer2/VideoSource.java index 29d162b..2e8d141 100644 --- a/android-studio-project/ExoPlayer-AirPlay-Receiver/src/main/java/com/github/warren_bank/exoplayer_airplay_receiver/exoplayer2/VideoSource.java +++ b/android-studio-project/ExoPlayer-AirPlay-Receiver/src/main/java/com/github/warren_bank/exoplayer_airplay_receiver/exoplayer2/VideoSource.java @@ -2,7 +2,7 @@ import com.github.warren_bank.exoplayer_airplay_receiver.utils.ExternalStorageUtils; import com.github.warren_bank.exoplayer_airplay_receiver.utils.MediaTypeUtils; -import com.github.warren_bank.exoplayer_airplay_receiver.utils.StringUtils; +import com.github.warren_bank.exoplayer_airplay_receiver.utils.UriUtils; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.MediaItem; @@ -82,11 +82,11 @@ private VideoSource( ) { // enforce that URLs are encoded and RFC 2396-compliant if (!TextUtils.isEmpty(uri)) - uri = StringUtils.encodeURL(uri); + uri = UriUtils.encodeURI(uri); if (!TextUtils.isEmpty(caption)) - caption = StringUtils.encodeURL(caption); + caption = UriUtils.encodeURI(caption); if (!TextUtils.isEmpty(referer)) - referer = StringUtils.encodeURL(referer); + referer = UriUtils.encodeURI(referer); if (uri == null) uri = ""; diff --git a/android-studio-project/ExoPlayer-AirPlay-Receiver/src/main/java/com/github/warren_bank/exoplayer_airplay_receiver/service/playlist_extractors/HttpBasePlaylistExtractor.java b/android-studio-project/ExoPlayer-AirPlay-Receiver/src/main/java/com/github/warren_bank/exoplayer_airplay_receiver/service/playlist_extractors/HttpBasePlaylistExtractor.java index a330982..007f66a 100644 --- a/android-studio-project/ExoPlayer-AirPlay-Receiver/src/main/java/com/github/warren_bank/exoplayer_airplay_receiver/service/playlist_extractors/HttpBasePlaylistExtractor.java +++ b/android-studio-project/ExoPlayer-AirPlay-Receiver/src/main/java/com/github/warren_bank/exoplayer_airplay_receiver/service/playlist_extractors/HttpBasePlaylistExtractor.java @@ -1,6 +1,6 @@ package com.github.warren_bank.exoplayer_airplay_receiver.service.playlist_extractors; -import com.github.warren_bank.exoplayer_airplay_receiver.utils.StringUtils; +import com.github.warren_bank.exoplayer_airplay_receiver.utils.UrlUtils; import java.io.BufferedReader; import java.io.InputStreamReader; @@ -29,11 +29,11 @@ protected String resolveM3uPlaylistItem(URL context, String relative) { uri = resolveM3uPlaylistItem( ((context != null) ? context.toString() : ""), - StringUtils.decodeURL(relative) + UrlUtils.decodeURL(relative) ); if (uri != null) - uri = StringUtils.encodeURL(uri); + uri = UrlUtils.encodeURL(uri); return uri; } @@ -84,7 +84,7 @@ protected ArrayList expandPlaylist(String strUrl, Charset cs) { in = new BufferedReader(new InputStreamReader(url.openStream(), cs)); // remove ascii encoding - url = new URL(StringUtils.decodeURL(strUrl)); + url = new URL(UrlUtils.decodeURL(strUrl)); preParse(url); while ((line = in.readLine()) != null) { diff --git a/android-studio-project/ExoPlayer-AirPlay-Receiver/src/main/java/com/github/warren_bank/exoplayer_airplay_receiver/utils/StringUtils.java b/android-studio-project/ExoPlayer-AirPlay-Receiver/src/main/java/com/github/warren_bank/exoplayer_airplay_receiver/utils/StringUtils.java index 93333d1..3d752f4 100644 --- a/android-studio-project/ExoPlayer-AirPlay-Receiver/src/main/java/com/github/warren_bank/exoplayer_airplay_receiver/utils/StringUtils.java +++ b/android-studio-project/ExoPlayer-AirPlay-Receiver/src/main/java/com/github/warren_bank/exoplayer_airplay_receiver/utils/StringUtils.java @@ -5,9 +5,6 @@ import android.os.Bundle; import android.text.TextUtils; -import java.net.URI; -import java.net.URL; -import java.net.URLDecoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -141,37 +138,6 @@ public static String convertEscapedLinefeeds(String requestBody) { return requestBody.replaceAll("\\\\n", "\n"); } - public static String decodeURL(String strUrl) { - try { - return URLDecoder.decode(strUrl, "UTF-8"); - } - catch(Exception e) { - return strUrl; - } - } - - public static String encodeURL(String strUrl) { - try { - URL url = new URL(StringUtils.decodeURL(strUrl)); - - return StringUtils.encodeURL(url); - } - catch(Exception e) { - return strUrl; - } - } - - public static String encodeURL(URL url) { - try { - URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); - - return uri.toASCIIString(); - } - catch(Exception e) { - return url.toExternalForm(); - } - } - public static String serializeURLs(ArrayList list) { return StringUtils.convertArrayListToString(list, Constant.Delimiter.PLAYLIST_URLS); } diff --git a/android-studio-project/ExoPlayer-AirPlay-Receiver/src/main/java/com/github/warren_bank/exoplayer_airplay_receiver/utils/UriUtils.java b/android-studio-project/ExoPlayer-AirPlay-Receiver/src/main/java/com/github/warren_bank/exoplayer_airplay_receiver/utils/UriUtils.java index 529718b..456b30e 100644 --- a/android-studio-project/ExoPlayer-AirPlay-Receiver/src/main/java/com/github/warren_bank/exoplayer_airplay_receiver/utils/UriUtils.java +++ b/android-studio-project/ExoPlayer-AirPlay-Receiver/src/main/java/com/github/warren_bank/exoplayer_airplay_receiver/utils/UriUtils.java @@ -1,12 +1,85 @@ package com.github.warren_bank.exoplayer_airplay_receiver.utils; +import android.net.Uri; + import java.net.URI; public class UriUtils { - public static URI parseURI(String strUrl) { + public static String encodeURI(String strUri) { try { - return new URI(StringUtils.encodeURL(strUrl)); + if ((strUri == null) || strUri.isEmpty()) + throw new Exception("uri is empty"); + + StringBuilder builder = new StringBuilder(); + Uri uri = Uri.parse(strUri); + String sVal; + int iVal; + + sVal = uri.getScheme(); + if (sVal == null) + throw new Exception("protocol is required"); + builder.append(sVal); + builder.append("://"); + + sVal = uri.getEncodedUserInfo(); + if (sVal != null) { + sVal = Uri.encode(sVal, "%:"); + builder.append(sVal); + builder.append("@"); + } + + sVal = uri.getHost(); + if (sVal == null) + throw new Exception("hostname is required"); + builder.append(sVal); + + iVal = uri.getPort(); + if (iVal > 0) { + builder.append(":"); + builder.append(iVal); + } + + sVal = uri.getEncodedPath(); + if (sVal == null) + throw new Exception("path is required"); + sVal = Uri.encode(sVal, "%/"); + builder.append(sVal); + + sVal = uri.getEncodedQuery(); + if (sVal != null) { + sVal = Uri.encode(sVal, "%=&[]"); + builder.append("?"); + builder.append(sVal); + } + + sVal = uri.getEncodedFragment(); + if (sVal != null) { + sVal = Uri.encode(sVal, "%/"); + builder.append("#"); + builder.append(sVal); + } + + strUri = builder.toString(); + + if (strUri.isEmpty()) + throw new Exception("uri is empty"); + + return strUri; + } + catch(Exception e) { + return null; + } + } + + public static URI parseURI(String strUri) { + try { + strUri = UriUtils.encodeURI(strUri); + + if (strUri == null) + throw new Exception("uri is empty"); + + return new URI(strUri); } catch(Exception e) { return null; diff --git a/android-studio-project/ExoPlayer-AirPlay-Receiver/src/main/java/com/github/warren_bank/exoplayer_airplay_receiver/utils/UrlUtils.java b/android-studio-project/ExoPlayer-AirPlay-Receiver/src/main/java/com/github/warren_bank/exoplayer_airplay_receiver/utils/UrlUtils.java new file mode 100644 index 0000000..ece1595 --- /dev/null +++ b/android-studio-project/ExoPlayer-AirPlay-Receiver/src/main/java/com/github/warren_bank/exoplayer_airplay_receiver/utils/UrlUtils.java @@ -0,0 +1,40 @@ +package com.github.warren_bank.exoplayer_airplay_receiver.utils; + +import java.net.URI; +import java.net.URL; +import java.net.URLDecoder; + +public class UrlUtils { + + public static String decodeURL(String strUrl) { + try { + return URLDecoder.decode(strUrl, "UTF-8"); + } + catch(Exception e) { + return strUrl; + } + } + + public static String encodeURL(String strUrl) { + try { + URL url = new URL(strUrl); + + return UrlUtils.encodeURL(url); + } + catch(Exception e) { + return strUrl; + } + } + + public static String encodeURL(URL url) { + try { + URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); + + return uri.toASCIIString(); + } + catch(Exception e) { + return url.toExternalForm(); + } + } + +} diff --git a/tests/01.sh b/tests/01. bash - curl sender - examples in README/01.sh old mode 100755 new mode 100644 similarity index 100% rename from tests/01.sh rename to tests/01. bash - curl sender - examples in README/01.sh diff --git a/tests/02. AirPlay sender.es5.html b/tests/02. html - SPA senders/airplay_sender.es5.html similarity index 100% rename from tests/02. AirPlay sender.es5.html rename to tests/02. html - SPA senders/airplay_sender.es5.html diff --git a/tests/02. AirPlay sender.html b/tests/02. html - SPA senders/airplay_sender.html similarity index 100% rename from tests/02. AirPlay sender.html rename to tests/02. html - SPA senders/airplay_sender.html diff --git a/tests/03. AirPlay sender - to receiver on same device.html b/tests/02. html - SPA senders/airplay_sender.send_from_playlist_to_receiver_on_same_device.html similarity index 100% rename from tests/03. AirPlay sender - to receiver on same device.html rename to tests/02. html - SPA senders/airplay_sender.send_from_playlist_to_receiver_on_same_device.html diff --git a/tests/03. unit tests/.gitignore b/tests/03. unit tests/.gitignore new file mode 100644 index 0000000..f14923c --- /dev/null +++ b/tests/03. unit tests/.gitignore @@ -0,0 +1,4 @@ +!**/bin +!**/lib +!**/src +!**/out diff --git a/tests/03. unit tests/01. URL encoder/bin/0-env.bat b/tests/03. unit tests/01. URL encoder/bin/0-env.bat new file mode 100644 index 0000000..050c22d --- /dev/null +++ b/tests/03. unit tests/01. URL encoder/bin/0-env.bat @@ -0,0 +1,5 @@ +@echo off + +set JDK_HOME=C:\Android\android-studio-2021.3.1.17\jre +set JRE_HOME=%JDK_HOME%\jre +set PATH=%JRE_HOME%\bin;%JDK_HOME%\bin;%PATH% diff --git a/tests/03. unit tests/01. URL encoder/bin/1-compile.bat b/tests/03. unit tests/01. URL encoder/bin/1-compile.bat new file mode 100644 index 0000000..dca68fb --- /dev/null +++ b/tests/03. unit tests/01. URL encoder/bin/1-compile.bat @@ -0,0 +1,21 @@ +@echo off + +call "%~dp0.\0-env.bat" + +set output_dir=%~dp0..\out\%~n0 + +set options= +set options=%options% --source-path "%~dp0..\lib" +set options=%options% -d "%output_dir%" +set options=%options% -encoding "UTF-8" +set options=%options% -g:none + +set sourcefile="%~dp0..\src\Main.java" + +if exist "%output_dir%" rmdir /Q /S "%output_dir%" +mkdir "%output_dir%" + +javac %options% %sourcefile% + +echo. +pause diff --git a/tests/03. unit tests/01. URL encoder/bin/2-run.bat b/tests/03. unit tests/01. URL encoder/bin/2-run.bat new file mode 100644 index 0000000..c03d921 --- /dev/null +++ b/tests/03. unit tests/01. URL encoder/bin/2-run.bat @@ -0,0 +1,17 @@ +@echo off + +call "%~dp0.\0-env.bat" + +set output_dir=%~dp0..\out\%~n0 +set stdout_file="%output_dir%\stdout.txt" +set stderr_file="%output_dir%\stderr.txt" + +set options= +set options=%options% --class-path "%output_dir%\..\1-compile" + +set mainclass="Main" + +if exist "%output_dir%" rmdir /Q /S "%output_dir%" +mkdir "%output_dir%" + +java %options% %mainclass% 1>%stdout_file% 2>%stderr_file% diff --git a/tests/03. unit tests/01. URL encoder/lib/android/net/Uri.java b/tests/03. unit tests/01. URL encoder/lib/android/net/Uri.java new file mode 100644 index 0000000..81752b7 --- /dev/null +++ b/tests/03. unit tests/01. URL encoder/lib/android/net/Uri.java @@ -0,0 +1,2255 @@ +/* ============ + * copied from: + * https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/net/Uri.java + * ============ + * JavaDoc at: + * https://developer.android.com/reference/android/net/Uri + * ============ + */ + +/* + * Copyright (C) 2007 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.net; + +import java.io.File; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.AbstractList; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Objects; +import java.util.RandomAccess; +import java.util.Set; + +/** + * Immutable URI reference. A URI reference includes a URI and a fragment, the + * component of the URI following a '#'. Builds and parses URI references + * which conform to + * RFC 2396. + * + *

In the interest of performance, this class performs little to no + * validation. Behavior is undefined for invalid input. This class is very + * forgiving--in the face of invalid input, it will return garbage + * rather than throw an exception unless otherwise specified. + */ +public abstract class Uri implements Comparable { + + /* + + This class aims to do as little up front work as possible. To accomplish + that, we vary the implementation depending on what the user passes in. + For example, we have one implementation if the user passes in a + URI string (StringUri) and another if the user passes in the + individual components (OpaqueUri). + + *Concurrency notes*: Like any truly immutable object, this class is safe + for concurrent use. This class uses a caching pattern in some places where + it doesn't use volatile or synchronized. This is safe to do with ints + because getting or setting an int is atomic. It's safe to do with a String + because the internal fields are final and the memory model guarantees other + threads won't see a partially initialized instance. We are not guaranteed + that some threads will immediately see changes from other threads on + certain platforms, but we don't mind if those threads reconstruct the + cached result. As a result, we get thread safe caching with no concurrency + overhead, which means the most common case, access from a single thread, + is as fast as possible. + + From the Java Language spec.: + + "17.5 Final Field Semantics + + ... when the object is seen by another thread, that thread will always + see the correctly constructed version of that object's final fields. + It will also see versions of any object or array referenced by + those final fields that are at least as up-to-date as the final fields + are." + + In that same vein, all non-transient fields within Uri + implementations should be final and immutable so as to ensure true + immutability for clients even when they don't use proper concurrency + control. + + For reference, from RFC 2396: + + "4.3. Parsing a URI Reference + + A URI reference is typically parsed according to the four main + components and fragment identifier in order to determine what + components are present and whether the reference is relative or + absolute. The individual components are then parsed for their + subparts and, if not opaque, to verify their validity. + + Although the BNF defines what is allowed in each component, it is + ambiguous in terms of differentiating between an authority component + and a path component that begins with two slash characters. The + greedy algorithm is used for disambiguation: the left-most matching + rule soaks up as much of the URI reference string as it is capable of + matching. In other words, the authority component wins." + + The "four main components" of a hierarchical URI consist of + ://? + + */ + + /** + * + * Holds a placeholder for strings which haven't been cached. This enables us + * to cache null. We intentionally create a new String instance so we can + * compare its identity and there is no chance we will confuse it with + * user data. + * + * NOTE This value is held in its own Holder class is so that referring to + * {@link NotCachedHolder#NOT_CACHED} does not trigger {@code Uri.}. + * For example, {@code PathPart.} uses {@code NotCachedHolder.NOT_CACHED} + * but must not trigger {@code Uri.}: Otherwise, the initialization of + * {@code Uri.EMPTY} would see a {@code null} value for {@code PathPart.EMPTY}! + * + * @hide + */ + static class NotCachedHolder { + private NotCachedHolder() { + // prevent instantiation + } + @SuppressWarnings("RedundantStringConstructorCall") + static final String NOT_CACHED = new String("NOT CACHED"); + } + + /** + * The empty URI, equivalent to "". + */ + public static final Uri EMPTY = new HierarchicalUri(null, Part.NULL, + PathPart.EMPTY, Part.NULL, Part.NULL); + + /** + * Prevents external subclassing. + */ + private Uri() {} + + /** + * Returns true if this URI is hierarchical like "http://google.com". + * Absolute URIs are hierarchical if the scheme-specific part starts with + * a '/'. Relative URIs are always hierarchical. + */ + public abstract boolean isHierarchical(); + + /** + * Returns true if this URI is opaque like "mailto:nobody@google.com". The + * scheme-specific part of an opaque URI cannot start with a '/'. + */ + public boolean isOpaque() { + return !isHierarchical(); + } + + /** + * Returns true if this URI is relative, i.e. if it doesn't contain an + * explicit scheme. + * + * @return true if this URI is relative, false if it's absolute + */ + public abstract boolean isRelative(); + + /** + * Returns true if this URI is absolute, i.e. if it contains an + * explicit scheme. + * + * @return true if this URI is absolute, false if it's relative + */ + public boolean isAbsolute() { + return !isRelative(); + } + + /** + * Gets the scheme of this URI. Example: "http" + * + * @return the scheme or null if this is a relative URI + */ + public abstract String getScheme(); + + /** + * Gets the scheme-specific part of this URI, i.e. everything between + * the scheme separator ':' and the fragment separator '#'. If this is a + * relative URI, this method returns the entire URI. Decodes escaped octets. + * + *

Example: "//www.google.com/search?q=android" + * + * @return the decoded scheme-specific-part + */ + public abstract String getSchemeSpecificPart(); + + /** + * Gets the scheme-specific part of this URI, i.e. everything between + * the scheme separator ':' and the fragment separator '#'. If this is a + * relative URI, this method returns the entire URI. Leaves escaped octets + * intact. + * + *

Example: "//www.google.com/search?q=android" + * + * @return the encoded scheme-specific-part + */ + public abstract String getEncodedSchemeSpecificPart(); + + /** + * Gets the decoded authority part of this URI. For + * server addresses, the authority is structured as follows: + * {@code [ userinfo '@' ] host [ ':' port ]} + * + *

Examples: "google.com", "bob@google.com:80" + * + * @return the authority for this URI or null if not present + */ + public abstract String getAuthority(); + + /** + * Gets the encoded authority part of this URI. For + * server addresses, the authority is structured as follows: + * {@code [ userinfo '@' ] host [ ':' port ]} + * + *

Examples: "google.com", "bob@google.com:80" + * + * @return the authority for this URI or null if not present + */ + public abstract String getEncodedAuthority(); + + /** + * Gets the decoded user information from the authority. + * For example, if the authority is "nobody@google.com", this method will + * return "nobody". + * + * @return the user info for this URI or null if not present + */ + public abstract String getUserInfo(); + + /** + * Gets the encoded user information from the authority. + * For example, if the authority is "nobody@google.com", this method will + * return "nobody". + * + * @return the user info for this URI or null if not present + */ + public abstract String getEncodedUserInfo(); + + /** + * Gets the encoded host from the authority for this URI. For example, + * if the authority is "bob@google.com", this method will return + * "google.com". + * + * @return the host for this URI or null if not present + */ + public abstract String getHost(); + + /** + * Gets the port from the authority for this URI. For example, + * if the authority is "google.com:80", this method will return 80. + * + * @return the port for this URI or -1 if invalid or not present + */ + public abstract int getPort(); + + /** + * Gets the decoded path. + * + * @return the decoded path, or null if this is not a hierarchical URI + * (like "mailto:nobody@google.com") or the URI is invalid + */ + public abstract String getPath(); + + /** + * Gets the encoded path. + * + * @return the encoded path, or null if this is not a hierarchical URI + * (like "mailto:nobody@google.com") or the URI is invalid + */ + public abstract String getEncodedPath(); + + /** + * Gets the decoded query component from this URI. The query comes after + * the query separator ('?') and before the fragment separator ('#'). This + * method would return "q=android" for + * "http://www.google.com/search?q=android". + * + * @return the decoded query or null if there isn't one + */ + public abstract String getQuery(); + + /** + * Gets the encoded query component from this URI. The query comes after + * the query separator ('?') and before the fragment separator ('#'). This + * method would return "q=android" for + * "http://www.google.com/search?q=android". + * + * @return the encoded query or null if there isn't one + */ + public abstract String getEncodedQuery(); + + /** + * Gets the decoded fragment part of this URI, everything after the '#'. + * + * @return the decoded fragment or null if there isn't one + */ + public abstract String getFragment(); + + /** + * Gets the encoded fragment part of this URI, everything after the '#'. + * + * @return the encoded fragment or null if there isn't one + */ + public abstract String getEncodedFragment(); + + /** + * Gets the decoded path segments. + * + * @return decoded path segments, each without a leading or trailing '/' + */ + public abstract List getPathSegments(); + + /** + * Gets the decoded last segment in the path. + * + * @return the decoded last segment or null if the path is empty + */ + public abstract String getLastPathSegment(); + + /** + * Compares this Uri to another object for equality. Returns true if the + * encoded string representations of this Uri and the given Uri are + * equal. Case counts. Paths are not normalized. If one Uri specifies a + * default port explicitly and the other leaves it implicit, they will not + * be considered equal. + */ + public boolean equals(Object o) { + if (!(o instanceof Uri)) { + return false; + } + + Uri other = (Uri) o; + + return toString().equals(other.toString()); + } + + /** + * Hashes the encoded string represention of this Uri consistently with + * {@link #equals(Object)}. + */ + public int hashCode() { + return toString().hashCode(); + } + + /** + * Compares the string representation of this Uri with that of + * another. + */ + public int compareTo(Uri other) { + return toString().compareTo(other.toString()); + } + + /** + * Returns the encoded string representation of this URI. + * Example: "http://google.com/" + */ + public abstract String toString(); + + /** + * Return a string representation of this URI that has common forms of PII redacted, + * making it safer to use for logging purposes. For example, {@code tel:800-466-4411} is + * returned as {@code tel:xxx-xxx-xxxx} and {@code http://example.com/path/to/item/} is + * returned as {@code http://example.com/...}. For all other uri schemes, only the scheme, + * host and port are returned. + * @return the common forms PII redacted string of this URI + * @hide + */ + public String toSafeString() { + String scheme = getScheme(); + String ssp = getSchemeSpecificPart(); + StringBuilder builder = new StringBuilder(64); + + if (scheme != null) { + builder.append(scheme); + builder.append(":"); + if (scheme.equalsIgnoreCase("tel") || scheme.equalsIgnoreCase("sip") + || scheme.equalsIgnoreCase("sms") || scheme.equalsIgnoreCase("smsto") + || scheme.equalsIgnoreCase("mailto") || scheme.equalsIgnoreCase("nfc")) { + if (ssp != null) { + for (int i=0; i". Encodes path characters with the exception of + * '/'. + * + *

Example: "file:///tmp/android.txt" + * + * @throws NullPointerException if file is null + * @return a Uri for the given file + */ + public static Uri fromFile(File file) { + if (file == null) { + throw new NullPointerException("file"); + } + + PathPart path = PathPart.fromDecoded(file.getAbsolutePath()); + return new HierarchicalUri( + "file", Part.EMPTY, path, Part.NULL, Part.NULL); + } + + /** + * An implementation which wraps a String URI. This URI can be opaque or + * hierarchical, but we extend AbstractHierarchicalUri in case we need + * the hierarchical functionality. + */ + private static class StringUri extends AbstractHierarchicalUri { + + /** Used in parcelling. */ + static final int TYPE_ID = 1; + + /** URI string representation. */ + private final String uriString; + + private StringUri(String uriString) { + if (uriString == null) { + throw new NullPointerException("uriString"); + } + + this.uriString = uriString; + } + + public int describeContents() { + return 0; + } + + /** Cached scheme separator index. */ + private volatile int cachedSsi = NOT_CALCULATED; + + /** Finds the first ':'. Returns -1 if none found. */ + private int findSchemeSeparator() { + return cachedSsi == NOT_CALCULATED + ? cachedSsi = uriString.indexOf(':') + : cachedSsi; + } + + /** Cached fragment separator index. */ + private volatile int cachedFsi = NOT_CALCULATED; + + /** Finds the first '#'. Returns -1 if none found. */ + private int findFragmentSeparator() { + return cachedFsi == NOT_CALCULATED + ? cachedFsi = uriString.indexOf('#', findSchemeSeparator()) + : cachedFsi; + } + + public boolean isHierarchical() { + int ssi = findSchemeSeparator(); + + if (ssi == NOT_FOUND) { + // All relative URIs are hierarchical. + return true; + } + + if (uriString.length() == ssi + 1) { + // No ssp. + return false; + } + + // If the ssp starts with a '/', this is hierarchical. + return uriString.charAt(ssi + 1) == '/'; + } + + public boolean isRelative() { + // Note: We return true if the index is 0 + return findSchemeSeparator() == NOT_FOUND; + } + + private volatile String scheme = NotCachedHolder.NOT_CACHED; + + public String getScheme() { + @SuppressWarnings("StringEquality") + boolean cached = (scheme != NotCachedHolder.NOT_CACHED); + return cached ? scheme : (scheme = parseScheme()); + } + + private String parseScheme() { + int ssi = findSchemeSeparator(); + return ssi == NOT_FOUND ? null : uriString.substring(0, ssi); + } + + private Part ssp; + + private Part getSsp() { + return ssp == null ? ssp = Part.fromEncoded(parseSsp()) : ssp; + } + + public String getEncodedSchemeSpecificPart() { + return getSsp().getEncoded(); + } + + public String getSchemeSpecificPart() { + return getSsp().getDecoded(); + } + + private String parseSsp() { + int ssi = findSchemeSeparator(); + int fsi = findFragmentSeparator(); + + // Return everything between ssi and fsi. + return fsi == NOT_FOUND + ? uriString.substring(ssi + 1) + : uriString.substring(ssi + 1, fsi); + } + + private Part authority; + + private Part getAuthorityPart() { + if (authority == null) { + String encodedAuthority + = parseAuthority(this.uriString, findSchemeSeparator()); + return authority = Part.fromEncoded(encodedAuthority); + } + + return authority; + } + + public String getEncodedAuthority() { + return getAuthorityPart().getEncoded(); + } + + public String getAuthority() { + return getAuthorityPart().getDecoded(); + } + + private PathPart path; + + private PathPart getPathPart() { + return path == null + ? path = PathPart.fromEncoded(parsePath()) + : path; + } + + public String getPath() { + return getPathPart().getDecoded(); + } + + public String getEncodedPath() { + return getPathPart().getEncoded(); + } + + public List getPathSegments() { + return getPathPart().getPathSegments(); + } + + private String parsePath() { + String uriString = this.uriString; + int ssi = findSchemeSeparator(); + + // If the URI is absolute. + if (ssi > -1) { + // Is there anything after the ':'? + boolean schemeOnly = ssi + 1 == uriString.length(); + if (schemeOnly) { + // Opaque URI. + return null; + } + + // A '/' after the ':' means this is hierarchical. + if (uriString.charAt(ssi + 1) != '/') { + // Opaque URI. + return null; + } + } else { + // All relative URIs are hierarchical. + } + + return parsePath(uriString, ssi); + } + + private Part query; + + private Part getQueryPart() { + return query == null + ? query = Part.fromEncoded(parseQuery()) : query; + } + + public String getEncodedQuery() { + return getQueryPart().getEncoded(); + } + + private String parseQuery() { + // It doesn't make sense to cache this index. We only ever + // calculate it once. + int qsi = uriString.indexOf('?', findSchemeSeparator()); + if (qsi == NOT_FOUND) { + return null; + } + + int fsi = findFragmentSeparator(); + + if (fsi == NOT_FOUND) { + return uriString.substring(qsi + 1); + } + + if (fsi < qsi) { + // Invalid. + return null; + } + + return uriString.substring(qsi + 1, fsi); + } + + public String getQuery() { + return getQueryPart().getDecoded(); + } + + private Part fragment; + + private Part getFragmentPart() { + return fragment == null + ? fragment = Part.fromEncoded(parseFragment()) : fragment; + } + + public String getEncodedFragment() { + return getFragmentPart().getEncoded(); + } + + private String parseFragment() { + int fsi = findFragmentSeparator(); + return fsi == NOT_FOUND ? null : uriString.substring(fsi + 1); + } + + public String getFragment() { + return getFragmentPart().getDecoded(); + } + + public String toString() { + return uriString; + } + + /** + * Parses an authority out of the given URI string. + * + * @param uriString URI string + * @param ssi scheme separator index, -1 for a relative URI + * + * @return the authority or null if none is found + */ + static String parseAuthority(String uriString, int ssi) { + int length = uriString.length(); + + // If "//" follows the scheme separator, we have an authority. + if (length > ssi + 2 + && uriString.charAt(ssi + 1) == '/' + && uriString.charAt(ssi + 2) == '/') { + // We have an authority. + + // Look for the start of the path, query, or fragment, or the + // end of the string. + int end = ssi + 3; + LOOP: while (end < length) { + switch (uriString.charAt(end)) { + case '/': // Start of path + case '\\':// Start of path + // Per http://url.spec.whatwg.org/#host-state, the \ character + // is treated as if it were a / character when encountered in a + // host + case '?': // Start of query + case '#': // Start of fragment + break LOOP; + } + end++; + } + + return uriString.substring(ssi + 3, end); + } else { + return null; + } + + } + + /** + * Parses a path out of this given URI string. + * + * @param uriString URI string + * @param ssi scheme separator index, -1 for a relative URI + * + * @return the path + */ + static String parsePath(String uriString, int ssi) { + int length = uriString.length(); + + // Find start of path. + int pathStart; + if (length > ssi + 2 + && uriString.charAt(ssi + 1) == '/' + && uriString.charAt(ssi + 2) == '/') { + // Skip over authority to path. + pathStart = ssi + 3; + LOOP: while (pathStart < length) { + switch (uriString.charAt(pathStart)) { + case '?': // Start of query + case '#': // Start of fragment + return ""; // Empty path. + case '/': // Start of path! + case '\\':// Start of path! + // Per http://url.spec.whatwg.org/#host-state, the \ character + // is treated as if it were a / character when encountered in a + // host + break LOOP; + } + pathStart++; + } + } else { + // Path starts immediately after scheme separator. + pathStart = ssi + 1; + } + + // Find end of path. + int pathEnd = pathStart; + LOOP: while (pathEnd < length) { + switch (uriString.charAt(pathEnd)) { + case '?': // Start of query + case '#': // Start of fragment + break LOOP; + } + pathEnd++; + } + + return uriString.substring(pathStart, pathEnd); + } + + public Builder buildUpon() { + if (isHierarchical()) { + return new Builder() + .scheme(getScheme()) + .authority(getAuthorityPart()) + .path(getPathPart()) + .query(getQueryPart()) + .fragment(getFragmentPart()); + } else { + return new Builder() + .scheme(getScheme()) + .opaquePart(getSsp()) + .fragment(getFragmentPart()); + } + } + } + + /** + * Creates an opaque Uri from the given components. Encodes the ssp + * which means this method cannot be used to create hierarchical URIs. + * + * @param scheme of the URI + * @param ssp scheme-specific-part, everything between the + * scheme separator (':') and the fragment separator ('#'), which will + * get encoded + * @param fragment fragment, everything after the '#', null if undefined, + * will get encoded + * + * @throws NullPointerException if scheme or ssp is null + * @return Uri composed of the given scheme, ssp, and fragment + * + * @see Builder if you don't want the ssp and fragment to be encoded + */ + public static Uri fromParts(String scheme, String ssp, + String fragment) { + if (scheme == null) { + throw new NullPointerException("scheme"); + } + if (ssp == null) { + throw new NullPointerException("ssp"); + } + + return new OpaqueUri(scheme, Part.fromDecoded(ssp), + Part.fromDecoded(fragment)); + } + + /** + * Opaque URI. + */ + private static class OpaqueUri extends Uri { + + /** Used in parcelling. */ + static final int TYPE_ID = 2; + + private final String scheme; + private final Part ssp; + private final Part fragment; + + private OpaqueUri(String scheme, Part ssp, Part fragment) { + this.scheme = scheme; + this.ssp = ssp; + this.fragment = fragment == null ? Part.NULL : fragment; + } + + public int describeContents() { + return 0; + } + + public boolean isHierarchical() { + return false; + } + + public boolean isRelative() { + return scheme == null; + } + + public String getScheme() { + return this.scheme; + } + + public String getEncodedSchemeSpecificPart() { + return ssp.getEncoded(); + } + + public String getSchemeSpecificPart() { + return ssp.getDecoded(); + } + + public String getAuthority() { + return null; + } + + public String getEncodedAuthority() { + return null; + } + + public String getPath() { + return null; + } + + public String getEncodedPath() { + return null; + } + + public String getQuery() { + return null; + } + + public String getEncodedQuery() { + return null; + } + + public String getFragment() { + return fragment.getDecoded(); + } + + public String getEncodedFragment() { + return fragment.getEncoded(); + } + + public List getPathSegments() { + return Collections.emptyList(); + } + + public String getLastPathSegment() { + return null; + } + + public String getUserInfo() { + return null; + } + + public String getEncodedUserInfo() { + return null; + } + + public String getHost() { + return null; + } + + public int getPort() { + return -1; + } + + private volatile String cachedString = NotCachedHolder.NOT_CACHED; + + public String toString() { + @SuppressWarnings("StringEquality") + boolean cached = cachedString != NotCachedHolder.NOT_CACHED; + if (cached) { + return cachedString; + } + + StringBuilder sb = new StringBuilder(); + + sb.append(scheme).append(':'); + sb.append(getEncodedSchemeSpecificPart()); + + if (!fragment.isEmpty()) { + sb.append('#').append(fragment.getEncoded()); + } + + return cachedString = sb.toString(); + } + + public Builder buildUpon() { + return new Builder() + .scheme(this.scheme) + .opaquePart(this.ssp) + .fragment(this.fragment); + } + } + + /** + * Wrapper for path segment array. + */ + static class PathSegments extends AbstractList + implements RandomAccess { + + static final PathSegments EMPTY = new PathSegments(null, 0); + + final String[] segments; + final int size; + + PathSegments(String[] segments, int size) { + this.segments = segments; + this.size = size; + } + + public String get(int index) { + if (index >= size) { + throw new IndexOutOfBoundsException(); + } + + return segments[index]; + } + + public int size() { + return this.size; + } + } + + /** + * Builds PathSegments. + */ + static class PathSegmentsBuilder { + + String[] segments; + int size = 0; + + void add(String segment) { + if (segments == null) { + segments = new String[4]; + } else if (size + 1 == segments.length) { + String[] expanded = new String[segments.length * 2]; + System.arraycopy(segments, 0, expanded, 0, segments.length); + segments = expanded; + } + + segments[size++] = segment; + } + + PathSegments build() { + if (segments == null) { + return PathSegments.EMPTY; + } + + try { + return new PathSegments(segments, size); + } finally { + // Makes sure this doesn't get reused. + segments = null; + } + } + } + + /** + * Support for hierarchical URIs. + */ + private abstract static class AbstractHierarchicalUri extends Uri { + + public String getLastPathSegment() { + // TODO: If we haven't parsed all of the segments already, just + // grab the last one directly so we only allocate one string. + + List segments = getPathSegments(); + int size = segments.size(); + if (size == 0) { + return null; + } + return segments.get(size - 1); + } + + private Part userInfo; + + private Part getUserInfoPart() { + return userInfo == null + ? userInfo = Part.fromEncoded(parseUserInfo()) : userInfo; + } + + public final String getEncodedUserInfo() { + return getUserInfoPart().getEncoded(); + } + + private String parseUserInfo() { + String authority = getEncodedAuthority(); + if (authority == null) { + return null; + } + + int end = authority.lastIndexOf('@'); + return end == NOT_FOUND ? null : authority.substring(0, end); + } + + public String getUserInfo() { + return getUserInfoPart().getDecoded(); + } + + private volatile String host = NotCachedHolder.NOT_CACHED; + + public String getHost() { + @SuppressWarnings("StringEquality") + boolean cached = (host != NotCachedHolder.NOT_CACHED); + return cached ? host : (host = parseHost()); + } + + private String parseHost() { + final String authority = getEncodedAuthority(); + if (authority == null) { + return null; + } + + // Parse out user info and then port. + int userInfoSeparator = authority.lastIndexOf('@'); + int portSeparator = findPortSeparator(authority); + + String encodedHost = portSeparator == NOT_FOUND + ? authority.substring(userInfoSeparator + 1) + : authority.substring(userInfoSeparator + 1, portSeparator); + + return decode(encodedHost); + } + + private volatile int port = NOT_CALCULATED; + + public int getPort() { + return port == NOT_CALCULATED + ? port = parsePort() + : port; + } + + private int parsePort() { + final String authority = getEncodedAuthority(); + int portSeparator = findPortSeparator(authority); + if (portSeparator == NOT_FOUND) { + return -1; + } + + String portString = decode(authority.substring(portSeparator + 1)); + try { + return Integer.parseInt(portString); + } catch (NumberFormatException e) { + return -1; + } + } + + private int findPortSeparator(String authority) { + if (authority == null) { + return NOT_FOUND; + } + + // Reverse search for the ':' character that breaks as soon as a char that is neither + // a colon nor an ascii digit is encountered. Thanks to the goodness of UTF-16 encoding, + // it's not possible that a surrogate matches one of these, so this loop can just + // look for characters rather than care about code points. + for (int i = authority.length() - 1; i >= 0; --i) { + final int character = authority.charAt(i); + if (':' == character) return i; + // Character.isDigit would include non-ascii digits + if (character < '0' || character > '9') return NOT_FOUND; + } + return NOT_FOUND; + } + } + + /** + * Hierarchical Uri. + */ + private static class HierarchicalUri extends AbstractHierarchicalUri { + + /** Used in parcelling. */ + static final int TYPE_ID = 3; + + private final String scheme; // can be null + private final Part authority; + private final PathPart path; + private final Part query; + private final Part fragment; + + private HierarchicalUri(String scheme, Part authority, PathPart path, + Part query, Part fragment) { + this.scheme = scheme; + this.authority = Part.nonNull(authority); + this.path = path == null ? PathPart.NULL : path; + this.query = Part.nonNull(query); + this.fragment = Part.nonNull(fragment); + } + + public int describeContents() { + return 0; + } + + public boolean isHierarchical() { + return true; + } + + public boolean isRelative() { + return scheme == null; + } + + public String getScheme() { + return scheme; + } + + private Part ssp; + + private Part getSsp() { + return ssp == null + ? ssp = Part.fromEncoded(makeSchemeSpecificPart()) : ssp; + } + + public String getEncodedSchemeSpecificPart() { + return getSsp().getEncoded(); + } + + public String getSchemeSpecificPart() { + return getSsp().getDecoded(); + } + + /** + * Creates the encoded scheme-specific part from its sub parts. + */ + private String makeSchemeSpecificPart() { + StringBuilder builder = new StringBuilder(); + appendSspTo(builder); + return builder.toString(); + } + + private void appendSspTo(StringBuilder builder) { + String encodedAuthority = authority.getEncoded(); + if (encodedAuthority != null) { + // Even if the authority is "", we still want to append "//". + builder.append("//").append(encodedAuthority); + } + + String encodedPath = path.getEncoded(); + if (encodedPath != null) { + builder.append(encodedPath); + } + + if (!query.isEmpty()) { + builder.append('?').append(query.getEncoded()); + } + } + + public String getAuthority() { + return this.authority.getDecoded(); + } + + public String getEncodedAuthority() { + return this.authority.getEncoded(); + } + + public String getEncodedPath() { + return this.path.getEncoded(); + } + + public String getPath() { + return this.path.getDecoded(); + } + + public String getQuery() { + return this.query.getDecoded(); + } + + public String getEncodedQuery() { + return this.query.getEncoded(); + } + + public String getFragment() { + return this.fragment.getDecoded(); + } + + public String getEncodedFragment() { + return this.fragment.getEncoded(); + } + + public List getPathSegments() { + return this.path.getPathSegments(); + } + + private volatile String uriString = NotCachedHolder.NOT_CACHED; + + @Override + public String toString() { + @SuppressWarnings("StringEquality") + boolean cached = (uriString != NotCachedHolder.NOT_CACHED); + return cached ? uriString + : (uriString = makeUriString()); + } + + private String makeUriString() { + StringBuilder builder = new StringBuilder(); + + if (scheme != null) { + builder.append(scheme).append(':'); + } + + appendSspTo(builder); + + if (!fragment.isEmpty()) { + builder.append('#').append(fragment.getEncoded()); + } + + return builder.toString(); + } + + public Builder buildUpon() { + return new Builder() + .scheme(scheme) + .authority(authority) + .path(path) + .query(query) + .fragment(fragment); + } + } + + /** + * Helper class for building or manipulating URI references. Not safe for + * concurrent use. + * + *

An absolute hierarchical URI reference follows the pattern: + * {@code ://?#} + * + *

Relative URI references (which are always hierarchical) follow one + * of two patterns: {@code ?#} + * or {@code //?#} + * + *

An opaque URI follows this pattern: + * {@code :#} + * + *

Use {@link Uri#buildUpon()} to obtain a builder representing an existing URI. + */ + public static final class Builder { + + private String scheme; + private Part opaquePart; + private Part authority; + private PathPart path; + private Part query; + private Part fragment; + + /** + * Constructs a new Builder. + */ + public Builder() {} + + /** + * Sets the scheme. + * + * @param scheme name or {@code null} if this is a relative Uri + */ + public Builder scheme(String scheme) { + this.scheme = scheme; + return this; + } + + Builder opaquePart(Part opaquePart) { + this.opaquePart = opaquePart; + return this; + } + + /** + * Encodes and sets the given opaque scheme-specific-part. + * + * @param opaquePart decoded opaque part + */ + public Builder opaquePart(String opaquePart) { + return opaquePart(Part.fromDecoded(opaquePart)); + } + + /** + * Sets the previously encoded opaque scheme-specific-part. + * + * @param opaquePart encoded opaque part + */ + public Builder encodedOpaquePart(String opaquePart) { + return opaquePart(Part.fromEncoded(opaquePart)); + } + + Builder authority(Part authority) { + // This URI will be hierarchical. + this.opaquePart = null; + + this.authority = authority; + return this; + } + + /** + * Encodes and sets the authority. + */ + public Builder authority(String authority) { + return authority(Part.fromDecoded(authority)); + } + + /** + * Sets the previously encoded authority. + */ + public Builder encodedAuthority(String authority) { + return authority(Part.fromEncoded(authority)); + } + + Builder path(PathPart path) { + // This URI will be hierarchical. + this.opaquePart = null; + + this.path = path; + return this; + } + + /** + * Sets the path. Leaves '/' characters intact but encodes others as + * necessary. + * + *

If the path is not null and doesn't start with a '/', and if + * you specify a scheme and/or authority, the builder will prepend the + * given path with a '/'. + */ + public Builder path(String path) { + return path(PathPart.fromDecoded(path)); + } + + /** + * Sets the previously encoded path. + * + *

If the path is not null and doesn't start with a '/', and if + * you specify a scheme and/or authority, the builder will prepend the + * given path with a '/'. + */ + public Builder encodedPath(String path) { + return path(PathPart.fromEncoded(path)); + } + + /** + * Encodes the given segment and appends it to the path. + */ + public Builder appendPath(String newSegment) { + return path(PathPart.appendDecodedSegment(path, newSegment)); + } + + /** + * Appends the given segment to the path. + */ + public Builder appendEncodedPath(String newSegment) { + return path(PathPart.appendEncodedSegment(path, newSegment)); + } + + Builder query(Part query) { + // This URI will be hierarchical. + this.opaquePart = null; + + this.query = query; + return this; + } + + /** + * Encodes and sets the query. + */ + public Builder query(String query) { + return query(Part.fromDecoded(query)); + } + + /** + * Sets the previously encoded query. + */ + public Builder encodedQuery(String query) { + return query(Part.fromEncoded(query)); + } + + Builder fragment(Part fragment) { + this.fragment = fragment; + return this; + } + + /** + * Encodes and sets the fragment. + */ + public Builder fragment(String fragment) { + return fragment(Part.fromDecoded(fragment)); + } + + /** + * Sets the previously encoded fragment. + */ + public Builder encodedFragment(String fragment) { + return fragment(Part.fromEncoded(fragment)); + } + + /** + * Encodes the key and value and then appends the parameter to the + * query string. + * + * @param key which will be encoded + * @param value which will be encoded + */ + public Builder appendQueryParameter(String key, String value) { + // This URI will be hierarchical. + this.opaquePart = null; + + String encodedParameter = encode(key, null) + "=" + + encode(value, null); + + if (query == null) { + query = Part.fromEncoded(encodedParameter); + return this; + } + + String oldQuery = query.getEncoded(); + if (oldQuery == null || oldQuery.length() == 0) { + query = Part.fromEncoded(encodedParameter); + } else { + query = Part.fromEncoded(oldQuery + "&" + encodedParameter); + } + + return this; + } + + /** + * Clears the the previously set query. + */ + public Builder clearQuery() { + return query((Part) null); + } + + /** + * Constructs a Uri with the current attributes. + * + * @throws UnsupportedOperationException if the URI is opaque and the + * scheme is null + */ + public Uri build() { + if (opaquePart != null) { + if (this.scheme == null) { + throw new UnsupportedOperationException( + "An opaque URI must have a scheme."); + } + + return new OpaqueUri(scheme, opaquePart, fragment); + } else { + // Hierarchical URIs should not return null for getPath(). + PathPart path = this.path; + if (path == null || path == PathPart.NULL) { + path = PathPart.EMPTY; + } else { + // If we have a scheme and/or authority, the path must + // be absolute. Prepend it with a '/' if necessary. + if (hasSchemeOrAuthority()) { + path = PathPart.makeAbsolute(path); + } + } + + return new HierarchicalUri( + scheme, authority, path, query, fragment); + } + } + + private boolean hasSchemeOrAuthority() { + return scheme != null + || (authority != null && authority != Part.NULL); + + } + + @Override + public String toString() { + return build().toString(); + } + } + + /** + * Returns a set of the unique names of all query parameters. Iterating + * over the set will return the names in order of their first occurrence. + * + * @throws UnsupportedOperationException if this isn't a hierarchical URI + * + * @return a set of decoded names + */ + public Set getQueryParameterNames() { + if (isOpaque()) { + throw new UnsupportedOperationException(NOT_HIERARCHICAL); + } + + String query = getEncodedQuery(); + if (query == null) { + return Collections.emptySet(); + } + + Set names = new LinkedHashSet(); + int start = 0; + do { + int next = query.indexOf('&', start); + int end = (next == -1) ? query.length() : next; + + int separator = query.indexOf('=', start); + if (separator > end || separator == -1) { + separator = end; + } + + String name = query.substring(start, separator); + names.add(decode(name)); + + // Move start to end of name. + start = end + 1; + } while (start < query.length()); + + return Collections.unmodifiableSet(names); + } + + /** + * Searches the query string for parameter values with the given key. + * + * @param key which will be encoded + * + * @throws UnsupportedOperationException if this isn't a hierarchical URI + * @throws NullPointerException if key is null + * @return a list of decoded values + */ + public List getQueryParameters(String key) { + if (isOpaque()) { + throw new UnsupportedOperationException(NOT_HIERARCHICAL); + } + if (key == null) { + throw new NullPointerException("key"); + } + + String query = getEncodedQuery(); + if (query == null) { + return Collections.emptyList(); + } + + String encodedKey; + try { + encodedKey = URLEncoder.encode(key, DEFAULT_ENCODING); + } catch (UnsupportedEncodingException e) { + throw new AssertionError(e); + } + + ArrayList values = new ArrayList(); + + int start = 0; + do { + int nextAmpersand = query.indexOf('&', start); + int end = nextAmpersand != -1 ? nextAmpersand : query.length(); + + int separator = query.indexOf('=', start); + if (separator > end || separator == -1) { + separator = end; + } + + if (separator - start == encodedKey.length() + && query.regionMatches(start, encodedKey, 0, encodedKey.length())) { + if (separator == end) { + values.add(""); + } else { + values.add(decode(query.substring(separator + 1, end))); + } + } + + // Move start to end of name. + if (nextAmpersand != -1) { + start = nextAmpersand + 1; + } else { + break; + } + } while (true); + + return Collections.unmodifiableList(values); + } + + /** + * Searches the query string for the first value with the given key. + * + *

Warning: Prior to Jelly Bean, this decoded + * the '+' character as '+' rather than ' '. + * + * @param key which will be encoded + * @throws UnsupportedOperationException if this isn't a hierarchical URI + * @throws NullPointerException if key is null + * @return the decoded value or null if no parameter is found + */ + public String getQueryParameter(String key) { + if (isOpaque()) { + throw new UnsupportedOperationException(NOT_HIERARCHICAL); + } + if (key == null) { + throw new NullPointerException("key"); + } + + final String query = getEncodedQuery(); + if (query == null) { + return null; + } + + final String encodedKey = encode(key, null); + final int length = query.length(); + int start = 0; + do { + int nextAmpersand = query.indexOf('&', start); + int end = nextAmpersand != -1 ? nextAmpersand : length; + + int separator = query.indexOf('=', start); + if (separator > end || separator == -1) { + separator = end; + } + + if (separator - start == encodedKey.length() + && query.regionMatches(start, encodedKey, 0, encodedKey.length())) { + if (separator == end) { + return ""; + } else { + String encodedValue = query.substring(separator + 1, end); + return UriCodec.decode(encodedValue, true, StandardCharsets.UTF_8, false); + } + } + + // Move start to end of name. + if (nextAmpersand != -1) { + start = nextAmpersand + 1; + } else { + break; + } + } while (true); + return null; + } + + /** + * Searches the query string for the first value with the given key and interprets it + * as a boolean value. "false" and "0" are interpreted as false, everything + * else is interpreted as true. + * + * @param key which will be decoded + * @param defaultValue the default value to return if there is no query parameter for key + * @return the boolean interpretation of the query parameter key + */ + public boolean getBooleanQueryParameter(String key, boolean defaultValue) { + String flag = getQueryParameter(key); + if (flag == null) { + return defaultValue; + } + flag = flag.toLowerCase(Locale.ROOT); + return (!"false".equals(flag) && !"0".equals(flag)); + } + + /** + * Return an equivalent URI with a lowercase scheme component. + * This aligns the Uri with Android best practices for + * intent filtering. + * + *

For example, "HTTP://www.android.com" becomes + * "http://www.android.com" + * + *

All URIs received from outside Android (such as user input, + * or external sources like Bluetooth, NFC, or the Internet) should + * be normalized before they are used to create an Intent. + * + *

This method does not validate bad URI's, + * or 'fix' poorly formatted URI's - so do not use it for input validation. + * A Uri will always be returned, even if the Uri is badly formatted to + * begin with and a scheme component cannot be found. + * + * @return normalized Uri (never null) + * @see android.content.Intent#setData + * @see android.content.Intent#setDataAndNormalize + */ + public Uri normalizeScheme() { + String scheme = getScheme(); + if (scheme == null) return this; // give up + String lowerScheme = scheme.toLowerCase(Locale.ROOT); + if (scheme.equals(lowerScheme)) return this; // no change + + return buildUpon().scheme(lowerScheme).build(); + } + + /** Identifies a null parcelled Uri. */ + private static final int NULL_TYPE_ID = 0; + + private static final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray(); + + /** + * Encodes characters in the given string as '%'-escaped octets + * using the UTF-8 scheme. Leaves letters ("A-Z", "a-z"), numbers + * ("0-9"), and unreserved characters ("_-!.~'()*") intact. Encodes + * all other characters. + * + * @param s string to encode + * @return an encoded version of s suitable for use as a URI component, + * or null if s is null + */ + public static String encode(String s) { + return encode(s, null); + } + + /** + * Encodes characters in the given string as '%'-escaped octets + * using the UTF-8 scheme. Leaves letters ("A-Z", "a-z"), numbers + * ("0-9"), and unreserved characters ("_-!.~'()*") intact. Encodes + * all other characters with the exception of those specified in the + * allow argument. + * + * @param s string to encode + * @param allow set of additional characters to allow in the encoded form, + * null if no characters should be skipped + * @return an encoded version of s suitable for use as a URI component, + * or null if s is null + */ + public static String encode(String s, String allow) { + if (s == null) { + return null; + } + + // Lazily-initialized buffers. + StringBuilder encoded = null; + + int oldLength = s.length(); + + // This loop alternates between copying over allowed characters and + // encoding in chunks. This results in fewer method calls and + // allocations than encoding one character at a time. + int current = 0; + while (current < oldLength) { + // Start in "copying" mode where we copy over allowed chars. + + // Find the next character which needs to be encoded. + int nextToEncode = current; + while (nextToEncode < oldLength + && isAllowed(s.charAt(nextToEncode), allow)) { + nextToEncode++; + } + + // If there's nothing more to encode... + if (nextToEncode == oldLength) { + if (current == 0) { + // We didn't need to encode anything! + return s; + } else { + // Presumably, we've already done some encoding. + encoded.append(s, current, oldLength); + return encoded.toString(); + } + } + + if (encoded == null) { + encoded = new StringBuilder(); + } + + if (nextToEncode > current) { + // Append allowed characters leading up to this point. + encoded.append(s, current, nextToEncode); + } else { + // assert nextToEncode == current + } + + // Switch to "encoding" mode. + + // Find the next allowed character. + current = nextToEncode; + int nextAllowed = current + 1; + while (nextAllowed < oldLength + && !isAllowed(s.charAt(nextAllowed), allow)) { + nextAllowed++; + } + + // Convert the substring to bytes and encode the bytes as + // '%'-escaped octets. + String toEncode = s.substring(current, nextAllowed); + try { + byte[] bytes = toEncode.getBytes(DEFAULT_ENCODING); + int bytesLength = bytes.length; + for (int i = 0; i < bytesLength; i++) { + encoded.append('%'); + encoded.append(HEX_DIGITS[(bytes[i] & 0xf0) >> 4]); + encoded.append(HEX_DIGITS[bytes[i] & 0xf]); + } + } catch (UnsupportedEncodingException e) { + throw new AssertionError(e); + } + + current = nextAllowed; + } + + // Encoded could still be null at this point if s is empty. + return encoded == null ? s : encoded.toString(); + } + + /** + * Returns true if the given character is allowed. + * + * @param c character to check + * @param allow characters to allow + * @return true if the character is allowed or false if it should be + * encoded + */ + private static boolean isAllowed(char c, String allow) { + return (c >= 'A' && c <= 'Z') + || (c >= 'a' && c <= 'z') + || (c >= '0' && c <= '9') + || "_-!.~'()*".indexOf(c) != NOT_FOUND + || (allow != null && allow.indexOf(c) != NOT_FOUND); + } + + /** + * Decodes '%'-escaped octets in the given string using the UTF-8 scheme. + * Replaces invalid octets with the unicode replacement character + * ("\\uFFFD"). + * + * @param s encoded string to decode + * @return the given string with escaped octets decoded, or null if + * s is null + */ + public static String decode(String s) { + if (s == null) { + return null; + } + return UriCodec.decode( + s, false /* convertPlus */, StandardCharsets.UTF_8, false /* throwOnFailure */); + } + + /** + * Support for part implementations. + */ + static abstract class AbstractPart { + + // Possible values of mCanonicalRepresentation. + static final int REPRESENTATION_ENCODED = 1; + static final int REPRESENTATION_DECODED = 2; + + volatile String encoded; + volatile String decoded; + private final int mCanonicalRepresentation; + + AbstractPart(String encoded, String decoded) { + if (encoded != NotCachedHolder.NOT_CACHED) { + this.mCanonicalRepresentation = REPRESENTATION_ENCODED; + this.encoded = encoded; + this.decoded = NotCachedHolder.NOT_CACHED; + } else if (decoded != NotCachedHolder.NOT_CACHED) { + this.mCanonicalRepresentation = REPRESENTATION_DECODED; + this.encoded = NotCachedHolder.NOT_CACHED; + this.decoded = decoded; + } else { + throw new IllegalArgumentException("Neither encoded nor decoded"); + } + } + + abstract String getEncoded(); + + final String getDecoded() { + @SuppressWarnings("StringEquality") + boolean hasDecoded = decoded != NotCachedHolder.NOT_CACHED; + return hasDecoded ? decoded : (decoded = decode(encoded)); + } + } + + /** + * Immutable wrapper of encoded and decoded versions of a URI part. Lazily + * creates the encoded or decoded version from the other. + */ + static class Part extends AbstractPart { + + /** A part with null values. */ + static final Part NULL = new EmptyPart(null); + + /** A part with empty strings for values. */ + static final Part EMPTY = new EmptyPart(""); + + private Part(String encoded, String decoded) { + super(encoded, decoded); + } + + boolean isEmpty() { + return false; + } + + String getEncoded() { + @SuppressWarnings("StringEquality") + boolean hasEncoded = encoded != NotCachedHolder.NOT_CACHED; + return hasEncoded ? encoded : (encoded = encode(decoded)); + } + + /** + * Returns given part or {@link #NULL} if the given part is null. + */ + static Part nonNull(Part part) { + return part == null ? NULL : part; + } + + /** + * Creates a part from the encoded string. + * + * @param encoded part string + */ + static Part fromEncoded(String encoded) { + return from(encoded, NotCachedHolder.NOT_CACHED); + } + + /** + * Creates a part from the decoded string. + * + * @param decoded part string + */ + static Part fromDecoded(String decoded) { + return from(NotCachedHolder.NOT_CACHED, decoded); + } + + /** + * Creates a part from the encoded and decoded strings. + * + * @param encoded part string + * @param decoded part string + */ + static Part from(String encoded, String decoded) { + // We have to check both encoded and decoded in case one is + // NotCachedHolder.NOT_CACHED. + + if (encoded == null) { + return NULL; + } + if (encoded.length() == 0) { + return EMPTY; + } + + if (decoded == null) { + return NULL; + } + if (decoded .length() == 0) { + return EMPTY; + } + + return new Part(encoded, decoded); + } + + private static class EmptyPart extends Part { + public EmptyPart(String value) { + super(value, value); + if (value != null && !value.isEmpty()) { + throw new IllegalArgumentException("Expected empty value, got: " + value); + } + // Avoid having to re-calculate the non-canonical value. + encoded = decoded = value; + } + + @Override + boolean isEmpty() { + return true; + } + } + } + + /** + * Immutable wrapper of encoded and decoded versions of a path part. Lazily + * creates the encoded or decoded version from the other. + */ + static class PathPart extends AbstractPart { + + /** A part with null values. */ + static final PathPart NULL = new PathPart(null, null); + + /** A part with empty strings for values. */ + static final PathPart EMPTY = new PathPart("", ""); + + private PathPart(String encoded, String decoded) { + super(encoded, decoded); + } + + String getEncoded() { + @SuppressWarnings("StringEquality") + boolean hasEncoded = encoded != NotCachedHolder.NOT_CACHED; + + // Don't encode '/'. + return hasEncoded ? encoded : (encoded = encode(decoded, "/")); + } + + /** + * Cached path segments. This doesn't need to be volatile--we don't + * care if other threads see the result. + */ + private PathSegments pathSegments; + + /** + * Gets the individual path segments. Parses them if necessary. + * + * @return parsed path segments or null if this isn't a hierarchical + * URI + */ + PathSegments getPathSegments() { + if (pathSegments != null) { + return pathSegments; + } + + String path = getEncoded(); + if (path == null) { + return pathSegments = PathSegments.EMPTY; + } + + PathSegmentsBuilder segmentBuilder = new PathSegmentsBuilder(); + + int previous = 0; + int current; + while ((current = path.indexOf('/', previous)) > -1) { + // This check keeps us from adding a segment if the path starts + // '/' and an empty segment for "//". + if (previous < current) { + String decodedSegment + = decode(path.substring(previous, current)); + segmentBuilder.add(decodedSegment); + } + previous = current + 1; + } + + // Add in the final path segment. + if (previous < path.length()) { + segmentBuilder.add(decode(path.substring(previous))); + } + + return pathSegments = segmentBuilder.build(); + } + + static PathPart appendEncodedSegment(PathPart oldPart, + String newSegment) { + // If there is no old path, should we make the new path relative + // or absolute? I pick absolute. + + if (oldPart == null) { + // No old path. + return fromEncoded("/" + newSegment); + } + + String oldPath = oldPart.getEncoded(); + + if (oldPath == null) { + oldPath = ""; + } + + int oldPathLength = oldPath.length(); + String newPath; + if (oldPathLength == 0) { + // No old path. + newPath = "/" + newSegment; + } else if (oldPath.charAt(oldPathLength - 1) == '/') { + newPath = oldPath + newSegment; + } else { + newPath = oldPath + "/" + newSegment; + } + + return fromEncoded(newPath); + } + + static PathPart appendDecodedSegment(PathPart oldPart, String decoded) { + String encoded = encode(decoded); + + // TODO: Should we reuse old PathSegments? Probably not. + return appendEncodedSegment(oldPart, encoded); + } + + /** + * Creates a path from the encoded string. + * + * @param encoded part string + */ + static PathPart fromEncoded(String encoded) { + return from(encoded, NotCachedHolder.NOT_CACHED); + } + + /** + * Creates a path from the decoded string. + * + * @param decoded part string + */ + static PathPart fromDecoded(String decoded) { + return from(NotCachedHolder.NOT_CACHED, decoded); + } + + /** + * Creates a path from the encoded and decoded strings. + * + * @param encoded part string + * @param decoded part string + */ + static PathPart from(String encoded, String decoded) { + if (encoded == null) { + return NULL; + } + + if (encoded.length() == 0) { + return EMPTY; + } + + return new PathPart(encoded, decoded); + } + + /** + * Prepends path values with "/" if they're present, not empty, and + * they don't already start with "/". + */ + static PathPart makeAbsolute(PathPart oldPart) { + @SuppressWarnings("StringEquality") + boolean encodedCached = oldPart.encoded != NotCachedHolder.NOT_CACHED; + + // We don't care which version we use, and we don't want to force + // unneccessary encoding/decoding. + String oldPath = encodedCached ? oldPart.encoded : oldPart.decoded; + + if (oldPath == null || oldPath.length() == 0 + || oldPath.startsWith("/")) { + return oldPart; + } + + // Prepend encoded string if present. + String newEncoded = encodedCached + ? "/" + oldPart.encoded : NotCachedHolder.NOT_CACHED; + + // Prepend decoded string if present. + @SuppressWarnings("StringEquality") + boolean decodedCached = oldPart.decoded != NotCachedHolder.NOT_CACHED; + String newDecoded = decodedCached + ? "/" + oldPart.decoded + : NotCachedHolder.NOT_CACHED; + + return new PathPart(newEncoded, newDecoded); + } + } + + /** + * Creates a new Uri by appending an already-encoded path segment to a + * base Uri. + * + * @param baseUri Uri to append path segment to + * @param pathSegment encoded path segment to append + * @return a new Uri based on baseUri with the given segment appended to + * the path + * @throws NullPointerException if baseUri is null + */ + public static Uri withAppendedPath(Uri baseUri, String pathSegment) { + Builder builder = baseUri.buildUpon(); + builder = builder.appendEncodedPath(pathSegment); + return builder.build(); + } + + /** + * If this {@link Uri} is {@code file://}, then resolve and return its + * canonical path. Also fixes legacy emulated storage paths so they are + * usable across user boundaries. Should always be called from the app + * process before sending elsewhere. + * + * @hide + */ + public Uri getCanonicalUri() { + if ("file".equals(getScheme())) { + final String canonicalPath; + try { + canonicalPath = new File(getPath()).getCanonicalPath(); + } catch (IOException e) { + return this; + } + + return Uri.fromFile(new File(canonicalPath)); + } else { + return this; + } + } + + /** + * Test if this is a path prefix match against the given Uri. Verifies that + * scheme, authority, and atomic path segments match. + * + * @hide + */ + public boolean isPathPrefixMatch(Uri prefix) { + if (!Objects.equals(getScheme(), prefix.getScheme())) return false; + if (!Objects.equals(getAuthority(), prefix.getAuthority())) return false; + + List seg = getPathSegments(); + List prefixSeg = prefix.getPathSegments(); + + final int prefixSize = prefixSeg.size(); + if (seg.size() < prefixSize) return false; + + for (int i = 0; i < prefixSize; i++) { + if (!Objects.equals(seg.get(i), prefixSeg.get(i))) { + return false; + } + } + + return true; + } +} diff --git a/tests/03. unit tests/01. URL encoder/lib/android/net/UriCodec.java b/tests/03. unit tests/01. URL encoder/lib/android/net/UriCodec.java new file mode 100644 index 0000000..8a792a8 --- /dev/null +++ b/tests/03. unit tests/01. URL encoder/lib/android/net/UriCodec.java @@ -0,0 +1,182 @@ +/* ============ + * copied from: + * https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/net/UriCodec.java + * ============ + */ + +/* + * Copyright (C) 2015 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.net; + +import java.net.URISyntaxException; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.Charset; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CodingErrorAction; + +/** + * Decodes “application/x-www-form-urlencoded” content. + * + * @hide + */ +public final class UriCodec { + + private UriCodec() {} + + /** + * Interprets a char as hex digits, returning a number from -1 (invalid char) to 15 ('f'). + */ + private static int hexCharToValue(char c) { + if ('0' <= c && c <= '9') { + return c - '0'; + } + if ('a' <= c && c <= 'f') { + return 10 + c - 'a'; + } + if ('A' <= c && c <= 'F') { + return 10 + c - 'A'; + } + return -1; + } + + private static URISyntaxException unexpectedCharacterException( + String uri, String name, char unexpected, int index) { + String nameString = (name == null) ? "" : " in [" + name + "]"; + return new URISyntaxException( + uri, "Unexpected character" + nameString + ": " + unexpected, index); + } + + private static char getNextCharacter(String uri, int index, int end, String name) + throws URISyntaxException { + if (index >= end) { + String nameString = (name == null) ? "" : " in [" + name + "]"; + throw new URISyntaxException( + uri, "Unexpected end of string" + nameString, index); + } + return uri.charAt(index); + } + + /** + * Decode a string according to the rules of this decoder. + * + * - if {@code convertPlus == true} all ‘+’ chars in the decoded output are converted to ‘ ‘ + * (white space) + * - if {@code throwOnFailure == true}, an {@link IllegalArgumentException} is thrown for + * invalid inputs. Else, U+FFFd is emitted to the output in place of invalid input octets. + */ + public static String decode( + String s, boolean convertPlus, Charset charset, boolean throwOnFailure) { + StringBuilder builder = new StringBuilder(s.length()); + appendDecoded(builder, s, convertPlus, charset, throwOnFailure); + return builder.toString(); + } + + /** + * Character to be output when there's an error decoding an input. + */ + private static final char INVALID_INPUT_CHARACTER = '\ufffd'; + + private static void appendDecoded( + StringBuilder builder, + String s, + boolean convertPlus, + Charset charset, + boolean throwOnFailure) { + CharsetDecoder decoder = charset.newDecoder() + .onMalformedInput(CodingErrorAction.REPLACE) + .replaceWith("\ufffd") + .onUnmappableCharacter(CodingErrorAction.REPORT); + // Holds the bytes corresponding to the escaped chars being read (empty if the last char + // wasn't a escaped char). + ByteBuffer byteBuffer = ByteBuffer.allocate(s.length()); + int i = 0; + while (i < s.length()) { + char c = s.charAt(i); + i++; + switch (c) { + case '+': + flushDecodingByteAccumulator( + builder, decoder, byteBuffer, throwOnFailure); + builder.append(convertPlus ? ' ' : '+'); + break; + case '%': + // Expect two characters representing a number in hex. + byte hexValue = 0; + for (int j = 0; j < 2; j++) { + try { + c = getNextCharacter(s, i, s.length(), null /* name */); + } catch (URISyntaxException e) { + // Unexpected end of input. + if (throwOnFailure) { + throw new IllegalArgumentException(e); + } else { + flushDecodingByteAccumulator( + builder, decoder, byteBuffer, throwOnFailure); + builder.append(INVALID_INPUT_CHARACTER); + return; + } + } + i++; + int newDigit = hexCharToValue(c); + if (newDigit < 0) { + if (throwOnFailure) { + throw new IllegalArgumentException( + unexpectedCharacterException(s, null /* name */, c, i - 1)); + } else { + flushDecodingByteAccumulator( + builder, decoder, byteBuffer, throwOnFailure); + builder.append(INVALID_INPUT_CHARACTER); + break; + } + } + hexValue = (byte) (hexValue * 0x10 + newDigit); + } + byteBuffer.put(hexValue); + break; + default: + flushDecodingByteAccumulator(builder, decoder, byteBuffer, throwOnFailure); + builder.append(c); + } + } + flushDecodingByteAccumulator(builder, decoder, byteBuffer, throwOnFailure); + } + + private static void flushDecodingByteAccumulator( + StringBuilder builder, + CharsetDecoder decoder, + ByteBuffer byteBuffer, + boolean throwOnFailure) { + if (byteBuffer.position() == 0) { + return; + } + byteBuffer.flip(); + try { + builder.append(decoder.decode(byteBuffer)); + } catch (CharacterCodingException e) { + if (throwOnFailure) { + throw new IllegalArgumentException(e); + } else { + builder.append(INVALID_INPUT_CHARACTER); + } + } finally { + // Use the byte buffer to write again. + byteBuffer.flip(); + byteBuffer.limit(byteBuffer.capacity()); + } + } +} diff --git a/tests/03. unit tests/01. URL encoder/out/1-compile/Main.class b/tests/03. unit tests/01. URL encoder/out/1-compile/Main.class new file mode 100644 index 0000000..9ed7003 Binary files /dev/null and b/tests/03. unit tests/01. URL encoder/out/1-compile/Main.class differ diff --git a/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$AbstractHierarchicalUri.class b/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$AbstractHierarchicalUri.class new file mode 100644 index 0000000..459fd89 Binary files /dev/null and b/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$AbstractHierarchicalUri.class differ diff --git a/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$AbstractPart.class b/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$AbstractPart.class new file mode 100644 index 0000000..27aabde Binary files /dev/null and b/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$AbstractPart.class differ diff --git a/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$Builder.class b/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$Builder.class new file mode 100644 index 0000000..dfffc91 Binary files /dev/null and b/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$Builder.class differ diff --git a/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$HierarchicalUri.class b/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$HierarchicalUri.class new file mode 100644 index 0000000..eb43d9c Binary files /dev/null and b/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$HierarchicalUri.class differ diff --git a/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$NotCachedHolder.class b/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$NotCachedHolder.class new file mode 100644 index 0000000..243c7af Binary files /dev/null and b/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$NotCachedHolder.class differ diff --git a/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$OpaqueUri.class b/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$OpaqueUri.class new file mode 100644 index 0000000..993907c Binary files /dev/null and b/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$OpaqueUri.class differ diff --git a/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$Part$EmptyPart.class b/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$Part$EmptyPart.class new file mode 100644 index 0000000..c0ebf0f Binary files /dev/null and b/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$Part$EmptyPart.class differ diff --git a/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$Part.class b/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$Part.class new file mode 100644 index 0000000..137e039 Binary files /dev/null and b/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$Part.class differ diff --git a/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$PathPart.class b/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$PathPart.class new file mode 100644 index 0000000..7d54eea Binary files /dev/null and b/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$PathPart.class differ diff --git a/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$PathSegments.class b/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$PathSegments.class new file mode 100644 index 0000000..593162e Binary files /dev/null and b/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$PathSegments.class differ diff --git a/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$PathSegmentsBuilder.class b/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$PathSegmentsBuilder.class new file mode 100644 index 0000000..303df1b Binary files /dev/null and b/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$PathSegmentsBuilder.class differ diff --git a/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$StringUri.class b/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$StringUri.class new file mode 100644 index 0000000..84053e6 Binary files /dev/null and b/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri$StringUri.class differ diff --git a/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri.class b/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri.class new file mode 100644 index 0000000..c238eab Binary files /dev/null and b/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/Uri.class differ diff --git a/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/UriCodec.class b/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/UriCodec.class new file mode 100644 index 0000000..f37dc70 Binary files /dev/null and b/tests/03. unit tests/01. URL encoder/out/1-compile/android/net/UriCodec.class differ diff --git a/tests/03. unit tests/01. URL encoder/out/2-run/stderr.txt b/tests/03. unit tests/01. URL encoder/out/2-run/stderr.txt new file mode 100644 index 0000000..e69de29 diff --git a/tests/03. unit tests/01. URL encoder/out/2-run/stdout.txt b/tests/03. unit tests/01. URL encoder/out/2-run/stdout.txt new file mode 100644 index 0000000..c74ff07 --- /dev/null +++ b/tests/03. unit tests/01. URL encoder/out/2-run/stdout.txt @@ -0,0 +1,78 @@ + +---------------------------------------- + +[subject] url: http://a%3Ab:pass@example.com:80/foo[bar].baz?hash=%26%2f#skip +[test_001] encoded: http%3A%2F%2Fa%253Ab%3Apass%40example.com%3A80%2Ffoo%5Bbar%5D.baz%3Fhash%3D%2526%252f%23skip +[test_002] encoded: http://a%3Ab:pass@example.com:80/foo[bar].baz?hash=%26%2f#skip +[test_003a] decoded: + http + a:b:pass + example.com + 80 + /foo[bar].baz + hash=&/ + skip +[test_003a] encoded: + http + a%3Ab:pass + example.com + 80 + /foo[bar].baz + hash=%26%2f + skip +[test_003b] decoded: + http + a%3Ab:pass + example.com + 80 + /foo[bar].baz + hash=%26%2f + skip +[test_004a] encoded: http://a%253Ab:pass@example.com:80/foo%5Bbar%5D.baz?hash=%2526%252f#skip +[test_004b] encoded: http://a:b:pass@example.com:80/foo%5Bbar%5D.baz?hash=&/#skip +[test_004c] encoded: http://a:b:pass@example.com:80/foo%5Bbar%5D.baz?hash=&/#skip +[test_004d] encoded: http://a%253Ab:pass@example.com:80/foo%5Bbar%5D.baz?hash=%2526%252f#skip +[test_005a] encoded: http://a%3Ab:pass@example.com:80/foo[bar].baz?hash=%26%2f#skip +[test_005b] encoded: http://a%3Ab%3Apass@example.com:80%2Ffoo%5Bbar%5D.baz?hash=%26%2f#skip +[test_005c] encoded: http://a:b:pass@example.com:80/foo%5Bbar%5D.baz?hash=%26%2f#skip +[test_005d] encoded: http://a%3Ab:pass@example.com:80/foo%5Bbar%5D.baz?hash=%26%2f#skip +[test_005e] encoded: http://a%3Ab:pass@example.com:80/foo%5Bbar%5D.baz?hash=%26%2f#skip + +---------------------------------------- + +[subject] url: http://a%3Ab:pass@example.com:80/foo%5Bbar%5D.baz?hash=%26%2f#skip +[test_001] encoded: http%3A%2F%2Fa%253Ab%3Apass%40example.com%3A80%2Ffoo%255Bbar%255D.baz%3Fhash%3D%2526%252f%23skip +[test_002] encoded: http://a%3Ab:pass@example.com:80/foo%5Bbar%5D.baz?hash=%26%2f#skip +[test_003a] decoded: + http + a:b:pass + example.com + 80 + /foo[bar].baz + hash=&/ + skip +[test_003a] encoded: + http + a%3Ab:pass + example.com + 80 + /foo%5Bbar%5D.baz + hash=%26%2f + skip +[test_003b] decoded: + http + a%3Ab:pass + example.com + 80 + /foo%5Bbar%5D.baz + hash=%26%2f + skip +[test_004a] encoded: http://a%253Ab:pass@example.com:80/foo%255Bbar%255D.baz?hash=%2526%252f#skip +[test_004b] encoded: http://a:b:pass@example.com:80/foo%5Bbar%5D.baz?hash=&/#skip +[test_004c] encoded: http://a:b:pass@example.com:80/foo%5Bbar%5D.baz?hash=&/#skip +[test_004d] encoded: http://a%253Ab:pass@example.com:80/foo%255Bbar%255D.baz?hash=%2526%252f#skip +[test_005a] encoded: http://a%3Ab:pass@example.com:80/foo%5Bbar%5D.baz?hash=%26%2f#skip +[test_005b] encoded: http://a%3Ab%3Apass@example.com:80%2Ffoo%5Bbar%5D.baz?hash=%26%2f#skip +[test_005c] encoded: http://a:b:pass@example.com:80/foo%5Bbar%5D.baz?hash=%26%2f#skip +[test_005d] encoded: http://a%3Ab:pass@example.com:80/foo%5Bbar%5D.baz?hash=%26%2f#skip +[test_005e] encoded: http://a%3Ab:pass@example.com:80/foo%5Bbar%5D.baz?hash=%26%2f#skip diff --git a/tests/03. unit tests/01. URL encoder/src/Main.java b/tests/03. unit tests/01. URL encoder/src/Main.java new file mode 100644 index 0000000..09a89ba --- /dev/null +++ b/tests/03. unit tests/01. URL encoder/src/Main.java @@ -0,0 +1,330 @@ +import android.net.Uri; + +import java.net.URI; +import java.net.URL; +import java.net.URLDecoder; +import java.net.URLEncoder; + +public class Main { + public static void run_test_001(String url_0, String TAG) { + try { + String url_1 = Uri.encode(url_0); + + System.out.println(TAG + "encoded: " + url_1); + } + catch(Exception e) { + System.out.println(TAG + "ERROR: " + e.getMessage()); + } + } + + public static void run_test_002(String url_0, String TAG) { + try { + Uri uri = Uri.parse(url_0); + String url_1 = uri.toString(); + + System.out.println(TAG + "encoded: " + url_1); + } + catch(Exception e) { + System.out.println(TAG + "ERROR: " + e.getMessage()); + } + } + + public static void run_test_003a(String url_0, String TAG) { + try { + Uri url = Uri.parse(url_0); + + String sep = "\n "; + String url_decoded = sep + url.getScheme() + sep + url.getUserInfo() + sep + url.getHost() + sep + url.getPort() + sep + url.getPath() + sep + url.getQuery() + sep + url.getFragment(); + String url_encoded = sep + url.getScheme() + sep + url.getEncodedUserInfo() + sep + url.getHost() + sep + url.getPort() + sep + url.getEncodedPath() + sep + url.getEncodedQuery() + sep + url.getEncodedFragment(); + + System.out.println(TAG + "decoded:" + url_decoded); + System.out.println(TAG + "encoded:" + url_encoded); + } + catch(Exception e) { + System.out.println(TAG + "ERROR: " + e.getMessage()); + } + } + + public static void run_test_003b(String url_0, String TAG) { + try { + URL url = new URL(url_0); + + String sep = "\n "; + String url_decoded = sep + url.getProtocol() + sep + url.getUserInfo() + sep + url.getHost() + sep + url.getPort() + sep + url.getPath() + sep + url.getQuery() + sep + url.getRef(); + + System.out.println(TAG + "decoded:" + url_decoded); + } + catch(Exception e) { + System.out.println(TAG + "ERROR: " + e.getMessage()); + } + } + + public static void run_test_004a(String url_0, String TAG) { + try { + URL url = new URL(url_0); + + URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); + String url_1 = uri.toASCIIString(); + + System.out.println(TAG + "encoded: " + url_1); + } + catch(Exception e) { + System.out.println(TAG + "ERROR: " + e.getMessage()); + } + } + + // note: this method represents the current methodology used by the app to encode URLs received as input from the user + public static void run_test_004b(String url_0, String TAG) { + try { + url_0 = URLDecoder.decode(url_0, "UTF-8"); + + URL url = new URL(url_0); + + URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); + String url_1 = uri.toASCIIString(); + + System.out.println(TAG + "encoded: " + url_1); + } + catch(Exception e) { + System.out.println(TAG + "ERROR: " + e.getMessage()); + } + } + + public static void run_test_004c(String url_0, String TAG) { + try { + Uri url = Uri.parse(url_0); + URI uri = new URI(url.getScheme(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getFragment()); + String url_1 = uri.toASCIIString(); + + System.out.println(TAG + "encoded: " + url_1); + } + catch(Exception e) { + System.out.println(TAG + "ERROR: " + e.getMessage()); + } + } + + public static void run_test_004d(String url_0, String TAG) { + try { + Uri url = Uri.parse(url_0); + URI uri = new URI(url.getScheme(), url.getEncodedUserInfo(), url.getHost(), url.getPort(), url.getEncodedPath(), url.getEncodedQuery(), url.getEncodedFragment()); + String url_1 = uri.toASCIIString(); + + System.out.println(TAG + "encoded: " + url_1); + } + catch(Exception e) { + System.out.println(TAG + "ERROR: " + e.getMessage()); + } + } + + public static void run_test_005a(String url_0, String TAG) { + try { + Uri url = Uri.parse(url_0); + + int iVal; + String sVal; + String url_1 = ""; + url_1 += url.getScheme() + "://"; + sVal = url.getEncodedUserInfo(); + if (sVal != null) + url_1 += sVal + "@"; + url_1 += url.getHost(); + iVal = url.getPort(); + if (iVal > 0) + url_1 += ":" + iVal; + url_1 += url.getEncodedPath(); + sVal = url.getEncodedQuery(); + if (sVal != null) + url_1 += "?" + sVal; + sVal = url.getEncodedFragment(); + if (sVal != null) + url_1 += "#" + sVal; + + System.out.println(TAG + "encoded: " + url_1); + } + catch(Exception e) { + System.out.println(TAG + "ERROR: " + e.getMessage()); + } + } + + public static void run_test_005b(String url_0, String TAG) { + try { + Uri url = Uri.parse(url_0); + + int iVal; + String sVal; + String url_1 = ""; + url_1 += url.getScheme() + "://"; + sVal = url.getUserInfo(); + if (sVal != null) + url_1 += encodeComponent(sVal) + "@"; + url_1 += url.getHost(); + iVal = url.getPort(); + if (iVal > 0) + url_1 += ":" + iVal; + url_1 += encodeComponent(url.getPath()); + sVal = url.getEncodedQuery(); + if (sVal != null) + url_1 += "?" + sVal; + sVal = url.getEncodedFragment(); + if (sVal != null) + url_1 += "#" + sVal; + + System.out.println(TAG + "encoded: " + url_1); + } + catch(Exception e) { + System.out.println(TAG + "ERROR: " + e.getMessage()); + } + } + + public static void run_test_005c(String url_0, String TAG) { + try { + Uri url = Uri.parse(url_0); + + int iVal; + String sVal; + String url_1 = ""; + url_1 += url.getScheme() + "://"; + sVal = url.getUserInfo(); + if (sVal != null) + url_1 += Uri.encode(sVal, ":") + "@"; + url_1 += url.getHost(); + iVal = url.getPort(); + if (iVal > 0) + url_1 += ":" + iVal; + url_1 += Uri.encode(url.getPath(), "/"); + sVal = url.getEncodedQuery(); + if (sVal != null) + url_1 += "?" + sVal; + sVal = url.getEncodedFragment(); + if (sVal != null) + url_1 += "#" + sVal; + + System.out.println(TAG + "encoded: " + url_1); + } + catch(Exception e) { + System.out.println(TAG + "ERROR: " + e.getMessage()); + } + } + + public static void run_test_005d(String url_0, String TAG) { + try { + Uri url = Uri.parse(url_0); + + int iVal; + String sVal; + String url_1 = ""; + url_1 += url.getScheme() + "://"; + sVal = url.getEncodedUserInfo(); + if (sVal != null) + url_1 += sVal + "@"; + url_1 += url.getHost(); + iVal = url.getPort(); + if (iVal > 0) + url_1 += ":" + iVal; + url_1 += Uri.encode(url.getPath(), "/"); + sVal = url.getEncodedQuery(); + if (sVal != null) + url_1 += "?" + sVal; + sVal = url.getEncodedFragment(); + if (sVal != null) + url_1 += "#" + sVal; + + System.out.println(TAG + "encoded: " + url_1); + } + catch(Exception e) { + System.out.println(TAG + "ERROR: " + e.getMessage()); + } + } + + /* =========================================================================== + https://developer.android.com/reference/android/net/Uri#encode(java.lang.String,%20java.lang.String) + Uri.encode() + always allow: + alpha = a-zA-Z + digit = 0-9 + other = _-!.~'()* + + https://www.rfc-editor.org/rfc/rfc3986#section-2.2 + reserved: + gen = :/?#[]@ + sub = !$&'()*+,;= + unreserved: + alpha = a-zA-Z + digit = 0-9 + other = -._~ + + summary: + reserved and not always allow: + gen = :/?#[]@ + sub = $&+,;= + * =========================================================================== + */ + public static void run_test_005e(String url_0, String TAG) { + try { + Uri url = Uri.parse(url_0); + + int iVal; + String sVal; + String url_1 = ""; + sVal = url.getScheme(); + if (sVal == null) + throw new Exception("scheme is required"); + url_1 += sVal + "://"; + sVal = url.getEncodedUserInfo(); + if (sVal != null) + url_1 += Uri.encode(sVal, "%:") + "@"; + url_1 += url.getHost(); + iVal = url.getPort(); + if (iVal > 0) + url_1 += ":" + iVal; + sVal = url.getEncodedPath(); + if (sVal == null) + throw new Exception("path is required"); + url_1 += Uri.encode(sVal, "%/"); + sVal = url.getEncodedQuery(); + if (sVal != null) + url_1 += "?" + Uri.encode(sVal, "%=&[]"); + sVal = url.getEncodedFragment(); + if (sVal != null) + url_1 += "#" + Uri.encode(sVal, "%/"); + + System.out.println(TAG + "encoded: " + url_1); + } + catch(Exception e) { + System.out.println(TAG + "ERROR: " + e.getMessage()); + } + } + + public static String encodeComponent(String s) { + try { + s = URLDecoder.decode(s, "UTF-8"); + s = URLEncoder.encode(s, "UTF-8"); + } + catch(Exception e) {} + return s; + } + + public static void run_tests(String url) { + System.out.println("\n" + "----------------------------------------" + "\n"); + System.out.println("[subject] url: " + url); + + run_test_001(url, "[test_001] "); + run_test_002(url, "[test_002] "); + run_test_003a(url, "[test_003a] "); + run_test_003b(url, "[test_003b] "); + run_test_004a(url, "[test_004a] "); + run_test_004b(url, "[test_004b] "); + run_test_004c(url, "[test_004c] "); + run_test_004d(url, "[test_004d] "); + run_test_005a(url, "[test_005a] "); + run_test_005b(url, "[test_005b] "); + run_test_005c(url, "[test_005c] "); + run_test_005d(url, "[test_005d] "); + run_test_005e(url, "[test_005e] "); + } + + public static void main(String args[]) { + run_tests("http://a%3Ab:pass@example.com:80/foo[bar].baz?hash=%26%2f#skip"); + run_tests("http://a%3Ab:pass@example.com:80/foo%5Bbar%5D.baz?hash=%26%2f#skip"); + } +} diff --git a/tests/04. integration tests/.gitignore b/tests/04. integration tests/.gitignore new file mode 100644 index 0000000..f14923c --- /dev/null +++ b/tests/04. integration tests/.gitignore @@ -0,0 +1,4 @@ +!**/bin +!**/lib +!**/src +!**/out diff --git a/tests/04. integration tests/01. URL encoder/bin/0-env.bat b/tests/04. integration tests/01. URL encoder/bin/0-env.bat new file mode 100644 index 0000000..050c22d --- /dev/null +++ b/tests/04. integration tests/01. URL encoder/bin/0-env.bat @@ -0,0 +1,5 @@ +@echo off + +set JDK_HOME=C:\Android\android-studio-2021.3.1.17\jre +set JRE_HOME=%JDK_HOME%\jre +set PATH=%JRE_HOME%\bin;%JDK_HOME%\bin;%PATH% diff --git a/tests/04. integration tests/01. URL encoder/bin/1-compile.bat b/tests/04. integration tests/01. URL encoder/bin/1-compile.bat new file mode 100644 index 0000000..6a98a52 --- /dev/null +++ b/tests/04. integration tests/01. URL encoder/bin/1-compile.bat @@ -0,0 +1,21 @@ +@echo off + +call "%~dp0.\0-env.bat" + +set output_dir=%~dp0..\out\%~n0 + +set options= +set options=%options% --source-path "%~dp0..\lib;%~dp0..\..\..\..\android-studio-project\ExoPlayer-AirPlay-Receiver\src\main\java" +set options=%options% -d "%output_dir%" +set options=%options% -encoding "UTF-8" +set options=%options% -g:none + +set sourcefile="%~dp0..\src\Main.java" + +if exist "%output_dir%" rmdir /Q /S "%output_dir%" +mkdir "%output_dir%" + +javac %options% %sourcefile% + +echo. +pause diff --git a/tests/04. integration tests/01. URL encoder/bin/2-run.bat b/tests/04. integration tests/01. URL encoder/bin/2-run.bat new file mode 100644 index 0000000..c03d921 --- /dev/null +++ b/tests/04. integration tests/01. URL encoder/bin/2-run.bat @@ -0,0 +1,17 @@ +@echo off + +call "%~dp0.\0-env.bat" + +set output_dir=%~dp0..\out\%~n0 +set stdout_file="%output_dir%\stdout.txt" +set stderr_file="%output_dir%\stderr.txt" + +set options= +set options=%options% --class-path "%output_dir%\..\1-compile" + +set mainclass="Main" + +if exist "%output_dir%" rmdir /Q /S "%output_dir%" +mkdir "%output_dir%" + +java %options% %mainclass% 1>%stdout_file% 2>%stderr_file% diff --git a/tests/04. integration tests/01. URL encoder/lib/android/net/Uri.java b/tests/04. integration tests/01. URL encoder/lib/android/net/Uri.java new file mode 100644 index 0000000..81752b7 --- /dev/null +++ b/tests/04. integration tests/01. URL encoder/lib/android/net/Uri.java @@ -0,0 +1,2255 @@ +/* ============ + * copied from: + * https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/net/Uri.java + * ============ + * JavaDoc at: + * https://developer.android.com/reference/android/net/Uri + * ============ + */ + +/* + * Copyright (C) 2007 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.net; + +import java.io.File; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.AbstractList; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Objects; +import java.util.RandomAccess; +import java.util.Set; + +/** + * Immutable URI reference. A URI reference includes a URI and a fragment, the + * component of the URI following a '#'. Builds and parses URI references + * which conform to + * RFC 2396. + * + *

In the interest of performance, this class performs little to no + * validation. Behavior is undefined for invalid input. This class is very + * forgiving--in the face of invalid input, it will return garbage + * rather than throw an exception unless otherwise specified. + */ +public abstract class Uri implements Comparable { + + /* + + This class aims to do as little up front work as possible. To accomplish + that, we vary the implementation depending on what the user passes in. + For example, we have one implementation if the user passes in a + URI string (StringUri) and another if the user passes in the + individual components (OpaqueUri). + + *Concurrency notes*: Like any truly immutable object, this class is safe + for concurrent use. This class uses a caching pattern in some places where + it doesn't use volatile or synchronized. This is safe to do with ints + because getting or setting an int is atomic. It's safe to do with a String + because the internal fields are final and the memory model guarantees other + threads won't see a partially initialized instance. We are not guaranteed + that some threads will immediately see changes from other threads on + certain platforms, but we don't mind if those threads reconstruct the + cached result. As a result, we get thread safe caching with no concurrency + overhead, which means the most common case, access from a single thread, + is as fast as possible. + + From the Java Language spec.: + + "17.5 Final Field Semantics + + ... when the object is seen by another thread, that thread will always + see the correctly constructed version of that object's final fields. + It will also see versions of any object or array referenced by + those final fields that are at least as up-to-date as the final fields + are." + + In that same vein, all non-transient fields within Uri + implementations should be final and immutable so as to ensure true + immutability for clients even when they don't use proper concurrency + control. + + For reference, from RFC 2396: + + "4.3. Parsing a URI Reference + + A URI reference is typically parsed according to the four main + components and fragment identifier in order to determine what + components are present and whether the reference is relative or + absolute. The individual components are then parsed for their + subparts and, if not opaque, to verify their validity. + + Although the BNF defines what is allowed in each component, it is + ambiguous in terms of differentiating between an authority component + and a path component that begins with two slash characters. The + greedy algorithm is used for disambiguation: the left-most matching + rule soaks up as much of the URI reference string as it is capable of + matching. In other words, the authority component wins." + + The "four main components" of a hierarchical URI consist of + ://? + + */ + + /** + * + * Holds a placeholder for strings which haven't been cached. This enables us + * to cache null. We intentionally create a new String instance so we can + * compare its identity and there is no chance we will confuse it with + * user data. + * + * NOTE This value is held in its own Holder class is so that referring to + * {@link NotCachedHolder#NOT_CACHED} does not trigger {@code Uri.}. + * For example, {@code PathPart.} uses {@code NotCachedHolder.NOT_CACHED} + * but must not trigger {@code Uri.}: Otherwise, the initialization of + * {@code Uri.EMPTY} would see a {@code null} value for {@code PathPart.EMPTY}! + * + * @hide + */ + static class NotCachedHolder { + private NotCachedHolder() { + // prevent instantiation + } + @SuppressWarnings("RedundantStringConstructorCall") + static final String NOT_CACHED = new String("NOT CACHED"); + } + + /** + * The empty URI, equivalent to "". + */ + public static final Uri EMPTY = new HierarchicalUri(null, Part.NULL, + PathPart.EMPTY, Part.NULL, Part.NULL); + + /** + * Prevents external subclassing. + */ + private Uri() {} + + /** + * Returns true if this URI is hierarchical like "http://google.com". + * Absolute URIs are hierarchical if the scheme-specific part starts with + * a '/'. Relative URIs are always hierarchical. + */ + public abstract boolean isHierarchical(); + + /** + * Returns true if this URI is opaque like "mailto:nobody@google.com". The + * scheme-specific part of an opaque URI cannot start with a '/'. + */ + public boolean isOpaque() { + return !isHierarchical(); + } + + /** + * Returns true if this URI is relative, i.e. if it doesn't contain an + * explicit scheme. + * + * @return true if this URI is relative, false if it's absolute + */ + public abstract boolean isRelative(); + + /** + * Returns true if this URI is absolute, i.e. if it contains an + * explicit scheme. + * + * @return true if this URI is absolute, false if it's relative + */ + public boolean isAbsolute() { + return !isRelative(); + } + + /** + * Gets the scheme of this URI. Example: "http" + * + * @return the scheme or null if this is a relative URI + */ + public abstract String getScheme(); + + /** + * Gets the scheme-specific part of this URI, i.e. everything between + * the scheme separator ':' and the fragment separator '#'. If this is a + * relative URI, this method returns the entire URI. Decodes escaped octets. + * + *

Example: "//www.google.com/search?q=android" + * + * @return the decoded scheme-specific-part + */ + public abstract String getSchemeSpecificPart(); + + /** + * Gets the scheme-specific part of this URI, i.e. everything between + * the scheme separator ':' and the fragment separator '#'. If this is a + * relative URI, this method returns the entire URI. Leaves escaped octets + * intact. + * + *

Example: "//www.google.com/search?q=android" + * + * @return the encoded scheme-specific-part + */ + public abstract String getEncodedSchemeSpecificPart(); + + /** + * Gets the decoded authority part of this URI. For + * server addresses, the authority is structured as follows: + * {@code [ userinfo '@' ] host [ ':' port ]} + * + *

Examples: "google.com", "bob@google.com:80" + * + * @return the authority for this URI or null if not present + */ + public abstract String getAuthority(); + + /** + * Gets the encoded authority part of this URI. For + * server addresses, the authority is structured as follows: + * {@code [ userinfo '@' ] host [ ':' port ]} + * + *

Examples: "google.com", "bob@google.com:80" + * + * @return the authority for this URI or null if not present + */ + public abstract String getEncodedAuthority(); + + /** + * Gets the decoded user information from the authority. + * For example, if the authority is "nobody@google.com", this method will + * return "nobody". + * + * @return the user info for this URI or null if not present + */ + public abstract String getUserInfo(); + + /** + * Gets the encoded user information from the authority. + * For example, if the authority is "nobody@google.com", this method will + * return "nobody". + * + * @return the user info for this URI or null if not present + */ + public abstract String getEncodedUserInfo(); + + /** + * Gets the encoded host from the authority for this URI. For example, + * if the authority is "bob@google.com", this method will return + * "google.com". + * + * @return the host for this URI or null if not present + */ + public abstract String getHost(); + + /** + * Gets the port from the authority for this URI. For example, + * if the authority is "google.com:80", this method will return 80. + * + * @return the port for this URI or -1 if invalid or not present + */ + public abstract int getPort(); + + /** + * Gets the decoded path. + * + * @return the decoded path, or null if this is not a hierarchical URI + * (like "mailto:nobody@google.com") or the URI is invalid + */ + public abstract String getPath(); + + /** + * Gets the encoded path. + * + * @return the encoded path, or null if this is not a hierarchical URI + * (like "mailto:nobody@google.com") or the URI is invalid + */ + public abstract String getEncodedPath(); + + /** + * Gets the decoded query component from this URI. The query comes after + * the query separator ('?') and before the fragment separator ('#'). This + * method would return "q=android" for + * "http://www.google.com/search?q=android". + * + * @return the decoded query or null if there isn't one + */ + public abstract String getQuery(); + + /** + * Gets the encoded query component from this URI. The query comes after + * the query separator ('?') and before the fragment separator ('#'). This + * method would return "q=android" for + * "http://www.google.com/search?q=android". + * + * @return the encoded query or null if there isn't one + */ + public abstract String getEncodedQuery(); + + /** + * Gets the decoded fragment part of this URI, everything after the '#'. + * + * @return the decoded fragment or null if there isn't one + */ + public abstract String getFragment(); + + /** + * Gets the encoded fragment part of this URI, everything after the '#'. + * + * @return the encoded fragment or null if there isn't one + */ + public abstract String getEncodedFragment(); + + /** + * Gets the decoded path segments. + * + * @return decoded path segments, each without a leading or trailing '/' + */ + public abstract List getPathSegments(); + + /** + * Gets the decoded last segment in the path. + * + * @return the decoded last segment or null if the path is empty + */ + public abstract String getLastPathSegment(); + + /** + * Compares this Uri to another object for equality. Returns true if the + * encoded string representations of this Uri and the given Uri are + * equal. Case counts. Paths are not normalized. If one Uri specifies a + * default port explicitly and the other leaves it implicit, they will not + * be considered equal. + */ + public boolean equals(Object o) { + if (!(o instanceof Uri)) { + return false; + } + + Uri other = (Uri) o; + + return toString().equals(other.toString()); + } + + /** + * Hashes the encoded string represention of this Uri consistently with + * {@link #equals(Object)}. + */ + public int hashCode() { + return toString().hashCode(); + } + + /** + * Compares the string representation of this Uri with that of + * another. + */ + public int compareTo(Uri other) { + return toString().compareTo(other.toString()); + } + + /** + * Returns the encoded string representation of this URI. + * Example: "http://google.com/" + */ + public abstract String toString(); + + /** + * Return a string representation of this URI that has common forms of PII redacted, + * making it safer to use for logging purposes. For example, {@code tel:800-466-4411} is + * returned as {@code tel:xxx-xxx-xxxx} and {@code http://example.com/path/to/item/} is + * returned as {@code http://example.com/...}. For all other uri schemes, only the scheme, + * host and port are returned. + * @return the common forms PII redacted string of this URI + * @hide + */ + public String toSafeString() { + String scheme = getScheme(); + String ssp = getSchemeSpecificPart(); + StringBuilder builder = new StringBuilder(64); + + if (scheme != null) { + builder.append(scheme); + builder.append(":"); + if (scheme.equalsIgnoreCase("tel") || scheme.equalsIgnoreCase("sip") + || scheme.equalsIgnoreCase("sms") || scheme.equalsIgnoreCase("smsto") + || scheme.equalsIgnoreCase("mailto") || scheme.equalsIgnoreCase("nfc")) { + if (ssp != null) { + for (int i=0; i". Encodes path characters with the exception of + * '/'. + * + *

Example: "file:///tmp/android.txt" + * + * @throws NullPointerException if file is null + * @return a Uri for the given file + */ + public static Uri fromFile(File file) { + if (file == null) { + throw new NullPointerException("file"); + } + + PathPart path = PathPart.fromDecoded(file.getAbsolutePath()); + return new HierarchicalUri( + "file", Part.EMPTY, path, Part.NULL, Part.NULL); + } + + /** + * An implementation which wraps a String URI. This URI can be opaque or + * hierarchical, but we extend AbstractHierarchicalUri in case we need + * the hierarchical functionality. + */ + private static class StringUri extends AbstractHierarchicalUri { + + /** Used in parcelling. */ + static final int TYPE_ID = 1; + + /** URI string representation. */ + private final String uriString; + + private StringUri(String uriString) { + if (uriString == null) { + throw new NullPointerException("uriString"); + } + + this.uriString = uriString; + } + + public int describeContents() { + return 0; + } + + /** Cached scheme separator index. */ + private volatile int cachedSsi = NOT_CALCULATED; + + /** Finds the first ':'. Returns -1 if none found. */ + private int findSchemeSeparator() { + return cachedSsi == NOT_CALCULATED + ? cachedSsi = uriString.indexOf(':') + : cachedSsi; + } + + /** Cached fragment separator index. */ + private volatile int cachedFsi = NOT_CALCULATED; + + /** Finds the first '#'. Returns -1 if none found. */ + private int findFragmentSeparator() { + return cachedFsi == NOT_CALCULATED + ? cachedFsi = uriString.indexOf('#', findSchemeSeparator()) + : cachedFsi; + } + + public boolean isHierarchical() { + int ssi = findSchemeSeparator(); + + if (ssi == NOT_FOUND) { + // All relative URIs are hierarchical. + return true; + } + + if (uriString.length() == ssi + 1) { + // No ssp. + return false; + } + + // If the ssp starts with a '/', this is hierarchical. + return uriString.charAt(ssi + 1) == '/'; + } + + public boolean isRelative() { + // Note: We return true if the index is 0 + return findSchemeSeparator() == NOT_FOUND; + } + + private volatile String scheme = NotCachedHolder.NOT_CACHED; + + public String getScheme() { + @SuppressWarnings("StringEquality") + boolean cached = (scheme != NotCachedHolder.NOT_CACHED); + return cached ? scheme : (scheme = parseScheme()); + } + + private String parseScheme() { + int ssi = findSchemeSeparator(); + return ssi == NOT_FOUND ? null : uriString.substring(0, ssi); + } + + private Part ssp; + + private Part getSsp() { + return ssp == null ? ssp = Part.fromEncoded(parseSsp()) : ssp; + } + + public String getEncodedSchemeSpecificPart() { + return getSsp().getEncoded(); + } + + public String getSchemeSpecificPart() { + return getSsp().getDecoded(); + } + + private String parseSsp() { + int ssi = findSchemeSeparator(); + int fsi = findFragmentSeparator(); + + // Return everything between ssi and fsi. + return fsi == NOT_FOUND + ? uriString.substring(ssi + 1) + : uriString.substring(ssi + 1, fsi); + } + + private Part authority; + + private Part getAuthorityPart() { + if (authority == null) { + String encodedAuthority + = parseAuthority(this.uriString, findSchemeSeparator()); + return authority = Part.fromEncoded(encodedAuthority); + } + + return authority; + } + + public String getEncodedAuthority() { + return getAuthorityPart().getEncoded(); + } + + public String getAuthority() { + return getAuthorityPart().getDecoded(); + } + + private PathPart path; + + private PathPart getPathPart() { + return path == null + ? path = PathPart.fromEncoded(parsePath()) + : path; + } + + public String getPath() { + return getPathPart().getDecoded(); + } + + public String getEncodedPath() { + return getPathPart().getEncoded(); + } + + public List getPathSegments() { + return getPathPart().getPathSegments(); + } + + private String parsePath() { + String uriString = this.uriString; + int ssi = findSchemeSeparator(); + + // If the URI is absolute. + if (ssi > -1) { + // Is there anything after the ':'? + boolean schemeOnly = ssi + 1 == uriString.length(); + if (schemeOnly) { + // Opaque URI. + return null; + } + + // A '/' after the ':' means this is hierarchical. + if (uriString.charAt(ssi + 1) != '/') { + // Opaque URI. + return null; + } + } else { + // All relative URIs are hierarchical. + } + + return parsePath(uriString, ssi); + } + + private Part query; + + private Part getQueryPart() { + return query == null + ? query = Part.fromEncoded(parseQuery()) : query; + } + + public String getEncodedQuery() { + return getQueryPart().getEncoded(); + } + + private String parseQuery() { + // It doesn't make sense to cache this index. We only ever + // calculate it once. + int qsi = uriString.indexOf('?', findSchemeSeparator()); + if (qsi == NOT_FOUND) { + return null; + } + + int fsi = findFragmentSeparator(); + + if (fsi == NOT_FOUND) { + return uriString.substring(qsi + 1); + } + + if (fsi < qsi) { + // Invalid. + return null; + } + + return uriString.substring(qsi + 1, fsi); + } + + public String getQuery() { + return getQueryPart().getDecoded(); + } + + private Part fragment; + + private Part getFragmentPart() { + return fragment == null + ? fragment = Part.fromEncoded(parseFragment()) : fragment; + } + + public String getEncodedFragment() { + return getFragmentPart().getEncoded(); + } + + private String parseFragment() { + int fsi = findFragmentSeparator(); + return fsi == NOT_FOUND ? null : uriString.substring(fsi + 1); + } + + public String getFragment() { + return getFragmentPart().getDecoded(); + } + + public String toString() { + return uriString; + } + + /** + * Parses an authority out of the given URI string. + * + * @param uriString URI string + * @param ssi scheme separator index, -1 for a relative URI + * + * @return the authority or null if none is found + */ + static String parseAuthority(String uriString, int ssi) { + int length = uriString.length(); + + // If "//" follows the scheme separator, we have an authority. + if (length > ssi + 2 + && uriString.charAt(ssi + 1) == '/' + && uriString.charAt(ssi + 2) == '/') { + // We have an authority. + + // Look for the start of the path, query, or fragment, or the + // end of the string. + int end = ssi + 3; + LOOP: while (end < length) { + switch (uriString.charAt(end)) { + case '/': // Start of path + case '\\':// Start of path + // Per http://url.spec.whatwg.org/#host-state, the \ character + // is treated as if it were a / character when encountered in a + // host + case '?': // Start of query + case '#': // Start of fragment + break LOOP; + } + end++; + } + + return uriString.substring(ssi + 3, end); + } else { + return null; + } + + } + + /** + * Parses a path out of this given URI string. + * + * @param uriString URI string + * @param ssi scheme separator index, -1 for a relative URI + * + * @return the path + */ + static String parsePath(String uriString, int ssi) { + int length = uriString.length(); + + // Find start of path. + int pathStart; + if (length > ssi + 2 + && uriString.charAt(ssi + 1) == '/' + && uriString.charAt(ssi + 2) == '/') { + // Skip over authority to path. + pathStart = ssi + 3; + LOOP: while (pathStart < length) { + switch (uriString.charAt(pathStart)) { + case '?': // Start of query + case '#': // Start of fragment + return ""; // Empty path. + case '/': // Start of path! + case '\\':// Start of path! + // Per http://url.spec.whatwg.org/#host-state, the \ character + // is treated as if it were a / character when encountered in a + // host + break LOOP; + } + pathStart++; + } + } else { + // Path starts immediately after scheme separator. + pathStart = ssi + 1; + } + + // Find end of path. + int pathEnd = pathStart; + LOOP: while (pathEnd < length) { + switch (uriString.charAt(pathEnd)) { + case '?': // Start of query + case '#': // Start of fragment + break LOOP; + } + pathEnd++; + } + + return uriString.substring(pathStart, pathEnd); + } + + public Builder buildUpon() { + if (isHierarchical()) { + return new Builder() + .scheme(getScheme()) + .authority(getAuthorityPart()) + .path(getPathPart()) + .query(getQueryPart()) + .fragment(getFragmentPart()); + } else { + return new Builder() + .scheme(getScheme()) + .opaquePart(getSsp()) + .fragment(getFragmentPart()); + } + } + } + + /** + * Creates an opaque Uri from the given components. Encodes the ssp + * which means this method cannot be used to create hierarchical URIs. + * + * @param scheme of the URI + * @param ssp scheme-specific-part, everything between the + * scheme separator (':') and the fragment separator ('#'), which will + * get encoded + * @param fragment fragment, everything after the '#', null if undefined, + * will get encoded + * + * @throws NullPointerException if scheme or ssp is null + * @return Uri composed of the given scheme, ssp, and fragment + * + * @see Builder if you don't want the ssp and fragment to be encoded + */ + public static Uri fromParts(String scheme, String ssp, + String fragment) { + if (scheme == null) { + throw new NullPointerException("scheme"); + } + if (ssp == null) { + throw new NullPointerException("ssp"); + } + + return new OpaqueUri(scheme, Part.fromDecoded(ssp), + Part.fromDecoded(fragment)); + } + + /** + * Opaque URI. + */ + private static class OpaqueUri extends Uri { + + /** Used in parcelling. */ + static final int TYPE_ID = 2; + + private final String scheme; + private final Part ssp; + private final Part fragment; + + private OpaqueUri(String scheme, Part ssp, Part fragment) { + this.scheme = scheme; + this.ssp = ssp; + this.fragment = fragment == null ? Part.NULL : fragment; + } + + public int describeContents() { + return 0; + } + + public boolean isHierarchical() { + return false; + } + + public boolean isRelative() { + return scheme == null; + } + + public String getScheme() { + return this.scheme; + } + + public String getEncodedSchemeSpecificPart() { + return ssp.getEncoded(); + } + + public String getSchemeSpecificPart() { + return ssp.getDecoded(); + } + + public String getAuthority() { + return null; + } + + public String getEncodedAuthority() { + return null; + } + + public String getPath() { + return null; + } + + public String getEncodedPath() { + return null; + } + + public String getQuery() { + return null; + } + + public String getEncodedQuery() { + return null; + } + + public String getFragment() { + return fragment.getDecoded(); + } + + public String getEncodedFragment() { + return fragment.getEncoded(); + } + + public List getPathSegments() { + return Collections.emptyList(); + } + + public String getLastPathSegment() { + return null; + } + + public String getUserInfo() { + return null; + } + + public String getEncodedUserInfo() { + return null; + } + + public String getHost() { + return null; + } + + public int getPort() { + return -1; + } + + private volatile String cachedString = NotCachedHolder.NOT_CACHED; + + public String toString() { + @SuppressWarnings("StringEquality") + boolean cached = cachedString != NotCachedHolder.NOT_CACHED; + if (cached) { + return cachedString; + } + + StringBuilder sb = new StringBuilder(); + + sb.append(scheme).append(':'); + sb.append(getEncodedSchemeSpecificPart()); + + if (!fragment.isEmpty()) { + sb.append('#').append(fragment.getEncoded()); + } + + return cachedString = sb.toString(); + } + + public Builder buildUpon() { + return new Builder() + .scheme(this.scheme) + .opaquePart(this.ssp) + .fragment(this.fragment); + } + } + + /** + * Wrapper for path segment array. + */ + static class PathSegments extends AbstractList + implements RandomAccess { + + static final PathSegments EMPTY = new PathSegments(null, 0); + + final String[] segments; + final int size; + + PathSegments(String[] segments, int size) { + this.segments = segments; + this.size = size; + } + + public String get(int index) { + if (index >= size) { + throw new IndexOutOfBoundsException(); + } + + return segments[index]; + } + + public int size() { + return this.size; + } + } + + /** + * Builds PathSegments. + */ + static class PathSegmentsBuilder { + + String[] segments; + int size = 0; + + void add(String segment) { + if (segments == null) { + segments = new String[4]; + } else if (size + 1 == segments.length) { + String[] expanded = new String[segments.length * 2]; + System.arraycopy(segments, 0, expanded, 0, segments.length); + segments = expanded; + } + + segments[size++] = segment; + } + + PathSegments build() { + if (segments == null) { + return PathSegments.EMPTY; + } + + try { + return new PathSegments(segments, size); + } finally { + // Makes sure this doesn't get reused. + segments = null; + } + } + } + + /** + * Support for hierarchical URIs. + */ + private abstract static class AbstractHierarchicalUri extends Uri { + + public String getLastPathSegment() { + // TODO: If we haven't parsed all of the segments already, just + // grab the last one directly so we only allocate one string. + + List segments = getPathSegments(); + int size = segments.size(); + if (size == 0) { + return null; + } + return segments.get(size - 1); + } + + private Part userInfo; + + private Part getUserInfoPart() { + return userInfo == null + ? userInfo = Part.fromEncoded(parseUserInfo()) : userInfo; + } + + public final String getEncodedUserInfo() { + return getUserInfoPart().getEncoded(); + } + + private String parseUserInfo() { + String authority = getEncodedAuthority(); + if (authority == null) { + return null; + } + + int end = authority.lastIndexOf('@'); + return end == NOT_FOUND ? null : authority.substring(0, end); + } + + public String getUserInfo() { + return getUserInfoPart().getDecoded(); + } + + private volatile String host = NotCachedHolder.NOT_CACHED; + + public String getHost() { + @SuppressWarnings("StringEquality") + boolean cached = (host != NotCachedHolder.NOT_CACHED); + return cached ? host : (host = parseHost()); + } + + private String parseHost() { + final String authority = getEncodedAuthority(); + if (authority == null) { + return null; + } + + // Parse out user info and then port. + int userInfoSeparator = authority.lastIndexOf('@'); + int portSeparator = findPortSeparator(authority); + + String encodedHost = portSeparator == NOT_FOUND + ? authority.substring(userInfoSeparator + 1) + : authority.substring(userInfoSeparator + 1, portSeparator); + + return decode(encodedHost); + } + + private volatile int port = NOT_CALCULATED; + + public int getPort() { + return port == NOT_CALCULATED + ? port = parsePort() + : port; + } + + private int parsePort() { + final String authority = getEncodedAuthority(); + int portSeparator = findPortSeparator(authority); + if (portSeparator == NOT_FOUND) { + return -1; + } + + String portString = decode(authority.substring(portSeparator + 1)); + try { + return Integer.parseInt(portString); + } catch (NumberFormatException e) { + return -1; + } + } + + private int findPortSeparator(String authority) { + if (authority == null) { + return NOT_FOUND; + } + + // Reverse search for the ':' character that breaks as soon as a char that is neither + // a colon nor an ascii digit is encountered. Thanks to the goodness of UTF-16 encoding, + // it's not possible that a surrogate matches one of these, so this loop can just + // look for characters rather than care about code points. + for (int i = authority.length() - 1; i >= 0; --i) { + final int character = authority.charAt(i); + if (':' == character) return i; + // Character.isDigit would include non-ascii digits + if (character < '0' || character > '9') return NOT_FOUND; + } + return NOT_FOUND; + } + } + + /** + * Hierarchical Uri. + */ + private static class HierarchicalUri extends AbstractHierarchicalUri { + + /** Used in parcelling. */ + static final int TYPE_ID = 3; + + private final String scheme; // can be null + private final Part authority; + private final PathPart path; + private final Part query; + private final Part fragment; + + private HierarchicalUri(String scheme, Part authority, PathPart path, + Part query, Part fragment) { + this.scheme = scheme; + this.authority = Part.nonNull(authority); + this.path = path == null ? PathPart.NULL : path; + this.query = Part.nonNull(query); + this.fragment = Part.nonNull(fragment); + } + + public int describeContents() { + return 0; + } + + public boolean isHierarchical() { + return true; + } + + public boolean isRelative() { + return scheme == null; + } + + public String getScheme() { + return scheme; + } + + private Part ssp; + + private Part getSsp() { + return ssp == null + ? ssp = Part.fromEncoded(makeSchemeSpecificPart()) : ssp; + } + + public String getEncodedSchemeSpecificPart() { + return getSsp().getEncoded(); + } + + public String getSchemeSpecificPart() { + return getSsp().getDecoded(); + } + + /** + * Creates the encoded scheme-specific part from its sub parts. + */ + private String makeSchemeSpecificPart() { + StringBuilder builder = new StringBuilder(); + appendSspTo(builder); + return builder.toString(); + } + + private void appendSspTo(StringBuilder builder) { + String encodedAuthority = authority.getEncoded(); + if (encodedAuthority != null) { + // Even if the authority is "", we still want to append "//". + builder.append("//").append(encodedAuthority); + } + + String encodedPath = path.getEncoded(); + if (encodedPath != null) { + builder.append(encodedPath); + } + + if (!query.isEmpty()) { + builder.append('?').append(query.getEncoded()); + } + } + + public String getAuthority() { + return this.authority.getDecoded(); + } + + public String getEncodedAuthority() { + return this.authority.getEncoded(); + } + + public String getEncodedPath() { + return this.path.getEncoded(); + } + + public String getPath() { + return this.path.getDecoded(); + } + + public String getQuery() { + return this.query.getDecoded(); + } + + public String getEncodedQuery() { + return this.query.getEncoded(); + } + + public String getFragment() { + return this.fragment.getDecoded(); + } + + public String getEncodedFragment() { + return this.fragment.getEncoded(); + } + + public List getPathSegments() { + return this.path.getPathSegments(); + } + + private volatile String uriString = NotCachedHolder.NOT_CACHED; + + @Override + public String toString() { + @SuppressWarnings("StringEquality") + boolean cached = (uriString != NotCachedHolder.NOT_CACHED); + return cached ? uriString + : (uriString = makeUriString()); + } + + private String makeUriString() { + StringBuilder builder = new StringBuilder(); + + if (scheme != null) { + builder.append(scheme).append(':'); + } + + appendSspTo(builder); + + if (!fragment.isEmpty()) { + builder.append('#').append(fragment.getEncoded()); + } + + return builder.toString(); + } + + public Builder buildUpon() { + return new Builder() + .scheme(scheme) + .authority(authority) + .path(path) + .query(query) + .fragment(fragment); + } + } + + /** + * Helper class for building or manipulating URI references. Not safe for + * concurrent use. + * + *

An absolute hierarchical URI reference follows the pattern: + * {@code ://?#} + * + *

Relative URI references (which are always hierarchical) follow one + * of two patterns: {@code ?#} + * or {@code //?#} + * + *

An opaque URI follows this pattern: + * {@code :#} + * + *

Use {@link Uri#buildUpon()} to obtain a builder representing an existing URI. + */ + public static final class Builder { + + private String scheme; + private Part opaquePart; + private Part authority; + private PathPart path; + private Part query; + private Part fragment; + + /** + * Constructs a new Builder. + */ + public Builder() {} + + /** + * Sets the scheme. + * + * @param scheme name or {@code null} if this is a relative Uri + */ + public Builder scheme(String scheme) { + this.scheme = scheme; + return this; + } + + Builder opaquePart(Part opaquePart) { + this.opaquePart = opaquePart; + return this; + } + + /** + * Encodes and sets the given opaque scheme-specific-part. + * + * @param opaquePart decoded opaque part + */ + public Builder opaquePart(String opaquePart) { + return opaquePart(Part.fromDecoded(opaquePart)); + } + + /** + * Sets the previously encoded opaque scheme-specific-part. + * + * @param opaquePart encoded opaque part + */ + public Builder encodedOpaquePart(String opaquePart) { + return opaquePart(Part.fromEncoded(opaquePart)); + } + + Builder authority(Part authority) { + // This URI will be hierarchical. + this.opaquePart = null; + + this.authority = authority; + return this; + } + + /** + * Encodes and sets the authority. + */ + public Builder authority(String authority) { + return authority(Part.fromDecoded(authority)); + } + + /** + * Sets the previously encoded authority. + */ + public Builder encodedAuthority(String authority) { + return authority(Part.fromEncoded(authority)); + } + + Builder path(PathPart path) { + // This URI will be hierarchical. + this.opaquePart = null; + + this.path = path; + return this; + } + + /** + * Sets the path. Leaves '/' characters intact but encodes others as + * necessary. + * + *

If the path is not null and doesn't start with a '/', and if + * you specify a scheme and/or authority, the builder will prepend the + * given path with a '/'. + */ + public Builder path(String path) { + return path(PathPart.fromDecoded(path)); + } + + /** + * Sets the previously encoded path. + * + *

If the path is not null and doesn't start with a '/', and if + * you specify a scheme and/or authority, the builder will prepend the + * given path with a '/'. + */ + public Builder encodedPath(String path) { + return path(PathPart.fromEncoded(path)); + } + + /** + * Encodes the given segment and appends it to the path. + */ + public Builder appendPath(String newSegment) { + return path(PathPart.appendDecodedSegment(path, newSegment)); + } + + /** + * Appends the given segment to the path. + */ + public Builder appendEncodedPath(String newSegment) { + return path(PathPart.appendEncodedSegment(path, newSegment)); + } + + Builder query(Part query) { + // This URI will be hierarchical. + this.opaquePart = null; + + this.query = query; + return this; + } + + /** + * Encodes and sets the query. + */ + public Builder query(String query) { + return query(Part.fromDecoded(query)); + } + + /** + * Sets the previously encoded query. + */ + public Builder encodedQuery(String query) { + return query(Part.fromEncoded(query)); + } + + Builder fragment(Part fragment) { + this.fragment = fragment; + return this; + } + + /** + * Encodes and sets the fragment. + */ + public Builder fragment(String fragment) { + return fragment(Part.fromDecoded(fragment)); + } + + /** + * Sets the previously encoded fragment. + */ + public Builder encodedFragment(String fragment) { + return fragment(Part.fromEncoded(fragment)); + } + + /** + * Encodes the key and value and then appends the parameter to the + * query string. + * + * @param key which will be encoded + * @param value which will be encoded + */ + public Builder appendQueryParameter(String key, String value) { + // This URI will be hierarchical. + this.opaquePart = null; + + String encodedParameter = encode(key, null) + "=" + + encode(value, null); + + if (query == null) { + query = Part.fromEncoded(encodedParameter); + return this; + } + + String oldQuery = query.getEncoded(); + if (oldQuery == null || oldQuery.length() == 0) { + query = Part.fromEncoded(encodedParameter); + } else { + query = Part.fromEncoded(oldQuery + "&" + encodedParameter); + } + + return this; + } + + /** + * Clears the the previously set query. + */ + public Builder clearQuery() { + return query((Part) null); + } + + /** + * Constructs a Uri with the current attributes. + * + * @throws UnsupportedOperationException if the URI is opaque and the + * scheme is null + */ + public Uri build() { + if (opaquePart != null) { + if (this.scheme == null) { + throw new UnsupportedOperationException( + "An opaque URI must have a scheme."); + } + + return new OpaqueUri(scheme, opaquePart, fragment); + } else { + // Hierarchical URIs should not return null for getPath(). + PathPart path = this.path; + if (path == null || path == PathPart.NULL) { + path = PathPart.EMPTY; + } else { + // If we have a scheme and/or authority, the path must + // be absolute. Prepend it with a '/' if necessary. + if (hasSchemeOrAuthority()) { + path = PathPart.makeAbsolute(path); + } + } + + return new HierarchicalUri( + scheme, authority, path, query, fragment); + } + } + + private boolean hasSchemeOrAuthority() { + return scheme != null + || (authority != null && authority != Part.NULL); + + } + + @Override + public String toString() { + return build().toString(); + } + } + + /** + * Returns a set of the unique names of all query parameters. Iterating + * over the set will return the names in order of their first occurrence. + * + * @throws UnsupportedOperationException if this isn't a hierarchical URI + * + * @return a set of decoded names + */ + public Set getQueryParameterNames() { + if (isOpaque()) { + throw new UnsupportedOperationException(NOT_HIERARCHICAL); + } + + String query = getEncodedQuery(); + if (query == null) { + return Collections.emptySet(); + } + + Set names = new LinkedHashSet(); + int start = 0; + do { + int next = query.indexOf('&', start); + int end = (next == -1) ? query.length() : next; + + int separator = query.indexOf('=', start); + if (separator > end || separator == -1) { + separator = end; + } + + String name = query.substring(start, separator); + names.add(decode(name)); + + // Move start to end of name. + start = end + 1; + } while (start < query.length()); + + return Collections.unmodifiableSet(names); + } + + /** + * Searches the query string for parameter values with the given key. + * + * @param key which will be encoded + * + * @throws UnsupportedOperationException if this isn't a hierarchical URI + * @throws NullPointerException if key is null + * @return a list of decoded values + */ + public List getQueryParameters(String key) { + if (isOpaque()) { + throw new UnsupportedOperationException(NOT_HIERARCHICAL); + } + if (key == null) { + throw new NullPointerException("key"); + } + + String query = getEncodedQuery(); + if (query == null) { + return Collections.emptyList(); + } + + String encodedKey; + try { + encodedKey = URLEncoder.encode(key, DEFAULT_ENCODING); + } catch (UnsupportedEncodingException e) { + throw new AssertionError(e); + } + + ArrayList values = new ArrayList(); + + int start = 0; + do { + int nextAmpersand = query.indexOf('&', start); + int end = nextAmpersand != -1 ? nextAmpersand : query.length(); + + int separator = query.indexOf('=', start); + if (separator > end || separator == -1) { + separator = end; + } + + if (separator - start == encodedKey.length() + && query.regionMatches(start, encodedKey, 0, encodedKey.length())) { + if (separator == end) { + values.add(""); + } else { + values.add(decode(query.substring(separator + 1, end))); + } + } + + // Move start to end of name. + if (nextAmpersand != -1) { + start = nextAmpersand + 1; + } else { + break; + } + } while (true); + + return Collections.unmodifiableList(values); + } + + /** + * Searches the query string for the first value with the given key. + * + *

Warning: Prior to Jelly Bean, this decoded + * the '+' character as '+' rather than ' '. + * + * @param key which will be encoded + * @throws UnsupportedOperationException if this isn't a hierarchical URI + * @throws NullPointerException if key is null + * @return the decoded value or null if no parameter is found + */ + public String getQueryParameter(String key) { + if (isOpaque()) { + throw new UnsupportedOperationException(NOT_HIERARCHICAL); + } + if (key == null) { + throw new NullPointerException("key"); + } + + final String query = getEncodedQuery(); + if (query == null) { + return null; + } + + final String encodedKey = encode(key, null); + final int length = query.length(); + int start = 0; + do { + int nextAmpersand = query.indexOf('&', start); + int end = nextAmpersand != -1 ? nextAmpersand : length; + + int separator = query.indexOf('=', start); + if (separator > end || separator == -1) { + separator = end; + } + + if (separator - start == encodedKey.length() + && query.regionMatches(start, encodedKey, 0, encodedKey.length())) { + if (separator == end) { + return ""; + } else { + String encodedValue = query.substring(separator + 1, end); + return UriCodec.decode(encodedValue, true, StandardCharsets.UTF_8, false); + } + } + + // Move start to end of name. + if (nextAmpersand != -1) { + start = nextAmpersand + 1; + } else { + break; + } + } while (true); + return null; + } + + /** + * Searches the query string for the first value with the given key and interprets it + * as a boolean value. "false" and "0" are interpreted as false, everything + * else is interpreted as true. + * + * @param key which will be decoded + * @param defaultValue the default value to return if there is no query parameter for key + * @return the boolean interpretation of the query parameter key + */ + public boolean getBooleanQueryParameter(String key, boolean defaultValue) { + String flag = getQueryParameter(key); + if (flag == null) { + return defaultValue; + } + flag = flag.toLowerCase(Locale.ROOT); + return (!"false".equals(flag) && !"0".equals(flag)); + } + + /** + * Return an equivalent URI with a lowercase scheme component. + * This aligns the Uri with Android best practices for + * intent filtering. + * + *

For example, "HTTP://www.android.com" becomes + * "http://www.android.com" + * + *

All URIs received from outside Android (such as user input, + * or external sources like Bluetooth, NFC, or the Internet) should + * be normalized before they are used to create an Intent. + * + *

This method does not validate bad URI's, + * or 'fix' poorly formatted URI's - so do not use it for input validation. + * A Uri will always be returned, even if the Uri is badly formatted to + * begin with and a scheme component cannot be found. + * + * @return normalized Uri (never null) + * @see android.content.Intent#setData + * @see android.content.Intent#setDataAndNormalize + */ + public Uri normalizeScheme() { + String scheme = getScheme(); + if (scheme == null) return this; // give up + String lowerScheme = scheme.toLowerCase(Locale.ROOT); + if (scheme.equals(lowerScheme)) return this; // no change + + return buildUpon().scheme(lowerScheme).build(); + } + + /** Identifies a null parcelled Uri. */ + private static final int NULL_TYPE_ID = 0; + + private static final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray(); + + /** + * Encodes characters in the given string as '%'-escaped octets + * using the UTF-8 scheme. Leaves letters ("A-Z", "a-z"), numbers + * ("0-9"), and unreserved characters ("_-!.~'()*") intact. Encodes + * all other characters. + * + * @param s string to encode + * @return an encoded version of s suitable for use as a URI component, + * or null if s is null + */ + public static String encode(String s) { + return encode(s, null); + } + + /** + * Encodes characters in the given string as '%'-escaped octets + * using the UTF-8 scheme. Leaves letters ("A-Z", "a-z"), numbers + * ("0-9"), and unreserved characters ("_-!.~'()*") intact. Encodes + * all other characters with the exception of those specified in the + * allow argument. + * + * @param s string to encode + * @param allow set of additional characters to allow in the encoded form, + * null if no characters should be skipped + * @return an encoded version of s suitable for use as a URI component, + * or null if s is null + */ + public static String encode(String s, String allow) { + if (s == null) { + return null; + } + + // Lazily-initialized buffers. + StringBuilder encoded = null; + + int oldLength = s.length(); + + // This loop alternates between copying over allowed characters and + // encoding in chunks. This results in fewer method calls and + // allocations than encoding one character at a time. + int current = 0; + while (current < oldLength) { + // Start in "copying" mode where we copy over allowed chars. + + // Find the next character which needs to be encoded. + int nextToEncode = current; + while (nextToEncode < oldLength + && isAllowed(s.charAt(nextToEncode), allow)) { + nextToEncode++; + } + + // If there's nothing more to encode... + if (nextToEncode == oldLength) { + if (current == 0) { + // We didn't need to encode anything! + return s; + } else { + // Presumably, we've already done some encoding. + encoded.append(s, current, oldLength); + return encoded.toString(); + } + } + + if (encoded == null) { + encoded = new StringBuilder(); + } + + if (nextToEncode > current) { + // Append allowed characters leading up to this point. + encoded.append(s, current, nextToEncode); + } else { + // assert nextToEncode == current + } + + // Switch to "encoding" mode. + + // Find the next allowed character. + current = nextToEncode; + int nextAllowed = current + 1; + while (nextAllowed < oldLength + && !isAllowed(s.charAt(nextAllowed), allow)) { + nextAllowed++; + } + + // Convert the substring to bytes and encode the bytes as + // '%'-escaped octets. + String toEncode = s.substring(current, nextAllowed); + try { + byte[] bytes = toEncode.getBytes(DEFAULT_ENCODING); + int bytesLength = bytes.length; + for (int i = 0; i < bytesLength; i++) { + encoded.append('%'); + encoded.append(HEX_DIGITS[(bytes[i] & 0xf0) >> 4]); + encoded.append(HEX_DIGITS[bytes[i] & 0xf]); + } + } catch (UnsupportedEncodingException e) { + throw new AssertionError(e); + } + + current = nextAllowed; + } + + // Encoded could still be null at this point if s is empty. + return encoded == null ? s : encoded.toString(); + } + + /** + * Returns true if the given character is allowed. + * + * @param c character to check + * @param allow characters to allow + * @return true if the character is allowed or false if it should be + * encoded + */ + private static boolean isAllowed(char c, String allow) { + return (c >= 'A' && c <= 'Z') + || (c >= 'a' && c <= 'z') + || (c >= '0' && c <= '9') + || "_-!.~'()*".indexOf(c) != NOT_FOUND + || (allow != null && allow.indexOf(c) != NOT_FOUND); + } + + /** + * Decodes '%'-escaped octets in the given string using the UTF-8 scheme. + * Replaces invalid octets with the unicode replacement character + * ("\\uFFFD"). + * + * @param s encoded string to decode + * @return the given string with escaped octets decoded, or null if + * s is null + */ + public static String decode(String s) { + if (s == null) { + return null; + } + return UriCodec.decode( + s, false /* convertPlus */, StandardCharsets.UTF_8, false /* throwOnFailure */); + } + + /** + * Support for part implementations. + */ + static abstract class AbstractPart { + + // Possible values of mCanonicalRepresentation. + static final int REPRESENTATION_ENCODED = 1; + static final int REPRESENTATION_DECODED = 2; + + volatile String encoded; + volatile String decoded; + private final int mCanonicalRepresentation; + + AbstractPart(String encoded, String decoded) { + if (encoded != NotCachedHolder.NOT_CACHED) { + this.mCanonicalRepresentation = REPRESENTATION_ENCODED; + this.encoded = encoded; + this.decoded = NotCachedHolder.NOT_CACHED; + } else if (decoded != NotCachedHolder.NOT_CACHED) { + this.mCanonicalRepresentation = REPRESENTATION_DECODED; + this.encoded = NotCachedHolder.NOT_CACHED; + this.decoded = decoded; + } else { + throw new IllegalArgumentException("Neither encoded nor decoded"); + } + } + + abstract String getEncoded(); + + final String getDecoded() { + @SuppressWarnings("StringEquality") + boolean hasDecoded = decoded != NotCachedHolder.NOT_CACHED; + return hasDecoded ? decoded : (decoded = decode(encoded)); + } + } + + /** + * Immutable wrapper of encoded and decoded versions of a URI part. Lazily + * creates the encoded or decoded version from the other. + */ + static class Part extends AbstractPart { + + /** A part with null values. */ + static final Part NULL = new EmptyPart(null); + + /** A part with empty strings for values. */ + static final Part EMPTY = new EmptyPart(""); + + private Part(String encoded, String decoded) { + super(encoded, decoded); + } + + boolean isEmpty() { + return false; + } + + String getEncoded() { + @SuppressWarnings("StringEquality") + boolean hasEncoded = encoded != NotCachedHolder.NOT_CACHED; + return hasEncoded ? encoded : (encoded = encode(decoded)); + } + + /** + * Returns given part or {@link #NULL} if the given part is null. + */ + static Part nonNull(Part part) { + return part == null ? NULL : part; + } + + /** + * Creates a part from the encoded string. + * + * @param encoded part string + */ + static Part fromEncoded(String encoded) { + return from(encoded, NotCachedHolder.NOT_CACHED); + } + + /** + * Creates a part from the decoded string. + * + * @param decoded part string + */ + static Part fromDecoded(String decoded) { + return from(NotCachedHolder.NOT_CACHED, decoded); + } + + /** + * Creates a part from the encoded and decoded strings. + * + * @param encoded part string + * @param decoded part string + */ + static Part from(String encoded, String decoded) { + // We have to check both encoded and decoded in case one is + // NotCachedHolder.NOT_CACHED. + + if (encoded == null) { + return NULL; + } + if (encoded.length() == 0) { + return EMPTY; + } + + if (decoded == null) { + return NULL; + } + if (decoded .length() == 0) { + return EMPTY; + } + + return new Part(encoded, decoded); + } + + private static class EmptyPart extends Part { + public EmptyPart(String value) { + super(value, value); + if (value != null && !value.isEmpty()) { + throw new IllegalArgumentException("Expected empty value, got: " + value); + } + // Avoid having to re-calculate the non-canonical value. + encoded = decoded = value; + } + + @Override + boolean isEmpty() { + return true; + } + } + } + + /** + * Immutable wrapper of encoded and decoded versions of a path part. Lazily + * creates the encoded or decoded version from the other. + */ + static class PathPart extends AbstractPart { + + /** A part with null values. */ + static final PathPart NULL = new PathPart(null, null); + + /** A part with empty strings for values. */ + static final PathPart EMPTY = new PathPart("", ""); + + private PathPart(String encoded, String decoded) { + super(encoded, decoded); + } + + String getEncoded() { + @SuppressWarnings("StringEquality") + boolean hasEncoded = encoded != NotCachedHolder.NOT_CACHED; + + // Don't encode '/'. + return hasEncoded ? encoded : (encoded = encode(decoded, "/")); + } + + /** + * Cached path segments. This doesn't need to be volatile--we don't + * care if other threads see the result. + */ + private PathSegments pathSegments; + + /** + * Gets the individual path segments. Parses them if necessary. + * + * @return parsed path segments or null if this isn't a hierarchical + * URI + */ + PathSegments getPathSegments() { + if (pathSegments != null) { + return pathSegments; + } + + String path = getEncoded(); + if (path == null) { + return pathSegments = PathSegments.EMPTY; + } + + PathSegmentsBuilder segmentBuilder = new PathSegmentsBuilder(); + + int previous = 0; + int current; + while ((current = path.indexOf('/', previous)) > -1) { + // This check keeps us from adding a segment if the path starts + // '/' and an empty segment for "//". + if (previous < current) { + String decodedSegment + = decode(path.substring(previous, current)); + segmentBuilder.add(decodedSegment); + } + previous = current + 1; + } + + // Add in the final path segment. + if (previous < path.length()) { + segmentBuilder.add(decode(path.substring(previous))); + } + + return pathSegments = segmentBuilder.build(); + } + + static PathPart appendEncodedSegment(PathPart oldPart, + String newSegment) { + // If there is no old path, should we make the new path relative + // or absolute? I pick absolute. + + if (oldPart == null) { + // No old path. + return fromEncoded("/" + newSegment); + } + + String oldPath = oldPart.getEncoded(); + + if (oldPath == null) { + oldPath = ""; + } + + int oldPathLength = oldPath.length(); + String newPath; + if (oldPathLength == 0) { + // No old path. + newPath = "/" + newSegment; + } else if (oldPath.charAt(oldPathLength - 1) == '/') { + newPath = oldPath + newSegment; + } else { + newPath = oldPath + "/" + newSegment; + } + + return fromEncoded(newPath); + } + + static PathPart appendDecodedSegment(PathPart oldPart, String decoded) { + String encoded = encode(decoded); + + // TODO: Should we reuse old PathSegments? Probably not. + return appendEncodedSegment(oldPart, encoded); + } + + /** + * Creates a path from the encoded string. + * + * @param encoded part string + */ + static PathPart fromEncoded(String encoded) { + return from(encoded, NotCachedHolder.NOT_CACHED); + } + + /** + * Creates a path from the decoded string. + * + * @param decoded part string + */ + static PathPart fromDecoded(String decoded) { + return from(NotCachedHolder.NOT_CACHED, decoded); + } + + /** + * Creates a path from the encoded and decoded strings. + * + * @param encoded part string + * @param decoded part string + */ + static PathPart from(String encoded, String decoded) { + if (encoded == null) { + return NULL; + } + + if (encoded.length() == 0) { + return EMPTY; + } + + return new PathPart(encoded, decoded); + } + + /** + * Prepends path values with "/" if they're present, not empty, and + * they don't already start with "/". + */ + static PathPart makeAbsolute(PathPart oldPart) { + @SuppressWarnings("StringEquality") + boolean encodedCached = oldPart.encoded != NotCachedHolder.NOT_CACHED; + + // We don't care which version we use, and we don't want to force + // unneccessary encoding/decoding. + String oldPath = encodedCached ? oldPart.encoded : oldPart.decoded; + + if (oldPath == null || oldPath.length() == 0 + || oldPath.startsWith("/")) { + return oldPart; + } + + // Prepend encoded string if present. + String newEncoded = encodedCached + ? "/" + oldPart.encoded : NotCachedHolder.NOT_CACHED; + + // Prepend decoded string if present. + @SuppressWarnings("StringEquality") + boolean decodedCached = oldPart.decoded != NotCachedHolder.NOT_CACHED; + String newDecoded = decodedCached + ? "/" + oldPart.decoded + : NotCachedHolder.NOT_CACHED; + + return new PathPart(newEncoded, newDecoded); + } + } + + /** + * Creates a new Uri by appending an already-encoded path segment to a + * base Uri. + * + * @param baseUri Uri to append path segment to + * @param pathSegment encoded path segment to append + * @return a new Uri based on baseUri with the given segment appended to + * the path + * @throws NullPointerException if baseUri is null + */ + public static Uri withAppendedPath(Uri baseUri, String pathSegment) { + Builder builder = baseUri.buildUpon(); + builder = builder.appendEncodedPath(pathSegment); + return builder.build(); + } + + /** + * If this {@link Uri} is {@code file://}, then resolve and return its + * canonical path. Also fixes legacy emulated storage paths so they are + * usable across user boundaries. Should always be called from the app + * process before sending elsewhere. + * + * @hide + */ + public Uri getCanonicalUri() { + if ("file".equals(getScheme())) { + final String canonicalPath; + try { + canonicalPath = new File(getPath()).getCanonicalPath(); + } catch (IOException e) { + return this; + } + + return Uri.fromFile(new File(canonicalPath)); + } else { + return this; + } + } + + /** + * Test if this is a path prefix match against the given Uri. Verifies that + * scheme, authority, and atomic path segments match. + * + * @hide + */ + public boolean isPathPrefixMatch(Uri prefix) { + if (!Objects.equals(getScheme(), prefix.getScheme())) return false; + if (!Objects.equals(getAuthority(), prefix.getAuthority())) return false; + + List seg = getPathSegments(); + List prefixSeg = prefix.getPathSegments(); + + final int prefixSize = prefixSeg.size(); + if (seg.size() < prefixSize) return false; + + for (int i = 0; i < prefixSize; i++) { + if (!Objects.equals(seg.get(i), prefixSeg.get(i))) { + return false; + } + } + + return true; + } +} diff --git a/tests/04. integration tests/01. URL encoder/lib/android/net/UriCodec.java b/tests/04. integration tests/01. URL encoder/lib/android/net/UriCodec.java new file mode 100644 index 0000000..8a792a8 --- /dev/null +++ b/tests/04. integration tests/01. URL encoder/lib/android/net/UriCodec.java @@ -0,0 +1,182 @@ +/* ============ + * copied from: + * https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/net/UriCodec.java + * ============ + */ + +/* + * Copyright (C) 2015 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.net; + +import java.net.URISyntaxException; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.Charset; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CodingErrorAction; + +/** + * Decodes “application/x-www-form-urlencoded” content. + * + * @hide + */ +public final class UriCodec { + + private UriCodec() {} + + /** + * Interprets a char as hex digits, returning a number from -1 (invalid char) to 15 ('f'). + */ + private static int hexCharToValue(char c) { + if ('0' <= c && c <= '9') { + return c - '0'; + } + if ('a' <= c && c <= 'f') { + return 10 + c - 'a'; + } + if ('A' <= c && c <= 'F') { + return 10 + c - 'A'; + } + return -1; + } + + private static URISyntaxException unexpectedCharacterException( + String uri, String name, char unexpected, int index) { + String nameString = (name == null) ? "" : " in [" + name + "]"; + return new URISyntaxException( + uri, "Unexpected character" + nameString + ": " + unexpected, index); + } + + private static char getNextCharacter(String uri, int index, int end, String name) + throws URISyntaxException { + if (index >= end) { + String nameString = (name == null) ? "" : " in [" + name + "]"; + throw new URISyntaxException( + uri, "Unexpected end of string" + nameString, index); + } + return uri.charAt(index); + } + + /** + * Decode a string according to the rules of this decoder. + * + * - if {@code convertPlus == true} all ‘+’ chars in the decoded output are converted to ‘ ‘ + * (white space) + * - if {@code throwOnFailure == true}, an {@link IllegalArgumentException} is thrown for + * invalid inputs. Else, U+FFFd is emitted to the output in place of invalid input octets. + */ + public static String decode( + String s, boolean convertPlus, Charset charset, boolean throwOnFailure) { + StringBuilder builder = new StringBuilder(s.length()); + appendDecoded(builder, s, convertPlus, charset, throwOnFailure); + return builder.toString(); + } + + /** + * Character to be output when there's an error decoding an input. + */ + private static final char INVALID_INPUT_CHARACTER = '\ufffd'; + + private static void appendDecoded( + StringBuilder builder, + String s, + boolean convertPlus, + Charset charset, + boolean throwOnFailure) { + CharsetDecoder decoder = charset.newDecoder() + .onMalformedInput(CodingErrorAction.REPLACE) + .replaceWith("\ufffd") + .onUnmappableCharacter(CodingErrorAction.REPORT); + // Holds the bytes corresponding to the escaped chars being read (empty if the last char + // wasn't a escaped char). + ByteBuffer byteBuffer = ByteBuffer.allocate(s.length()); + int i = 0; + while (i < s.length()) { + char c = s.charAt(i); + i++; + switch (c) { + case '+': + flushDecodingByteAccumulator( + builder, decoder, byteBuffer, throwOnFailure); + builder.append(convertPlus ? ' ' : '+'); + break; + case '%': + // Expect two characters representing a number in hex. + byte hexValue = 0; + for (int j = 0; j < 2; j++) { + try { + c = getNextCharacter(s, i, s.length(), null /* name */); + } catch (URISyntaxException e) { + // Unexpected end of input. + if (throwOnFailure) { + throw new IllegalArgumentException(e); + } else { + flushDecodingByteAccumulator( + builder, decoder, byteBuffer, throwOnFailure); + builder.append(INVALID_INPUT_CHARACTER); + return; + } + } + i++; + int newDigit = hexCharToValue(c); + if (newDigit < 0) { + if (throwOnFailure) { + throw new IllegalArgumentException( + unexpectedCharacterException(s, null /* name */, c, i - 1)); + } else { + flushDecodingByteAccumulator( + builder, decoder, byteBuffer, throwOnFailure); + builder.append(INVALID_INPUT_CHARACTER); + break; + } + } + hexValue = (byte) (hexValue * 0x10 + newDigit); + } + byteBuffer.put(hexValue); + break; + default: + flushDecodingByteAccumulator(builder, decoder, byteBuffer, throwOnFailure); + builder.append(c); + } + } + flushDecodingByteAccumulator(builder, decoder, byteBuffer, throwOnFailure); + } + + private static void flushDecodingByteAccumulator( + StringBuilder builder, + CharsetDecoder decoder, + ByteBuffer byteBuffer, + boolean throwOnFailure) { + if (byteBuffer.position() == 0) { + return; + } + byteBuffer.flip(); + try { + builder.append(decoder.decode(byteBuffer)); + } catch (CharacterCodingException e) { + if (throwOnFailure) { + throw new IllegalArgumentException(e); + } else { + builder.append(INVALID_INPUT_CHARACTER); + } + } finally { + // Use the byte buffer to write again. + byteBuffer.flip(); + byteBuffer.limit(byteBuffer.capacity()); + } + } +} diff --git a/tests/04. integration tests/01. URL encoder/out/1-compile/Main.class b/tests/04. integration tests/01. URL encoder/out/1-compile/Main.class new file mode 100644 index 0000000..c6ee756 Binary files /dev/null and b/tests/04. integration tests/01. URL encoder/out/1-compile/Main.class differ diff --git a/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$AbstractHierarchicalUri.class b/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$AbstractHierarchicalUri.class new file mode 100644 index 0000000..459fd89 Binary files /dev/null and b/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$AbstractHierarchicalUri.class differ diff --git a/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$AbstractPart.class b/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$AbstractPart.class new file mode 100644 index 0000000..27aabde Binary files /dev/null and b/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$AbstractPart.class differ diff --git a/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$Builder.class b/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$Builder.class new file mode 100644 index 0000000..dfffc91 Binary files /dev/null and b/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$Builder.class differ diff --git a/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$HierarchicalUri.class b/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$HierarchicalUri.class new file mode 100644 index 0000000..eb43d9c Binary files /dev/null and b/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$HierarchicalUri.class differ diff --git a/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$NotCachedHolder.class b/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$NotCachedHolder.class new file mode 100644 index 0000000..243c7af Binary files /dev/null and b/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$NotCachedHolder.class differ diff --git a/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$OpaqueUri.class b/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$OpaqueUri.class new file mode 100644 index 0000000..993907c Binary files /dev/null and b/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$OpaqueUri.class differ diff --git a/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$Part$EmptyPart.class b/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$Part$EmptyPart.class new file mode 100644 index 0000000..c0ebf0f Binary files /dev/null and b/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$Part$EmptyPart.class differ diff --git a/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$Part.class b/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$Part.class new file mode 100644 index 0000000..137e039 Binary files /dev/null and b/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$Part.class differ diff --git a/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$PathPart.class b/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$PathPart.class new file mode 100644 index 0000000..7d54eea Binary files /dev/null and b/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$PathPart.class differ diff --git a/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$PathSegments.class b/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$PathSegments.class new file mode 100644 index 0000000..593162e Binary files /dev/null and b/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$PathSegments.class differ diff --git a/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$PathSegmentsBuilder.class b/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$PathSegmentsBuilder.class new file mode 100644 index 0000000..303df1b Binary files /dev/null and b/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$PathSegmentsBuilder.class differ diff --git a/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$StringUri.class b/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$StringUri.class new file mode 100644 index 0000000..84053e6 Binary files /dev/null and b/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri$StringUri.class differ diff --git a/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri.class b/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri.class new file mode 100644 index 0000000..c238eab Binary files /dev/null and b/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/Uri.class differ diff --git a/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/UriCodec.class b/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/UriCodec.class new file mode 100644 index 0000000..f37dc70 Binary files /dev/null and b/tests/04. integration tests/01. URL encoder/out/1-compile/android/net/UriCodec.class differ diff --git a/tests/04. integration tests/01. URL encoder/out/1-compile/com/github/warren_bank/exoplayer_airplay_receiver/utils/UriUtils.class b/tests/04. integration tests/01. URL encoder/out/1-compile/com/github/warren_bank/exoplayer_airplay_receiver/utils/UriUtils.class new file mode 100644 index 0000000..d5be09a Binary files /dev/null and b/tests/04. integration tests/01. URL encoder/out/1-compile/com/github/warren_bank/exoplayer_airplay_receiver/utils/UriUtils.class differ diff --git a/tests/04. integration tests/01. URL encoder/out/2-run/stderr.txt b/tests/04. integration tests/01. URL encoder/out/2-run/stderr.txt new file mode 100644 index 0000000..e69de29 diff --git a/tests/04. integration tests/01. URL encoder/out/2-run/stdout.txt b/tests/04. integration tests/01. URL encoder/out/2-run/stdout.txt new file mode 100644 index 0000000..f5d0f23 --- /dev/null +++ b/tests/04. integration tests/01. URL encoder/out/2-run/stdout.txt @@ -0,0 +1,10 @@ + +---------------------------------------- + +[subject] url: http://a%3Ab:pass@example.com:80/foo[bar].baz?hash=%26%2f#skip +[test_001] encoded: http://a%3Ab:pass@example.com:80/foo%5Bbar%5D.baz?hash=%26%2f#skip + +---------------------------------------- + +[subject] url: http://a%3Ab:pass@example.com:80/foo%5Bbar%5D.baz?hash=%26%2f#skip +[test_001] encoded: http://a%3Ab:pass@example.com:80/foo%5Bbar%5D.baz?hash=%26%2f#skip diff --git a/tests/04. integration tests/01. URL encoder/src/Main.java b/tests/04. integration tests/01. URL encoder/src/Main.java new file mode 100644 index 0000000..3e1d16f --- /dev/null +++ b/tests/04. integration tests/01. URL encoder/src/Main.java @@ -0,0 +1,26 @@ +import com.github.warren_bank.exoplayer_airplay_receiver.utils.UriUtils; + +public class Main { + public static void run_test_001(String url_0, String TAG) { + try { + String url_1 = UriUtils.encodeURI(url_0); + + System.out.println(TAG + "encoded: " + url_1); + } + catch(Exception e) { + System.out.println(TAG + "ERROR: " + e.getMessage()); + } + } + + public static void run_tests(String url) { + System.out.println("\n" + "----------------------------------------" + "\n"); + System.out.println("[subject] url: " + url); + + run_test_001(url, "[test_001] "); + } + + public static void main(String args[]) { + run_tests("http://a%3Ab:pass@example.com:80/foo[bar].baz?hash=%26%2f#skip"); + run_tests("http://a%3Ab:pass@example.com:80/foo%5Bbar%5D.baz?hash=%26%2f#skip"); + } +} diff --git a/tests/.captions/counter.srt b/tests/05. issues/ExoPlayer/7122/.captions/counter.srt similarity index 100% rename from tests/.captions/counter.srt rename to tests/05. issues/ExoPlayer/7122/.captions/counter.srt diff --git a/tests/.captions/counter.vtt b/tests/05. issues/ExoPlayer/7122/.captions/counter.vtt similarity index 100% rename from tests/.captions/counter.vtt rename to tests/05. issues/ExoPlayer/7122/.captions/counter.vtt diff --git a/tests/.captions/counter.workaround-exoplayer-issue-7122.srt b/tests/05. issues/ExoPlayer/7122/.captions/counter.workaround-exoplayer-issue-7122.srt similarity index 100% rename from tests/.captions/counter.workaround-exoplayer-issue-7122.srt rename to tests/05. issues/ExoPlayer/7122/.captions/counter.workaround-exoplayer-issue-7122.srt diff --git a/tests/05. issues/ExoPlayer/7122/README.md b/tests/05. issues/ExoPlayer/7122/README.md new file mode 100644 index 0000000..eae3156 --- /dev/null +++ b/tests/05. issues/ExoPlayer/7122/README.md @@ -0,0 +1,166 @@ +[issue 7122](https://github.com/google/ExoPlayer/issues/7122) + +- - - - + +* in [SubripDecoder](https://github.com/google/ExoPlayer/blob/r2.11.3/library/core/src/main/java/com/google/android/exoplayer2/text/subrip/SubripDecoder.java) + - correctly: the regex [`SUBRIP_TIMECODE`](https://github.com/google/ExoPlayer/blob/r2.11.3/library/core/src/main/java/com/google/android/exoplayer2/text/subrip/SubripDecoder.java#L44) makes this field optional + - incorrectly: the function [`parseTimecode`](https://github.com/google/ExoPlayer/blob/r2.11.3/library/core/src/main/java/com/google/android/exoplayer2/text/subrip/SubripDecoder.java#L232) blindly assumes this field contains a non-null String value that can be parsed to a `Long` + +__minimal code to reproduces the problem:__ + +```java +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +class Main { + public static void main(String[] args) { + run_test("00:00,000 --> 00:01,000"); + } + + private static final String SUBRIP_TIMECODE = "(?:(\\d+):)?(\\d+):(\\d+),(\\d+)"; + private static final Pattern SUBRIP_TIMING_LINE = Pattern.compile("\\s*(" + SUBRIP_TIMECODE + ")\\s*-->\\s*(" + SUBRIP_TIMECODE + ")\\s*"); + + private static void run_test(String currentLine) { + Matcher matcher = SUBRIP_TIMING_LINE.matcher(currentLine); + if (matcher.matches()) { + long start = parseTimecode(matcher, /* groupOffset= */ 1); + long end = parseTimecode(matcher, /* groupOffset= */ 6); + + System.out.println("start: " + start); + System.out.println("end: " + end); + } + else { + System.out.println("no match"); + } + } + + private static long parseTimecode(Matcher matcher, int groupOffset) { + long timestampMs = Long.parseLong(matcher.group(groupOffset + 1)) * 60 * 60 * 1000; + timestampMs += Long.parseLong(matcher.group(groupOffset + 2)) * 60 * 1000; + timestampMs += Long.parseLong(matcher.group(groupOffset + 3)) * 1000; + timestampMs += Long.parseLong(matcher.group(groupOffset + 4)); + return timestampMs * 1000; + } +} +``` + +_output (stderr):_ + +```text +java.lang.NumberFormatException: null + at java.base/java.lang.Long.parseLong +``` + +__fixed:__ + +```java + private static long parseTimecode(Matcher matcher, int groupOffset) { + long timestampMs = 0; + String groupVal; + + // HOURS field is optional + groupVal = matcher.group(groupOffset + 1); + if (groupVal != null) + timestampMs += Long.parseLong(groupVal) * 60 * 60 * 1000; + + // MINUTES field is required + groupVal = matcher.group(groupOffset + 2); + if (groupVal != null) + timestampMs += Long.parseLong(groupVal) * 60 * 1000; + + // SECONDS field is required + groupVal = matcher.group(groupOffset + 3); + if (groupVal != null) + timestampMs += Long.parseLong(groupVal) * 1000; + + // MILLISECONDS field is required + groupVal = matcher.group(groupOffset + 4); + if (groupVal != null) + timestampMs += Long.parseLong(groupVal); + + // convert timecode from MILLISECONDS to MICROSECONDS + return timestampMs * 1000; + } +``` + +_output (stdout):_ + +```text +start: 0 +end: 1000000 +``` + +- - - - + +[__full example:__](https://repl.it/@WarrenBank/ExoPlayer-SubripDecoder) + +```java +// https://repl.it/@WarrenBank/ExoPlayer-SubripDecoder + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +class Main { + public static void main(String[] args) { + run_test("00:00:00,000 --> 00:00:01,000"); + run_test(" 00:00,000 --> 00:01,000"); + run_test(" 00:00 --> 00:01 "); + } + + private static final String SUBRIP_TIMECODE = "(?:(\\d+):)?(\\d+):(\\d+)(?:,(\\d+))?"; + private static final Pattern SUBRIP_TIMING_LINE = Pattern.compile("\\s*(" + SUBRIP_TIMECODE + ")\\s*-->\\s*(" + SUBRIP_TIMECODE + ")\\s*"); + + private static void run_test(String currentLine) { + Matcher matcher = SUBRIP_TIMING_LINE.matcher(currentLine); + if (matcher.matches()) { + long start = parseTimecode(matcher, /* groupOffset= */ 1); + long end = parseTimecode(matcher, /* groupOffset= */ 6); + + System.out.println("start: " + start); + System.out.println("end: " + end); + } + else { + System.out.println("no match"); + } + } + + private static long parseTimecode(Matcher matcher, int groupOffset) { + long timestampMs = 0; + String groupVal; + + // HOURS field is optional + groupVal = matcher.group(groupOffset + 1); + if (groupVal != null) + timestampMs += Long.parseLong(groupVal) * 60 * 60 * 1000; + + // MINUTES field is required + groupVal = matcher.group(groupOffset + 2); + if (groupVal != null) + timestampMs += Long.parseLong(groupVal) * 60 * 1000; + + // SECONDS field is required + groupVal = matcher.group(groupOffset + 3); + if (groupVal != null) + timestampMs += Long.parseLong(groupVal) * 1000; + + // MILLISECONDS field is optional + groupVal = matcher.group(groupOffset + 4); + if (groupVal != null) + timestampMs += Long.parseLong(groupVal); + + // convert timecode from MILLISECONDS to MICROSECONDS + return timestampMs * 1000; + } +} +``` + +_output (stdout):_ + +```text +start: 0 +end: 1000000 +start: 0 +end: 1000000 +start: 0 +end: 1000000 +```