Home | History | Annotate | Download | only in content
      1 /*
      2  * Copyright (C) 2006 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 android.content;
     18 
     19 import android.annotation.UnsupportedAppUsage;
     20 import android.net.Uri;
     21 
     22 import java.util.ArrayList;
     23 import java.util.List;
     24 
     25 /**
     26 Utility class to aid in matching URIs in content providers.
     27 
     28 <p>To use this class, build up a tree of <code>UriMatcher</code> objects.
     29 For example:
     30 <pre>
     31     private static final int PEOPLE = 1;
     32     private static final int PEOPLE_ID = 2;
     33     private static final int PEOPLE_PHONES = 3;
     34     private static final int PEOPLE_PHONES_ID = 4;
     35     private static final int PEOPLE_CONTACTMETHODS = 7;
     36     private static final int PEOPLE_CONTACTMETHODS_ID = 8;
     37 
     38     private static final int DELETED_PEOPLE = 20;
     39 
     40     private static final int PHONES = 9;
     41     private static final int PHONES_ID = 10;
     42     private static final int PHONES_FILTER = 14;
     43 
     44     private static final int CONTACTMETHODS = 18;
     45     private static final int CONTACTMETHODS_ID = 19;
     46 
     47     private static final int CALLS = 11;
     48     private static final int CALLS_ID = 12;
     49     private static final int CALLS_FILTER = 15;
     50 
     51     private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
     52 
     53     static
     54     {
     55         sURIMatcher.addURI("contacts", "people", PEOPLE);
     56         sURIMatcher.addURI("contacts", "people/#", PEOPLE_ID);
     57         sURIMatcher.addURI("contacts", "people/#/phones", PEOPLE_PHONES);
     58         sURIMatcher.addURI("contacts", "people/#/phones/#", PEOPLE_PHONES_ID);
     59         sURIMatcher.addURI("contacts", "people/#/contact_methods", PEOPLE_CONTACTMETHODS);
     60         sURIMatcher.addURI("contacts", "people/#/contact_methods/#", PEOPLE_CONTACTMETHODS_ID);
     61         sURIMatcher.addURI("contacts", "deleted_people", DELETED_PEOPLE);
     62         sURIMatcher.addURI("contacts", "phones", PHONES);
     63         sURIMatcher.addURI("contacts", "phones/filter/*", PHONES_FILTER);
     64         sURIMatcher.addURI("contacts", "phones/#", PHONES_ID);
     65         sURIMatcher.addURI("contacts", "contact_methods", CONTACTMETHODS);
     66         sURIMatcher.addURI("contacts", "contact_methods/#", CONTACTMETHODS_ID);
     67         sURIMatcher.addURI("call_log", "calls", CALLS);
     68         sURIMatcher.addURI("call_log", "calls/filter/*", CALLS_FILTER);
     69         sURIMatcher.addURI("call_log", "calls/#", CALLS_ID);
     70     }
     71 </pre>
     72 <p>Starting from API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, paths can start
     73  with a leading slash.  For example:
     74 <pre>
     75         sURIMatcher.addURI("contacts", "/people", PEOPLE);
     76 </pre>
     77 <p>Then when you need to match against a URI, call {@link #match}, providing
     78 the URL that you have been given.  You can use the result to build a query,
     79 return a type, insert or delete a row, or whatever you need, without duplicating
     80 all of the if-else logic that you would otherwise need.  For example:
     81 <pre>
     82     public String getType(Uri url)
     83     {
     84         int match = sURIMatcher.match(url);
     85         switch (match)
     86         {
     87             case PEOPLE:
     88                 return "vnd.android.cursor.dir/person";
     89             case PEOPLE_ID:
     90                 return "vnd.android.cursor.item/person";
     91 ... snip ...
     92                 return "vnd.android.cursor.dir/snail-mail";
     93             case PEOPLE_ADDRESS_ID:
     94                 return "vnd.android.cursor.item/snail-mail";
     95             default:
     96                 return null;
     97         }
     98     }
     99 </pre>
    100 instead of:
    101 <pre>
    102     public String getType(Uri url)
    103     {
    104         List<String> pathSegments = url.getPathSegments();
    105         if (pathSegments.size() >= 2) {
    106             if ("people".equals(pathSegments.get(1))) {
    107                 if (pathSegments.size() == 2) {
    108                     return "vnd.android.cursor.dir/person";
    109                 } else if (pathSegments.size() == 3) {
    110                     return "vnd.android.cursor.item/person";
    111 ... snip ...
    112                     return "vnd.android.cursor.dir/snail-mail";
    113                 } else if (pathSegments.size() == 3) {
    114                     return "vnd.android.cursor.item/snail-mail";
    115                 }
    116             }
    117         }
    118         return null;
    119     }
    120 </pre>
    121 */
    122 public class UriMatcher
    123 {
    124     public static final int NO_MATCH = -1;
    125     /**
    126      * Creates the root node of the URI tree.
    127      *
    128      * @param code the code to match for the root URI
    129      */
    130     public UriMatcher(int code)
    131     {
    132         mCode = code;
    133         mWhich = -1;
    134         mChildren = new ArrayList<UriMatcher>();
    135         mText = null;
    136     }
    137 
    138     private UriMatcher(int which, String text)
    139     {
    140         mCode = NO_MATCH;
    141         mWhich = which;
    142         mChildren = new ArrayList<UriMatcher>();
    143         mText = text;
    144     }
    145 
    146     /**
    147      * Add a URI to match, and the code to return when this URI is
    148      * matched. URI nodes may be exact match string, the token "*"
    149      * that matches any text, or the token "#" that matches only
    150      * numbers.
    151      * <p>
    152      * Starting from API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
    153      * this method will accept a leading slash in the path.
    154      *
    155      * @param authority the authority to match
    156      * @param path the path to match. * may be used as a wild card for
    157      * any text, and # may be used as a wild card for numbers.
    158      * @param code the code that is returned when a URI is matched
    159      * against the given components. Must be positive.
    160      */
    161     public void addURI(String authority, String path, int code)
    162     {
    163         if (code < 0) {
    164             throw new IllegalArgumentException("code " + code + " is invalid: it must be positive");
    165         }
    166 
    167         String[] tokens = null;
    168         if (path != null) {
    169             String newPath = path;
    170             // Strip leading slash if present.
    171             if (path.length() > 1 && path.charAt(0) == '/') {
    172                 newPath = path.substring(1);
    173             }
    174             tokens = newPath.split("/");
    175         }
    176 
    177         int numTokens = tokens != null ? tokens.length : 0;
    178         UriMatcher node = this;
    179         for (int i = -1; i < numTokens; i++) {
    180             String token = i < 0 ? authority : tokens[i];
    181             ArrayList<UriMatcher> children = node.mChildren;
    182             int numChildren = children.size();
    183             UriMatcher child;
    184             int j;
    185             for (j = 0; j < numChildren; j++) {
    186                 child = children.get(j);
    187                 if (token.equals(child.mText)) {
    188                     node = child;
    189                     break;
    190                 }
    191             }
    192             if (j == numChildren) {
    193                 // Child not found, create it
    194                 child = createChild(token);
    195                 node.mChildren.add(child);
    196                 node = child;
    197             }
    198         }
    199         node.mCode = code;
    200     }
    201 
    202     private static UriMatcher createChild(String token) {
    203         switch (token) {
    204             case "#":
    205                 return new UriMatcher(NUMBER, "#");
    206             case "*":
    207                 return new UriMatcher(TEXT, "*");
    208             default:
    209                 return new UriMatcher(EXACT, token);
    210         }
    211     }
    212 
    213     /**
    214      * Try to match against the path in a url.
    215      *
    216      * @param uri       The url whose path we will match against.
    217      *
    218      * @return  The code for the matched node (added using addURI),
    219      * or -1 if there is no matched node.
    220      */
    221     public int match(Uri uri)
    222     {
    223         final List<String> pathSegments = uri.getPathSegments();
    224         final int li = pathSegments.size();
    225 
    226         UriMatcher node = this;
    227 
    228         if (li == 0 && uri.getAuthority() == null) {
    229             return this.mCode;
    230         }
    231 
    232         for (int i=-1; i<li; i++) {
    233             String u = i < 0 ? uri.getAuthority() : pathSegments.get(i);
    234             ArrayList<UriMatcher> list = node.mChildren;
    235             if (list == null) {
    236                 break;
    237             }
    238             node = null;
    239             int lj = list.size();
    240             for (int j=0; j<lj; j++) {
    241                 UriMatcher n = list.get(j);
    242           which_switch:
    243                 switch (n.mWhich) {
    244                     case EXACT:
    245                         if (n.mText.equals(u)) {
    246                             node = n;
    247                         }
    248                         break;
    249                     case NUMBER:
    250                         int lk = u.length();
    251                         for (int k=0; k<lk; k++) {
    252                             char c = u.charAt(k);
    253                             if (c < '0' || c > '9') {
    254                                 break which_switch;
    255                             }
    256                         }
    257                         node = n;
    258                         break;
    259                     case TEXT:
    260                         node = n;
    261                         break;
    262                 }
    263                 if (node != null) {
    264                     break;
    265                 }
    266             }
    267             if (node == null) {
    268                 return NO_MATCH;
    269             }
    270         }
    271 
    272         return node.mCode;
    273     }
    274 
    275     private static final int EXACT = 0;
    276     private static final int NUMBER = 1;
    277     private static final int TEXT = 2;
    278 
    279     private int mCode;
    280     private final int mWhich;
    281     @UnsupportedAppUsage
    282     private final String mText;
    283     @UnsupportedAppUsage
    284     private ArrayList<UriMatcher> mChildren;
    285 }
    286