View Javadoc

1   /*
2    * Copyright 2007-2008 the original author or authors.
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 org.gwe.utils.web;
18  
19  import java.io.UnsupportedEncodingException;
20  import java.net.URLEncoder;
21  import java.util.HashMap;
22  import java.util.Map;
23  
24  import org.gwe.app.client.web.request.PageModel;
25  import org.gwe.app.client.web.request.Param;
26  
27  /**
28   * @author Marco Ruiz
29   * @since Dec 15, 2008
30   */
31  public class HtmlLink extends HashMap<Object, Object> {
32  	
33  	private String context;
34  	private boolean external = false;
35  	
36  	public HtmlLink(boolean external, String context, PageModel model) {
37  	    this(external, context);
38  	    for (Param param : Param.values())
39  	        put(param, model.getParam(param));
40      }
41  	
42  	public HtmlLink(boolean external, String context) {
43  		this.external = external;
44  	    this.context = context;
45      }
46  	
47  	public HtmlLink addParam(Object key, Object value) {
48  		put(key, value);
49  		return this;
50  	}
51  	
52  	public String render() {
53  		StringBuffer result = new StringBuffer();
54  		if (context.contains("#")) return context;
55  		result.append(context + "?");
56  		for (Map.Entry<Object, Object> entry : entrySet())
57  			result.append(encode(entry.getKey()) + "=" + encode(entry.getValue()) + "&");
58  		
59  		return result.toString(); 
60  	}
61  	
62  	public StringBuffer getHTML(StringBuffer content) {
63  		StringBuffer result = new StringBuffer();
64  	    result.append("<a href=\"").append(render()).append("\" ").append(getAttributes()).append(">");
65  		result.append(content);
66  		result.append("</a>");
67  		return result;
68      }
69  
70  	private String encode(Object value) {
71  		String valueStr = (value == null) ? "" : value.toString();
72  		try {
73  	        return URLEncoder.encode(valueStr, "UTF-8");
74          } catch (UnsupportedEncodingException e) {
75          	return valueStr;
76          }
77      }
78  
79  	public String getAttributes() {
80  	    return external ? " class=\"externalLink\" " : "";
81      }
82  }