FileDocCategorySizeDatePackage
UrlQuerySanitizer.javaAPI DocAndroid 1.5 API31293Wed May 06 22:41:54 BST 2009android.net

UrlQuerySanitizer

public class UrlQuerySanitizer extends Object
Sanitizes the Query portion of a URL. Simple example: UrlQuerySanitizer sanitizer = new UrlQuerySanitizer(); sanitizer.setAllowUnregisteredParamaters(true); sanitizer.parseUrl("http://example.com/?name=Joe+User"); String name = sanitizer.getValue("name")); // name now contains "Joe_User" Register ValueSanitizers to customize the way individual parameters are sanitized: UrlQuerySanitizer sanitizer = new UrlQuerySanitizer(); sanitizer.registerParamater("name", UrlQuerySanitizer.createSpaceLegal()); sanitizer.parseUrl("http://example.com/?name=Joe+User"); String name = sanitizer.getValue("name")); // name now contains "Joe User". (The string is first decoded, which // converts the '+' to a ' '. Then the string is sanitized, which // converts the ' ' to an '_'. (The ' ' is converted because the default unregistered parameter sanitizer does not allow any special characters, and ' ' is a special character.) There are several ways to create ValueSanitizers. In order of increasing sophistication:
  1. Call one of the UrlQuerySanitizer.createXXX() methods.
  2. Construct your own instance of UrlQuerySanitizer.IllegalCharacterValueSanitizer.
  3. Subclass UrlQuerySanitizer.ValueSanitizer to define your own value sanitizer.

Fields Summary
private final HashMap
mSanitizers
private final HashMap
mEntries
private final ArrayList
mEntriesList
private boolean
mAllowUnregisteredParamaters
private boolean
mPreferFirstRepeatedParameter
private ValueSanitizer
mUnregisteredParameterValueSanitizer
private static final ValueSanitizer
sAllIllegal
private static final ValueSanitizer
sAllButNulLegal
private static final ValueSanitizer
sAllButWhitespaceLegal
private static final ValueSanitizer
sURLLegal
private static final ValueSanitizer
sUrlAndSpaceLegal
private static final ValueSanitizer
sAmpLegal
private static final ValueSanitizer
sAmpAndSpaceLegal
private static final ValueSanitizer
sSpaceLegal
private static final ValueSanitizer
sAllButNulAndAngleBracketsLegal
Constructors Summary
public UrlQuerySanitizer()
Constructs a UrlQuerySanitizer.

Defaults:

  • unregistered parameters are not allowed.
  • the last instance of a repeated parameter is preferred.
  • The default value sanitizer is an AllIllegal value sanitizer.

          
public UrlQuerySanitizer(String url)
Constructs a UrlQuerySanitizer and parse a URL. This constructor is provided for convenience when the default parsing behavior is acceptable.

Because the URL is parsed before the constructor returns, there isn't a chance to configure the sanitizer to change the parsing behavior.

UrlQuerySanitizer sanitizer = new UrlQuerySanitizer(myUrl); String name = sanitizer.getValue("name");

Defaults:

  • unregistered parameters are allowed.
  • the last instance of a repeated parameter is preferred.
  • The default value sanitizer is an AllIllegal value sanitizer.

              setAllowUnregisteredParamaters(true);
              parseUrl(url);
          
Methods Summary
protected voidaddSanitizedEntry(java.lang.String parameter, java.lang.String value)
Record a sanitized parameter-value pair. Override if you want to do additional filtering or validation.

param
parameter an unescaped parameter
param
value a sanitized unescaped value

        mEntriesList.add(
                new ParameterValuePair(parameter, value));
        if (mPreferFirstRepeatedParameter) {
            if (mEntries.containsKey(parameter)) {
                return;
            }
        }
        mEntries.put(parameter, value);
    
protected voidclear()
Clear the existing entries. Called to get ready to parse a new query string.

        mEntries.clear();
        mEntriesList.clear();
    
protected intdecodeHexDigit(char c)
Convert a character that represents a hexidecimal digit into an integer. If the character is not a hexidecimal digit, then -1 is returned. Both upper case and lower case hex digits are allowed.

param
c the hexidecimal digit.
return
the integer value of the hexidecimal digit.

        if (c >= '0" && c <= '9") {
            return c - '0";
        }
        else if (c >= 'A" && c <= 'F") {
            return c - 'A" + 10;
        }
        else if (c >= 'a" && c <= 'f") {
            return c - 'a" + 10;
        }
        else {
            return -1;
        }
    
public static final android.net.UrlQuerySanitizer$ValueSanitizergetAllButNulAndAngleBracketsLegal()
Return a value sanitizer that allows any special characters except angle brackets ('<' and '>') and Nul ('\0'). Allows script URLs.

return
a value sanitizer

        return sAllButNulAndAngleBracketsLegal;
    
public static final android.net.UrlQuerySanitizer$ValueSanitizergetAllButNulLegal()
Return a value sanitizer that allows everything except Nul ('\0') characters. Script URLs are allowed.

return
a value sanitizer

        return sAllButNulLegal;
    
public static final android.net.UrlQuerySanitizer$ValueSanitizergetAllButWhitespaceLegal()
Return a value sanitizer that allows everything except Nul ('\0') characters, space (' '), and other whitespace characters. Script URLs are allowed.

return
a value sanitizer

        return sAllButWhitespaceLegal;
    
public static final android.net.UrlQuerySanitizer$ValueSanitizergetAllIllegal()
Return a value sanitizer that does not allow any special characters, and also does not allow script URLs.

return
a value sanitizer


                               
         
        return sAllIllegal;
    
public booleangetAllowUnregisteredParamaters()
Get whether or not unregistered parameters are allowed. If not allowed, they will be dropped when a query is parsed.

return
true if unregistered parameters are allowed.
see
#setAllowUnregisteredParamaters(boolean)

        return mAllowUnregisteredParamaters;
    
public static final android.net.UrlQuerySanitizer$ValueSanitizergetAmpAndSpaceLegal()
Return a value sanitizer that does not allow any special characters except ampersand ('&') and space (' '). Does not allow script URLs.

return
a value sanitizer

        return sAmpAndSpaceLegal;
    
public static final android.net.UrlQuerySanitizer$ValueSanitizergetAmpLegal()
Return a value sanitizer that does not allow any special characters except ampersand ('&'). Does not allow script URLs.

return
a value sanitizer

        return sAmpLegal;
    
public android.net.UrlQuerySanitizer$ValueSanitizergetEffectiveValueSanitizer(java.lang.String parameter)
Get the effective value sanitizer for a parameter. Like getValueSanitizer, except if there is no value sanitizer registered for a parameter, and unregistered paramaters are allowed, then the default value sanitizer is returned.

param
parameter an unescaped parameter
return
the effective value sanitizer for a parameter.

        ValueSanitizer sanitizer = getValueSanitizer(parameter);
        if (sanitizer == null && mAllowUnregisteredParamaters) {
            sanitizer = getUnregisteredParameterValueSanitizer();
        }
        return sanitizer;
    
public java.util.ListgetParameterList()
An array list of all of the parameter value pairs in the sanitized query, in the order they appeared in the query. May contain duplicate parameters.

Note: Do not modify this list. Treat it as a read-only list.

        return mEntriesList;
    
public java.util.SetgetParameterSet()
Get a set of all of the parameters found in the sanitized query.

Note: Do not modify this set. Treat it as a read-only set.

return
all the parameters found in the current query.

        return mEntries.keySet();
    
public booleangetPreferFirstRepeatedParameter()
Get whether or not the first occurrence of a repeated parameter is preferred.

return
true if the first occurrence of a repeated parameter is preferred.
see
#setPreferFirstRepeatedParameter(boolean)

        return mPreferFirstRepeatedParameter;
    
public static final android.net.UrlQuerySanitizer$ValueSanitizergetSpaceLegal()
Return a value sanitizer that does not allow any special characters except space (' '). Does not allow script URLs.

return
a value sanitizer

        return sSpaceLegal;
    
public android.net.UrlQuerySanitizer$ValueSanitizergetUnregisteredParameterValueSanitizer()
Get the current value sanitizer used when processing unregistered parameter values.

Note: The default unregistered parameter value sanitizer is one that doesn't allow any special characters, similar to what is returned by calling createAllIllegal.

return
the current ValueSanitizer used to sanitize unregistered parameter values.

        return mUnregisteredParameterValueSanitizer;
    
public static final android.net.UrlQuerySanitizer$ValueSanitizergetUrlAndSpaceLegal()
Return a value sanitizer that allows all the characters used by encoded URLs and allows spaces, which are not technically legal in encoded URLs, but commonly appear anyway. Does not allow script URLs.

return
a value sanitizer

        return sUrlAndSpaceLegal;
    
public static final android.net.UrlQuerySanitizer$ValueSanitizergetUrlLegal()
Return a value sanitizer that allows all the characters used by encoded URLs. Does not allow script URLs.

return
a value sanitizer

        return sURLLegal;
    
public java.lang.StringgetValue(java.lang.String parameter)
Get the value for a parameter in the current sanitized query. Returns null if the parameter does not exit.

param
parameter the unencoded name of a parameter.
return
the sanitized unencoded value of the parameter, or null if the parameter does not exist.

        return mEntries.get(parameter);
    
public android.net.UrlQuerySanitizer$ValueSanitizergetValueSanitizer(java.lang.String parameter)
Get the value sanitizer for a parameter. Returns null if there is no value sanitizer registered for the parameter.

param
parameter the unescaped parameter
return
the currently registered value sanitizer for this parameter.
see
#registerParameter(String, android.net.UrlQuerySanitizer.ValueSanitizer)

        return mSanitizers.get(parameter);
    
public booleanhasParameter(java.lang.String parameter)
Check if a parameter exists in the current sanitized query.

param
parameter the unencoded name of a parameter.
return
true if the paramater exists in the current sanitized queary.

        return mEntries.containsKey(parameter);
    
protected booleanisHexDigit(char c)
Test if a character is a hexidecimal digit. Both upper case and lower case hex digits are allowed.

param
c the character to test
return
true if c is a hex digit.

        return decodeHexDigit(c) >= 0;
    
protected voidparseEntry(java.lang.String parameter, java.lang.String value)
Parse an escaped parameter-value pair. The default implementation unescapes both the parameter and the value, then looks up the effective value sanitizer for the parameter and uses it to sanitize the value. If all goes well then addSanitizedValue is called with the unescaped parameter and the sanitized unescaped value.

param
parameter an escaped parameter
param
value an unsanitzied escaped value

        String unescapedParameter = unescape(parameter);
         ValueSanitizer valueSanitizer =
            getEffectiveValueSanitizer(unescapedParameter);

        if (valueSanitizer == null) {
            return;
        }
        String unescapedValue = unescape(value);
        String sanitizedValue = valueSanitizer.sanitize(unescapedValue);
        addSanitizedEntry(unescapedParameter, sanitizedValue);
    
public voidparseQuery(java.lang.String query)
Parse a query. A query string is any number of parameter-value clauses separated by any non-zero number of ampersands. A parameter-value clause is a parameter followed by an equal sign, followed by a value. If the equal sign is missing, the value is assumed to be the empty string.

param
query the query to parse.

        clear();
        // Split by '&'
        StringTokenizer tokenizer = new StringTokenizer(query, "&");
        while(tokenizer.hasMoreElements()) {
            String attributeValuePair = tokenizer.nextToken();
            if (attributeValuePair.length() > 0) {
                int assignmentIndex = attributeValuePair.indexOf('=");
                if (assignmentIndex < 0) {
                    // No assignment found, treat as if empty value
                    parseEntry(attributeValuePair, "");
                }
                else {
                    parseEntry(attributeValuePair.substring(0, assignmentIndex),
                            attributeValuePair.substring(assignmentIndex + 1));
                }
            }
        }
    
public voidparseUrl(java.lang.String url)
Parse the query parameters out of an encoded URL. Works by extracting the query portion from the URL and then calling parseQuery(). If there is no query portion it is treated as if the query portion is an empty string.

param
url the encoded URL to parse.

        int queryIndex = url.indexOf('?");
        String query;
        if (queryIndex >= 0) {
            query = url.substring(queryIndex + 1);
        }
        else {
            query = "";
        }
        parseQuery(query);
    
public voidregisterParameter(java.lang.String parameter, android.net.UrlQuerySanitizer$ValueSanitizer valueSanitizer)
Register a value sanitizer for a particular parameter. Can also be used to replace or remove an already-set value sanitizer.

Registering a non-null value sanitizer for a particular parameter makes that parameter a registered parameter.

param
parameter an unencoded parameter name
param
valueSanitizer the value sanitizer to use for a particular parameter. May be null in order to unregister that parameter.
see
#getAllowUnregisteredParamaters()

        if (valueSanitizer == null) {
            mSanitizers.remove(parameter);
        }
        mSanitizers.put(parameter, valueSanitizer);
    
public voidregisterParameters(java.lang.String[] parameters, android.net.UrlQuerySanitizer$ValueSanitizer valueSanitizer)
Register a value sanitizer for an array of parameters.

param
parameters An array of unencoded parameter names.
param
valueSanitizer
see
#registerParameter

        int length = parameters.length;
        for(int i = 0; i < length; i++) {
            mSanitizers.put(parameters[i], valueSanitizer);
        }
    
public voidsetAllowUnregisteredParamaters(boolean allowUnregisteredParamaters)
Set whether or not unregistered parameters are allowed. If they are not allowed, then they will be dropped when a query is sanitized.

Defaults to false.

param
allowUnregisteredParamaters true to allow unregistered parameters.
see
#getAllowUnregisteredParamaters()

        mAllowUnregisteredParamaters = allowUnregisteredParamaters;
    
public voidsetPreferFirstRepeatedParameter(boolean preferFirstRepeatedParameter)
Set whether or not the first occurrence of a repeated parameter is preferred. True means the first repeated parameter is preferred. False means that the last repeated parameter is preferred.

The preferred parameter is the one that is returned when getParameter is called.

defaults to false.

param
preferFirstRepeatedParameter True if the first repeated parameter is preferred.
see
#getPreferFirstRepeatedParameter()

        mPreferFirstRepeatedParameter = preferFirstRepeatedParameter;
    
public voidsetUnregisteredParameterValueSanitizer(android.net.UrlQuerySanitizer$ValueSanitizer sanitizer)
Set the value sanitizer used when processing unregistered parameter values.

param
sanitizer set the ValueSanitizer used to sanitize unregistered parameter values.

        mUnregisteredParameterValueSanitizer = sanitizer;
    
public java.lang.Stringunescape(java.lang.String string)
Unescape an escaped string.
  • '+' characters are replaced by ' ' characters.
  • Valid "%xx" escape sequences are replaced by the corresponding unescaped character.
  • Invalid escape sequences such as %1z", are passed through unchanged.

      param
      string the escaped string
      return
      the unescaped string.

              // Early exit if no escaped characters.
              int firstEscape = string.indexOf('%");
              if ( firstEscape < 0) {
                  firstEscape = string.indexOf('+");
                  if (firstEscape < 0) {
                      return string;
                  }
              }
      
              int length = string.length();
      
              StringBuilder stringBuilder = new StringBuilder(length);
              stringBuilder.append(string.substring(0, firstEscape));
              for (int i = firstEscape; i < length; i++) {
                  char c = string.charAt(i);
                  if (c == '+") {
                      c = ' ";
                  }
                  else if ( c == '%" && i + 2 < length) {
                      char c1 = string.charAt(i + 1);
                      char c2 = string.charAt(i + 2);
                      if (isHexDigit(c1) && isHexDigit(c2)) {
                          c = (char) (decodeHexDigit(c1) * 16 + decodeHexDigit(c2));
                          i += 2;
                      }
                  }
                  stringBuilder.append(c);
              }
              return stringBuilder.toString();