
cat.inspiracio.url.URLParameters Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of url-parser Show documentation
Show all versions of url-parser Show documentation
A JavaBean for URLs of the HTTP protocol.
/*
Copyright 2015 Alexander Bunkenburg
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 cat.inspiracio.url;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.StringTokenizer;
import cat.inspiracio.util.BagMap;
/** URL parameters: each key is mapped to one or more values.
* The parameters are kept in the order in which they were inserted. */
public class URLParameters extends BagMap implements Serializable{
private static final long serialVersionUID = -6159016415157423666L;
// construction -------------------------------------------------
/** Starts off with no parameters. */
public URLParameters(){}
//Very useful, but introduces dependency on HttpServletRequest.
// URLParameters(HttpServletRequest request){
// @SuppressWarnings("unchecked")
// Enumerationkeys=request.getParameterNames();
// Iterable ps=new EnumerationIterable(keys);
// for(String key : ps){
// String[] values=request.getParameterValues(key);//already decoded
// if(values!=null){
// for(String value : values)
// add(key, value);
// }
// }
// }
/** Returns null if there are no parameters. */
//Very useful, but introduces dependency on HttpServletRequest.
// public static URLParameters from(HttpServletRequest request){
// if(request.getParameterNames().hasMoreElements())
// return new URLParameters(request);
// return null;
// }
/** Parses URL parameters from the string that may be returned from request.getQueryString().
* @param query Like request.getQueryString(). URL-encoded. */
URLParameters(String query){parse(query);}
/** Initialises with a copy of the parameters from init. */
URLParameters(URLParameters init){
for(Entry p : init)
add(p.getKey(), p.getValue());
}
/** Appends a parameter. Maybe the key is already there. */
public void append(String key, String value){add(key, value);}
/** Gets all values of this key. */
public List getAll(String key){return getValues(key);}
/** Is there a value for this key? */
boolean has(String key){return containsKey(key);}
/** Returns a new URLParameters object that is
* like this, but the keys and values are sorted. */
URLParameters sort(){
URLParameters ps=new URLParameters();
Listkeys=new ArrayList(keys());
Collections.sort(keys);
for(String key : keys){
Listvalues=getValues(key);
Collections.sort(values);
for(String value : values)
ps.add(key, value);
}
return ps;
}
/** Deep clone. */
public URLParameters clone(){
String s=toString();
return new URLParameters(s);
}
/** Deletes all values for this key. */
public void delete(String key){remove(key);}
// business -----------------------------------------------------
/** Adds an entry. If the value is null, removes the parameter. */
@Override public URLParameters add(String key, String value){
return (URLParameters)super.add(key, value);
}
/** A string that can be appended to a URL.
* The parameters are already URL-encoded. */
@Override public String toString(){
if(empty())return "";
StringBuilder s=new StringBuilder();
boolean first=true;
for(Map.Entry e : this){
if(!first)s.append('&');
String key=encode(e.getKey());
String value=encode(e.getValue());
s.append(key);
s.append('=');
s.append(value);
first=false;
}
return s.toString();
}
/** Parse a query string and adds the found parameters. */
public URLParameters parse(String query){
if(query==null)return this;
if(query.length()==0)return this;
//Parsing is primitive. No error handling.
StringTokenizer pairs=new StringTokenizer(query, "&");
while(pairs.hasMoreTokens()){
String pair=pairs.nextToken ();
StringTokenizer parts=new StringTokenizer (pair, "=");
String key=decode(parts.nextToken ());
String value="";//If there is no value, should it be "" or null?
if(parts.hasMoreTokens())
value=parts.nextToken();
value=decode(value);
add(key, value);
}
return this;
}
/** URLParameters objects are equal if the have the same keys and values.
* The order is not relevant.
* This is the same as in http. */
@Override public boolean equals(Object o){
if(o==null)return false;
if(this==o)return true;
if(!(o instanceof URLParameters))return false;
URLParameters ps=(URLParameters)o;
URLParameters a=sort();//can I avoid this?
URLParameters b=ps.sort();
String as=a.toString();//can I avoid this?
String bs=b.toString();
return as.equals(bs);
}
/** Matches equals(), does not take order into account. */
@Override public int hashCode(){
URLParameters ps=sort();
String s=ps.toString();
return s.hashCode();
}
// helpers -------------------------------------------------------
private String encode(String s){
try{return URLEncoder.encode(s, "UTF-8");}
catch(UnsupportedEncodingException e){throw new RuntimeException(e);}
}
private String decode(String s){
try{return URLDecoder.decode(s, "UTF-8");}
catch(UnsupportedEncodingException e){throw new RuntimeException(e);}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy