JR Utily

simplify H2 console, and deploy it only when in Integration project stage

1 -package org.legrog.util;
2 -// Code copied from org.h2.server.web.ConnectionInfo
3 -/*
4 - * Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0,
5 - * and the EPL 1.0 (http://h2database.com/html/license.html).
6 - * Initial Developer: H2 Group
7 - */
8 -//package org.h2.server.web;
9 -
10 - import org.h2.util.MathUtils;
11 - import org.h2.util.StringUtils;
12 -
13 -/**
14 - * The connection info object is a wrapper for database connection information
15 - * such as the database URL, user name and password.
16 - * This class is used by the H2 Console.
17 - */
18 -public class ConnectionInfo implements Comparable<ConnectionInfo> {
19 - /**
20 - * The driver class name.
21 - */
22 - public String driver;
23 -
24 - /**
25 - * The database URL.
26 - */
27 - public String url;
28 -
29 - /**
30 - * The user name.
31 - */
32 - public String user;
33 -
34 - /**
35 - * The connection display name.
36 - */
37 - String name;
38 -
39 - /**
40 - * The last time this connection was used.
41 - */
42 - int lastAccess;
43 -
44 - ConnectionInfo() {
45 - // nothing to do
46 - }
47 -
48 - public ConnectionInfo(String data) {
49 - String[] array = StringUtils.arraySplit(data, '|', false);
50 - name = get(array, 0);
51 - driver = get(array, 1);
52 - url = get(array, 2);
53 - user = get(array, 3);
54 - }
55 -
56 - private static String get(String[] array, int i) {
57 - return array != null && array.length > i ? array[i] : "";
58 - }
59 -
60 - String getString() {
61 - return StringUtils.arrayCombine(new String[] { name, driver, url, user }, '|');
62 - }
63 -
64 - @Override
65 - public int compareTo(ConnectionInfo o) {
66 - return -MathUtils.compareInt(lastAccess, o.lastAccess);
67 - }
68 -
69 -}
...\ No newline at end of file ...\ No newline at end of file
1 package org.legrog.util; 1 package org.legrog.util;
2 2
3 -import javax.servlet.annotation.WebServlet; 3 +import org.apache.deltaspike.core.api.projectstage.ProjectStage;
4 - 4 +import org.apache.deltaspike.core.util.ProjectStageProducer;
5 -import java.io.IOException; 5 +import org.slf4j.Logger;
6 -import java.net.InetAddress; 6 +import org.slf4j.LoggerFactory;
7 -import java.net.UnknownHostException;
8 -import java.util.ArrayList;
9 -import java.util.Enumeration;
10 -import java.util.Properties;
11 7
12 -import javax.servlet.ServletConfig; 8 +import javax.servlet.annotation.WebInitParam;
13 -import javax.servlet.ServletOutputStream; 9 +import javax.servlet.annotation.WebServlet;
14 -import javax.servlet.http.HttpServlet;
15 -import javax.servlet.http.HttpServletRequest;
16 -import javax.servlet.http.HttpServletResponse;
17 10
18 -import org.h2.engine.Constants; 11 +import static org.legrog.util.H2ConsoleServlet.CONSOLE_MAPPING;
19 -import org.h2.server.web.PageParser;
20 -import org.h2.util.New;
21 12
22 13
23 -@WebServlet(urlPatterns="/console/*", name="H2Console", loadOnStartup=1) 14 +@WebServlet(
24 -public class H2ConsoleServlet extends HttpServlet { 15 + urlPatterns = CONSOLE_MAPPING,
25 -// Code copied from org.h2.server.web.WebServlet 16 + name = "H2Console",
26 - private static final long serialVersionUID = 1L; 17 + loadOnStartup = 1,
27 - private transient WebServer server; 18 + initParams = {@WebInitParam(name = "webAllowOthers", value = ""), @WebInitParam(name = "trace", value = "")}
19 +)
20 +public class H2ConsoleServlet extends org.h2.server.web.WebServlet {
21 + static final String CONSOLE_MAPPING = "/console/*";
22 + private Logger logger = LoggerFactory.getLogger(getClass());
28 23
29 @Override 24 @Override
30 public void init() { 25 public void init() {
31 - ServletConfig config = getServletConfig(); 26 + ProjectStage projectStage = ProjectStageProducer.getInstance().getProjectStage();
32 - Enumeration<?> en = config.getInitParameterNames(); 27 + if (projectStage == ProjectStage.IntegrationTest) {
33 - ArrayList<String> list = New.arrayList(); 28 + logger.info("Create a H2 Console Servlet mapped to {}", CONSOLE_MAPPING);
34 - while (en.hasMoreElements()) { 29 + super.init();
35 - String name = en.nextElement().toString();
36 - String value = config.getInitParameter(name);
37 - if (!name.startsWith("-")) {
38 - name = "-" + name;
39 - }
40 - list.add(name);
41 - if (value.length() > 0) {
42 - list.add(value);
43 - }
44 - }
45 - String[] args = new String[list.size()];
46 - list.toArray(args);
47 - server = new WebServer();
48 - server.setAllowChunked(false);
49 - server.init(args);
50 - }
51 -
52 - @Override
53 - public void destroy() {
54 - server.stop();
55 - }
56 -
57 - private boolean allow(HttpServletRequest req) {
58 - if (server.getAllowOthers()) {
59 - return true;
60 - }
61 - String addr = req.getRemoteAddr();
62 - try {
63 - InetAddress address = InetAddress.getByName(addr);
64 - return address.isLoopbackAddress();
65 - } catch (UnknownHostException e) {
66 - return false;
67 - } catch (NoClassDefFoundError e) {
68 - // Google App Engine does not allow java.net.InetAddress
69 - return false;
70 - }
71 - }
72 -
73 - private String getAllowedFile(HttpServletRequest req, String requestedFile) {
74 - if (!allow(req)) {
75 - return "notAllowed.jsp";
76 - }
77 - if (requestedFile.length() == 0) {
78 - return "index.do";
79 - }
80 - return requestedFile;
81 - }
82 -
83 - @Override
84 - public void doGet(HttpServletRequest req, HttpServletResponse resp)
85 - throws IOException {
86 - req.setCharacterEncoding("utf-8");
87 - String file = req.getPathInfo();
88 - if (file == null) {
89 - resp.sendRedirect(req.getRequestURI() + "/");
90 - return;
91 - } else if (file.startsWith("/")) {
92 - file = file.substring(1);
93 - }
94 - file = getAllowedFile(req, file);
95 -
96 - // extract the request attributes
97 - Properties attributes = new Properties();
98 - Enumeration<?> en = req.getAttributeNames();
99 - while (en.hasMoreElements()) {
100 - String name = en.nextElement().toString();
101 - String value = req.getAttribute(name).toString();
102 - attributes.put(name, value);
103 - }
104 - en = req.getParameterNames();
105 - while (en.hasMoreElements()) {
106 - String name = en.nextElement().toString();
107 - String value = req.getParameter(name);
108 - attributes.put(name, value);
109 - }
110 -
111 - WebSession session = null;
112 - String sessionId = attributes.getProperty("jsessionid");
113 - if (sessionId != null) {
114 - session = server.getSession(sessionId);
115 - }
116 - WebApp app = new WebApp(server);
117 - app.setSession(session, attributes);
118 - String ifModifiedSince = req.getHeader("if-modified-since");
119 -
120 - String hostAddr = req.getRemoteAddr();
121 - file = app.processRequest(file, hostAddr);
122 - session = app.getSession();
123 -
124 - String mimeType = app.getMimeType();
125 - boolean cache = app.getCache();
126 -
127 - if (cache && server.getStartDateTime().equals(ifModifiedSince)) {
128 - resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
129 - return;
130 - }
131 - byte[] bytes = server.getFile(file);
132 - if (bytes == null) {
133 - resp.sendError(HttpServletResponse.SC_NOT_FOUND);
134 - bytes = ("File not found: " + file).getBytes(Constants.UTF8);
135 } else { 30 } else {
136 - if (session != null && file.endsWith(".jsp")) { 31 + logger.info("Skipping H2 Console Servlet creation");
137 - String page = new String(bytes, Constants.UTF8);
138 - page = PageParser.parse(page, session.map);
139 - bytes = page.getBytes(Constants.UTF8);
140 - }
141 - resp.setContentType(mimeType);
142 - if (!cache) {
143 - resp.setHeader("Cache-Control", "no-cache");
144 - } else {
145 - resp.setHeader("Cache-Control", "max-age=10");
146 - resp.setHeader("Last-Modified", server.getStartDateTime());
147 - }
148 } 32 }
149 - if (bytes != null) {
150 - ServletOutputStream out = resp.getOutputStream();
151 - out.write(bytes);
152 - }
153 - }
154 33
155 - @Override
156 - public void doPost(HttpServletRequest req, HttpServletResponse resp)
157 - throws IOException {
158 - doGet(req, resp);
159 } 34 }
160 } 35 }
36 +
......
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
1 -package org.legrog.util;
2 -// Code copied from org.h2.server.web.WebSession
3 -/*
4 - * Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0,
5 - * and the EPL 1.0 (http://h2database.com/html/license.html).
6 - * Initial Developer: H2 Group
7 - */
8 -///package org.h2.server.web;
9 -
10 - import java.sql.Connection;
11 - import java.sql.DatabaseMetaData;
12 - import java.sql.ResultSet;
13 - import java.sql.SQLException;
14 - import java.sql.Statement;
15 - import java.sql.Timestamp;
16 - import java.util.ArrayList;
17 - import java.util.HashMap;
18 - import java.util.Locale;
19 -
20 - import org.h2.bnf.Bnf;
21 - import org.h2.bnf.context.DbContents;
22 - import org.h2.bnf.context.DbContextRule;
23 - import org.h2.message.DbException;
24 - import org.h2.util.New;
25 -
26 -/**
27 - * The web session keeps all data of a user session.
28 - * This class is used by the H2 Console.
29 - */
30 -class WebSession {
31 -
32 - private static final int MAX_HISTORY = 1000;
33 -
34 - /**
35 - * The last time this client sent a request.
36 - */
37 - long lastAccess;
38 -
39 - /**
40 - * The session attribute map.
41 - */
42 - final HashMap<String, Object> map = New.hashMap();
43 -
44 - /**
45 - * The current locale.
46 - */
47 - Locale locale;
48 -
49 - /**
50 - * The currently executing statement.
51 - */
52 - Statement executingStatement;
53 -
54 - /**
55 - * The current updatable result set.
56 - */
57 - ResultSet result;
58 -
59 - private final WebServer server;
60 -
61 - private final ArrayList<String> commandHistory;
62 -
63 - private Connection conn;
64 - private DatabaseMetaData meta;
65 - private DbContents contents = new DbContents();
66 - private Bnf bnf;
67 - private boolean shutdownServerOnDisconnect;
68 -
69 - WebSession(WebServer server) {
70 - this.server = server;
71 - // This must be stored in the session rather than in the server.
72 - // Otherwise, one client could allow
73 - // saving history for others (insecure).
74 - this.commandHistory = server.getCommandHistoryList();
75 - }
76 -
77 - /**
78 - * Put an attribute value in the map.
79 - *
80 - * @param key the key
81 - * @param value the new value
82 - */
83 - void put(String key, Object value) {
84 - map.put(key, value);
85 - }
86 -
87 - /**
88 - * Get the value for the given key.
89 - *
90 - * @param key the key
91 - * @return the value
92 - */
93 - Object get(String key) {
94 - if ("sessions".equals(key)) {
95 - return server.getSessions();
96 - }
97 - return map.get(key);
98 - }
99 -
100 - /**
101 - * Remove a session attribute from the map.
102 - *
103 - * @param key the key
104 - */
105 - void remove(String key) {
106 - map.remove(key);
107 - }
108 -
109 - /**
110 - * Get the BNF object.
111 - *
112 - * @return the BNF object
113 - */
114 - Bnf getBnf() {
115 - return bnf;
116 - }
117 -
118 - /**
119 - * Load the SQL grammar BNF.
120 - */
121 - void loadBnf() {
122 - try {
123 - Bnf newBnf = Bnf.getInstance(null);
124 - DbContextRule columnRule =
125 - new DbContextRule(contents, DbContextRule.COLUMN);
126 - DbContextRule newAliasRule =
127 - new DbContextRule(contents, DbContextRule.NEW_TABLE_ALIAS);
128 - DbContextRule aliasRule =
129 - new DbContextRule(contents, DbContextRule.TABLE_ALIAS);
130 - DbContextRule tableRule =
131 - new DbContextRule(contents, DbContextRule.TABLE);
132 - DbContextRule schemaRule =
133 - new DbContextRule(contents, DbContextRule.SCHEMA);
134 - DbContextRule columnAliasRule =
135 - new DbContextRule(contents, DbContextRule.COLUMN_ALIAS);
136 - DbContextRule procedure =
137 - new DbContextRule(contents, DbContextRule.PROCEDURE);
138 - newBnf.updateTopic("procedure", procedure);
139 - newBnf.updateTopic("column_name", columnRule);
140 - newBnf.updateTopic("new_table_alias", newAliasRule);
141 - newBnf.updateTopic("table_alias", aliasRule);
142 - newBnf.updateTopic("column_alias", columnAliasRule);
143 - newBnf.updateTopic("table_name", tableRule);
144 - newBnf.updateTopic("schema_name", schemaRule);
145 - newBnf.linkStatements();
146 - bnf = newBnf;
147 - } catch (Exception e) {
148 - // ok we don't have the bnf
149 - server.traceError(e);
150 - }
151 - }
152 -
153 - /**
154 - * Get the SQL statement from history.
155 - *
156 - * @param id the history id
157 - * @return the SQL statement
158 - */
159 - String getCommand(int id) {
160 - return commandHistory.get(id);
161 - }
162 -
163 - /**
164 - * Add a SQL statement to the history.
165 - *
166 - * @param sql the SQL statement
167 - */
168 - void addCommand(String sql) {
169 - if (sql == null) {
170 - return;
171 - }
172 - sql = sql.trim();
173 - if (sql.length() == 0) {
174 - return;
175 - }
176 - if (commandHistory.size() > MAX_HISTORY) {
177 - commandHistory.remove(0);
178 - }
179 - int idx = commandHistory.indexOf(sql);
180 - if (idx >= 0) {
181 - commandHistory.remove(idx);
182 - }
183 - commandHistory.add(sql);
184 - if (server.isCommandHistoryAllowed()) {
185 - server.saveCommandHistoryList(commandHistory);
186 - }
187 - }
188 -
189 - /**
190 - * Get the list of SQL statements in the history.
191 - *
192 - * @return the commands
193 - */
194 - ArrayList<String> getCommandHistory() {
195 - return commandHistory;
196 - }
197 -
198 - /**
199 - * Update session meta data information and get the information in a map.
200 - *
201 - * @return a map containing the session meta data
202 - */
203 - HashMap<String, Object> getInfo() {
204 - HashMap<String, Object> m = New.hashMap();
205 - m.putAll(map);
206 - m.put("lastAccess", new Timestamp(lastAccess).toString());
207 - try {
208 - m.put("url", conn == null ?
209 - "${text.admin.notConnected}" : conn.getMetaData().getURL());
210 - m.put("user", conn == null ?
211 - "-" : conn.getMetaData().getUserName());
212 - m.put("lastQuery", commandHistory.size() == 0 ?
213 - "" : commandHistory.get(0));
214 - m.put("executing", executingStatement == null ?
215 - "${text.admin.no}" : "${text.admin.yes}");
216 - } catch (SQLException e) {
217 - DbException.traceThrowable(e);
218 - }
219 - return m;
220 - }
221 -
222 - void setConnection(Connection conn) throws SQLException {
223 - this.conn = conn;
224 - if (conn == null) {
225 - meta = null;
226 - } else {
227 - meta = conn.getMetaData();
228 - }
229 - contents = new DbContents();
230 - }
231 -
232 - DatabaseMetaData getMetaData() {
233 - return meta;
234 - }
235 -
236 - Connection getConnection() {
237 - return conn;
238 - }
239 -
240 - DbContents getContents() {
241 - return contents;
242 - }
243 -
244 - /**
245 - * Shutdown the server when disconnecting.
246 - */
247 - void setShutdownServerOnDisconnect() {
248 - this.shutdownServerOnDisconnect = true;
249 - }
250 -
251 - boolean getShutdownServerOnDisconnect() {
252 - return shutdownServerOnDisconnect;
253 - }
254 -
255 - /**
256 - * Close the connection and stop the statement if one is currently
257 - * executing.
258 - */
259 - void close() {
260 - if (executingStatement != null) {
261 - try {
262 - executingStatement.cancel();
263 - } catch (Exception e) {
264 - // ignore
265 - }
266 - }
267 - if (conn != null) {
268 - try {
269 - conn.close();
270 - } catch (Exception e) {
271 - // ignore
272 - }
273 - }
274 -
275 - }
276 -
277 -}
...\ No newline at end of file ...\ No newline at end of file
This diff is collapsed. Click to expand it.