1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.kuali.rice.krad.util;
17
18 import org.apache.commons.codec.EncoderException;
19 import org.apache.commons.codec.net.URLCodec;
20 import org.apache.commons.lang.StringUtils;
21 import org.apache.log4j.Logger;
22
23 import java.util.Properties;
24
25
26
27
28
29
30
31 public class UrlFactory {
32 private static Logger LOG = Logger.getLogger(UrlFactory.class);
33
34
35
36
37
38
39
40
41
42
43
44
45 private static URLCodec urlCodec = new URLCodec("UTF-8");
46
47 public static String parameterizeUrl(String baseUrl, Properties params) {
48 baseUrl = StringUtils.trim(baseUrl);
49 if (StringUtils.isEmpty(baseUrl)) {
50 throw new IllegalArgumentException("invalid (blank) base URL");
51 }
52 if (params == null) {
53 throw new IllegalArgumentException("invalid (null) Properties");
54 }
55
56
57 StringBuffer ret = new StringBuffer(baseUrl);
58
59 String delimiter = (ret.indexOf("?") == -1) ? "?" : "&";
60 for ( Object key : params.keySet() ) {
61 String paramName = StringUtils.trim( (String)key );
62 String paramValue = params.getProperty(paramName);
63 ret.append( delimiter );
64 if (StringUtils.isEmpty(paramName)) {
65 throw new IllegalArgumentException("invalid (blank) paramName");
66 }
67 if (paramValue == null) {
68 ret.append( paramName );
69 ret.append( "=" );
70 } else {
71 try {
72 ret.append( paramName );
73 ret.append( "=" );
74 ret.append( urlCodec.encode(paramValue) );
75 } catch ( EncoderException ex ) {
76 LOG.error("Unable to encode parameter name or value: " + paramName + "=" + paramValue, ex);
77 throw new RuntimeException( "Unable to encode parameter name or value: " + paramName + "=" + paramValue, ex );
78 }
79 }
80 delimiter = "&";
81 }
82
83 return ret.toString();
84 }
85
86 public static String encode( String value ) {
87 try {
88 return urlCodec.encode(value);
89 } catch ( EncoderException ex ) {
90 throw new RuntimeException( "Unable to encode value: " + value, ex );
91 }
92 }
93 }