View Javadoc
1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  
28  package org.apache.hc.core5.http.protocol;
29  
30  import java.util.HashMap;
31  import java.util.HashSet;
32  import java.util.Map;
33  import java.util.Map.Entry;
34  import java.util.Set;
35  
36  import org.apache.hc.core5.annotation.Contract;
37  import org.apache.hc.core5.annotation.ThreadingBehavior;
38  import org.apache.hc.core5.util.Args;
39  
40  /**
41   * Maintains a map of objects keyed by a request URI pattern. <br>
42   * Patterns may have three formats:
43   * <ul>
44   * <li>{@code *}</li>
45   * <li>{@code *<uri>}</li>
46   * <li>{@code <uri>*}</li>
47   * </ul>
48   * <br>
49   * This class can be used to resolve an object matching a particular request URI.
50   *
51   * @param <T> The type of registered objects.
52   * @since 4.0
53   */
54  @Contract(threading = ThreadingBehavior.SAFE)
55  public class UriPatternMatcher<T> implements LookupRegistry<T> {
56  
57      private final Map<String, T> map;
58  
59      public UriPatternMatcher() {
60          super();
61          this.map = new HashMap<>();
62      }
63  
64      /**
65       * Returns a {@link Set} view of the mappings contained in this matcher.
66       *
67       * @return  a set view of the mappings contained in this matcher.
68       *
69       * @see Map#entrySet()
70       * @since 4.4.9
71       */
72      public synchronized Set<Entry<String, T>> entrySet() {
73          return new HashSet<>(map.entrySet());
74      }
75  
76      /**
77       * Registers the given object for URIs matching the given pattern.
78       *
79       * @param pattern
80       *            the pattern to register the handler for.
81       * @param obj
82       *            the object.
83       */
84      @Override
85      public synchronized void register(final String pattern, final T obj) {
86          Args.notNull(pattern, "URI request pattern");
87          this.map.put(pattern, obj);
88      }
89  
90      /**
91       * Removes registered object, if exists, for the given pattern.
92       *
93       * @param pattern
94       *            the pattern to unregister.
95       */
96      @Override
97      public synchronized void unregister(final String pattern) {
98          if (pattern == null) {
99              return;
100         }
101         this.map.remove(pattern);
102     }
103 
104     /**
105      * Looks up an object matching the given request path.
106      *
107      * @param path
108      *            the request path
109      * @return object or {@code null} if no match is found.
110      */
111     @Override
112     public synchronized T lookup(final String path) {
113         Args.notNull(path, "Request path");
114         // direct match?
115         T obj = this.map.get(path);
116         if (obj == null) {
117             // pattern match?
118             String bestMatch = null;
119             for (final String pattern : this.map.keySet()) {
120                 if (matchUriRequestPattern(pattern, path)) {
121                     // we have a match. is it any better?
122                     if (bestMatch == null || (bestMatch.length() < pattern.length())
123                             || (bestMatch.length() == pattern.length() && pattern.endsWith("*"))) {
124                         obj = this.map.get(pattern);
125                         bestMatch = pattern;
126                     }
127                 }
128             }
129         }
130         return obj;
131     }
132 
133     /**
134      * Tests if the given request path matches the given pattern.
135      *
136      * @param pattern
137      *            the pattern
138      * @param path
139      *            the request path
140      * @return {@code true} if the request URI matches the pattern, {@code false} otherwise.
141      */
142     protected boolean matchUriRequestPattern(final String pattern, final String path) {
143         if (pattern.equals("*")) {
144             return true;
145         }
146         return (pattern.endsWith("*") && path.startsWith(pattern.substring(0, pattern.length() - 1)))
147                 || (pattern.startsWith("*") && path.endsWith(pattern.substring(1, pattern.length())));
148     }
149 
150     @Override
151     public String toString() {
152         return this.map.toString();
153     }
154 
155 }