1 /* 2 * Copyright (C) 2010 Google Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.google.clearsilver.jsilver.functions.escape; 18 19 import com.google.clearsilver.jsilver.functions.TextFilter; 20 21 import java.io.ByteArrayOutputStream; 22 import java.io.IOException; 23 import java.io.OutputStreamWriter; 24 import java.io.UnsupportedEncodingException; 25 import java.net.URLEncoder; 26 27 /** 28 * This URL encodes the string. This converts characters such as ?, ampersands, and = into their URL 29 * safe equivilants using the %hh syntax. 30 */ 31 public class UrlEscapeFunction implements TextFilter { 32 33 private final String encoding; 34 35 public UrlEscapeFunction(String encoding) { 36 try { 37 // Sanity check. Fail at construction time rather than render time. 38 new OutputStreamWriter(new ByteArrayOutputStream(), encoding); 39 } catch (UnsupportedEncodingException e) { 40 throw new IllegalArgumentException("Unsupported encoding : " + encoding); 41 } 42 this.encoding = encoding; 43 } 44 45 @Override 46 public void filter(String in, Appendable out) throws IOException { 47 try { 48 out.append(URLEncoder.encode(in, encoding)); 49 } catch (UnsupportedEncodingException e) { 50 // The sanity check in the constructor should have caught this. 51 // Things must be really broken for this to happen, so throw an Error. 52 throw new Error("Unsuported encoding : " + encoding); 53 } 54 } 55 56 } 57