001    /**
002     * Implements the Cold Fusion Function urlencodedformat
003     */
004    package railo.runtime.functions.other;
005    
006    import java.io.UnsupportedEncodingException;
007    
008    import railo.commons.lang.StringUtil;
009    import railo.commons.lang.URLEncoder;
010    import railo.runtime.PageContext;
011    import railo.runtime.exp.PageException;
012    import railo.runtime.ext.function.Function;
013    import railo.runtime.net.http.ReqRspUtil;
014    import railo.runtime.op.Caster;
015    
016    public final class URLEncodedFormat implements Function {
017            
018            private static final long serialVersionUID = 5640029138134769481L;
019    
020            public static String call(PageContext pc , String str) throws PageException {
021                    return call(pc,str, "UTF-8",true);
022            }
023            
024    
025            public static String call(PageContext pc , String str, String encoding) throws PageException {
026                    return call(pc,str, encoding,true);
027            }
028            
029            public static String call(PageContext pc , String str, String encoding,boolean force) throws PageException {
030                    if(!force && !ReqRspUtil.needEncoding(str,false))
031                            return str;
032                    
033                    try {
034                            String enc=railo.commons.net.URLEncoder.encode(str, encoding);
035                            return StringUtil.replace(StringUtil.replace(StringUtil.replace(StringUtil.replace(StringUtil.replace(enc, "+", "%20", false), "*", "%2A", false), "-", "%2D", false), ".", "%2E", false), "_", "%5F", false);// TODO do better
036                            //return enc;
037                    } 
038                    catch (Throwable t) {
039                            try {
040                                    return URLEncoder.encode(str, encoding);
041                            } 
042                            catch (UnsupportedEncodingException e) {
043                                    throw Caster.toPageException(e);
044                            }
045                    }
046            }
047            
048    }