View Javadoc
1   /*
2    * Copyright 2016 The Lannister Project
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 net.anyflow.lannister.http;
18  
19  import java.io.IOException;
20  import java.io.InputStream;
21  import java.io.UnsupportedEncodingException;
22  import java.util.HashMap;
23  import java.util.Map;
24  
25  import org.slf4j.Logger;
26  import org.slf4j.LoggerFactory;
27  import org.w3c.tidy.Tidy;
28  
29  import io.netty.handler.codec.http.HttpResponseStatus;
30  
31  public class HtmlGenerator {
32  
33  	private static final Logger logger = LoggerFactory.getLogger(HtmlGenerator.class);
34  
35  	private static String html_error;
36  
37  	static {
38  		html_error = tidy(Thread.currentThread().getContextClassLoader().getResourceAsStream("html/error.htm"));
39  	}
40  
41  	public static String generate(Map<String, String> values, String htmlPath) throws IOException {
42  		return replace(values, tidy(Thread.currentThread().getContextClassLoader().getResourceAsStream(htmlPath)));
43  	}
44  
45  	private static String replace(Map<String, String> values, String htmlTemplate) {
46  		String openMarker = "${";
47  		String closeMarker = "}";
48  
49  		String ret = htmlTemplate;
50  
51  		for (Map.Entry<String, String> item : values.entrySet()) {
52  			ret = ret.replace(openMarker + item.getKey() + closeMarker, item.getValue());
53  		}
54  
55  		return ret;
56  	}
57  
58  	public static String error(String message, HttpResponseStatus status) {
59  		HashMap<String, String> values = new HashMap<String, String>();
60  
61  		values.put("ERROR_CODE", status.toString());
62  		values.put("message", message);
63  
64  		return replace(values, html_error);
65  	}
66  
67  	private static String tidy(InputStream is) {
68  		Tidy tidy = new Tidy();
69  
70  		tidy.setQuiet(true);
71  		tidy.setDocType("loose");
72  		tidy.setTidyMark(false);
73  		tidy.setOutputEncoding("UTF8");
74  
75  		java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
76  		tidy.parse(is, out);
77  
78  		try {
79  			return out.toString("UTF-8");
80  		}
81  		catch (UnsupportedEncodingException e) {
82  
83  			logger.error(e.getMessage(), e);
84  			return null;
85  		}
86  	}
87  }