1 /* 2 * Copyright (C) 2017 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package androidx.navigation; 18 19 import android.net.Uri; 20 import android.os.Bundle; 21 import android.support.annotation.NonNull; 22 import android.support.annotation.Nullable; 23 24 import java.util.ArrayList; 25 import java.util.regex.Matcher; 26 import java.util.regex.Pattern; 27 28 /** 29 * NavDeepLink encapsulates the parsing and matching of a navigation deep link. 30 */ 31 class NavDeepLink { 32 private static final Pattern SCHEME_PATTERN = Pattern.compile("^(\\w+-)*\\w+:"); 33 34 private final ArrayList<String> mArguments = new ArrayList<>(); 35 private final Pattern mPattern; 36 37 /** 38 * NavDestinations should be created via {@link Navigator#createDestination}. 39 */ 40 NavDeepLink(@NonNull String uri) { 41 StringBuffer uriRegex = new StringBuffer("^"); 42 43 if (!SCHEME_PATTERN.matcher(uri).find()) { 44 uriRegex.append("http[s]?://"); 45 } 46 Pattern fillInPattern = Pattern.compile("\\{(.+?)\\}"); 47 Matcher matcher = fillInPattern.matcher(uri); 48 while (matcher.find()) { 49 String argName = matcher.group(1); 50 mArguments.add(argName); 51 matcher.appendReplacement(uriRegex, ""); 52 uriRegex.append("(.+?)"); 53 } 54 matcher.appendTail(uriRegex); 55 mPattern = Pattern.compile(uriRegex.toString()); 56 } 57 58 boolean matches(@NonNull Uri deepLink) { 59 return mPattern.matcher(deepLink.toString()).matches(); 60 } 61 62 @Nullable 63 Bundle getMatchingArguments(@NonNull Uri deepLink) { 64 Matcher matcher = mPattern.matcher(deepLink.toString()); 65 if (!matcher.matches()) { 66 return null; 67 } 68 Bundle bundle = new Bundle(); 69 int size = mArguments.size(); 70 for (int index = 0; index < size; index++) { 71 String argument = mArguments.get(index); 72 bundle.putString(argument, Uri.decode(matcher.group(index + 1))); 73 } 74 return bundle; 75 } 76 } 77