JR Utily

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

package org.legrog.util;
// Code copied from org.h2.server.web.ConnectionInfo
/*
* Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
//package org.h2.server.web;
import org.h2.util.MathUtils;
import org.h2.util.StringUtils;
/**
* The connection info object is a wrapper for database connection information
* such as the database URL, user name and password.
* This class is used by the H2 Console.
*/
public class ConnectionInfo implements Comparable<ConnectionInfo> {
/**
* The driver class name.
*/
public String driver;
/**
* The database URL.
*/
public String url;
/**
* The user name.
*/
public String user;
/**
* The connection display name.
*/
String name;
/**
* The last time this connection was used.
*/
int lastAccess;
ConnectionInfo() {
// nothing to do
}
public ConnectionInfo(String data) {
String[] array = StringUtils.arraySplit(data, '|', false);
name = get(array, 0);
driver = get(array, 1);
url = get(array, 2);
user = get(array, 3);
}
private static String get(String[] array, int i) {
return array != null && array.length > i ? array[i] : "";
}
String getString() {
return StringUtils.arrayCombine(new String[] { name, driver, url, user }, '|');
}
@Override
public int compareTo(ConnectionInfo o) {
return -MathUtils.compareInt(lastAccess, o.lastAccess);
}
}
\ No newline at end of file
package org.legrog.util;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Properties;
import org.apache.deltaspike.core.api.projectstage.ProjectStage;
import org.apache.deltaspike.core.util.ProjectStageProducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletConfig;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import org.h2.engine.Constants;
import org.h2.server.web.PageParser;
import org.h2.util.New;
import static org.legrog.util.H2ConsoleServlet.CONSOLE_MAPPING;
@WebServlet(urlPatterns="/console/*", name="H2Console", loadOnStartup=1)
public class H2ConsoleServlet extends HttpServlet {
// Code copied from org.h2.server.web.WebServlet
private static final long serialVersionUID = 1L;
private transient WebServer server;
@WebServlet(
urlPatterns = CONSOLE_MAPPING,
name = "H2Console",
loadOnStartup = 1,
initParams = {@WebInitParam(name = "webAllowOthers", value = ""), @WebInitParam(name = "trace", value = "")}
)
public class H2ConsoleServlet extends org.h2.server.web.WebServlet {
static final String CONSOLE_MAPPING = "/console/*";
private Logger logger = LoggerFactory.getLogger(getClass());
@Override
public void init() {
ServletConfig config = getServletConfig();
Enumeration<?> en = config.getInitParameterNames();
ArrayList<String> list = New.arrayList();
while (en.hasMoreElements()) {
String name = en.nextElement().toString();
String value = config.getInitParameter(name);
if (!name.startsWith("-")) {
name = "-" + name;
}
list.add(name);
if (value.length() > 0) {
list.add(value);
}
}
String[] args = new String[list.size()];
list.toArray(args);
server = new WebServer();
server.setAllowChunked(false);
server.init(args);
}
@Override
public void destroy() {
server.stop();
}
private boolean allow(HttpServletRequest req) {
if (server.getAllowOthers()) {
return true;
}
String addr = req.getRemoteAddr();
try {
InetAddress address = InetAddress.getByName(addr);
return address.isLoopbackAddress();
} catch (UnknownHostException e) {
return false;
} catch (NoClassDefFoundError e) {
// Google App Engine does not allow java.net.InetAddress
return false;
}
}
private String getAllowedFile(HttpServletRequest req, String requestedFile) {
if (!allow(req)) {
return "notAllowed.jsp";
}
if (requestedFile.length() == 0) {
return "index.do";
}
return requestedFile;
}
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
req.setCharacterEncoding("utf-8");
String file = req.getPathInfo();
if (file == null) {
resp.sendRedirect(req.getRequestURI() + "/");
return;
} else if (file.startsWith("/")) {
file = file.substring(1);
}
file = getAllowedFile(req, file);
// extract the request attributes
Properties attributes = new Properties();
Enumeration<?> en = req.getAttributeNames();
while (en.hasMoreElements()) {
String name = en.nextElement().toString();
String value = req.getAttribute(name).toString();
attributes.put(name, value);
}
en = req.getParameterNames();
while (en.hasMoreElements()) {
String name = en.nextElement().toString();
String value = req.getParameter(name);
attributes.put(name, value);
}
WebSession session = null;
String sessionId = attributes.getProperty("jsessionid");
if (sessionId != null) {
session = server.getSession(sessionId);
}
WebApp app = new WebApp(server);
app.setSession(session, attributes);
String ifModifiedSince = req.getHeader("if-modified-since");
String hostAddr = req.getRemoteAddr();
file = app.processRequest(file, hostAddr);
session = app.getSession();
String mimeType = app.getMimeType();
boolean cache = app.getCache();
if (cache && server.getStartDateTime().equals(ifModifiedSince)) {
resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return;
}
byte[] bytes = server.getFile(file);
if (bytes == null) {
resp.sendError(HttpServletResponse.SC_NOT_FOUND);
bytes = ("File not found: " + file).getBytes(Constants.UTF8);
ProjectStage projectStage = ProjectStageProducer.getInstance().getProjectStage();
if (projectStage == ProjectStage.IntegrationTest) {
logger.info("Create a H2 Console Servlet mapped to {}", CONSOLE_MAPPING);
super.init();
} else {
if (session != null && file.endsWith(".jsp")) {
String page = new String(bytes, Constants.UTF8);
page = PageParser.parse(page, session.map);
bytes = page.getBytes(Constants.UTF8);
}
resp.setContentType(mimeType);
if (!cache) {
resp.setHeader("Cache-Control", "no-cache");
} else {
resp.setHeader("Cache-Control", "max-age=10");
resp.setHeader("Last-Modified", server.getStartDateTime());
}
}
if (bytes != null) {
ServletOutputStream out = resp.getOutputStream();
out.write(bytes);
}
logger.info("Skipping H2 Console Servlet creation");
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
doGet(req, resp);
}
}
......
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
package org.legrog.util;
// Code copied from org.h2.server.web.WebSession
/*
* Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
///package org.h2.server.web;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import org.h2.bnf.Bnf;
import org.h2.bnf.context.DbContents;
import org.h2.bnf.context.DbContextRule;
import org.h2.message.DbException;
import org.h2.util.New;
/**
* The web session keeps all data of a user session.
* This class is used by the H2 Console.
*/
class WebSession {
private static final int MAX_HISTORY = 1000;
/**
* The last time this client sent a request.
*/
long lastAccess;
/**
* The session attribute map.
*/
final HashMap<String, Object> map = New.hashMap();
/**
* The current locale.
*/
Locale locale;
/**
* The currently executing statement.
*/
Statement executingStatement;
/**
* The current updatable result set.
*/
ResultSet result;
private final WebServer server;
private final ArrayList<String> commandHistory;
private Connection conn;
private DatabaseMetaData meta;
private DbContents contents = new DbContents();
private Bnf bnf;
private boolean shutdownServerOnDisconnect;
WebSession(WebServer server) {
this.server = server;
// This must be stored in the session rather than in the server.
// Otherwise, one client could allow
// saving history for others (insecure).
this.commandHistory = server.getCommandHistoryList();
}
/**
* Put an attribute value in the map.
*
* @param key the key
* @param value the new value
*/
void put(String key, Object value) {
map.put(key, value);
}
/**
* Get the value for the given key.
*
* @param key the key
* @return the value
*/
Object get(String key) {
if ("sessions".equals(key)) {
return server.getSessions();
}
return map.get(key);
}
/**
* Remove a session attribute from the map.
*
* @param key the key
*/
void remove(String key) {
map.remove(key);
}
/**
* Get the BNF object.
*
* @return the BNF object
*/
Bnf getBnf() {
return bnf;
}
/**
* Load the SQL grammar BNF.
*/
void loadBnf() {
try {
Bnf newBnf = Bnf.getInstance(null);
DbContextRule columnRule =
new DbContextRule(contents, DbContextRule.COLUMN);
DbContextRule newAliasRule =
new DbContextRule(contents, DbContextRule.NEW_TABLE_ALIAS);
DbContextRule aliasRule =
new DbContextRule(contents, DbContextRule.TABLE_ALIAS);
DbContextRule tableRule =
new DbContextRule(contents, DbContextRule.TABLE);
DbContextRule schemaRule =
new DbContextRule(contents, DbContextRule.SCHEMA);
DbContextRule columnAliasRule =
new DbContextRule(contents, DbContextRule.COLUMN_ALIAS);
DbContextRule procedure =
new DbContextRule(contents, DbContextRule.PROCEDURE);
newBnf.updateTopic("procedure", procedure);
newBnf.updateTopic("column_name", columnRule);
newBnf.updateTopic("new_table_alias", newAliasRule);
newBnf.updateTopic("table_alias", aliasRule);
newBnf.updateTopic("column_alias", columnAliasRule);
newBnf.updateTopic("table_name", tableRule);
newBnf.updateTopic("schema_name", schemaRule);
newBnf.linkStatements();
bnf = newBnf;
} catch (Exception e) {
// ok we don't have the bnf
server.traceError(e);
}
}
/**
* Get the SQL statement from history.
*
* @param id the history id
* @return the SQL statement
*/
String getCommand(int id) {
return commandHistory.get(id);
}
/**
* Add a SQL statement to the history.
*
* @param sql the SQL statement
*/
void addCommand(String sql) {
if (sql == null) {
return;
}
sql = sql.trim();
if (sql.length() == 0) {
return;
}
if (commandHistory.size() > MAX_HISTORY) {
commandHistory.remove(0);
}
int idx = commandHistory.indexOf(sql);
if (idx >= 0) {
commandHistory.remove(idx);
}
commandHistory.add(sql);
if (server.isCommandHistoryAllowed()) {
server.saveCommandHistoryList(commandHistory);
}
}
/**
* Get the list of SQL statements in the history.
*
* @return the commands
*/
ArrayList<String> getCommandHistory() {
return commandHistory;
}
/**
* Update session meta data information and get the information in a map.
*
* @return a map containing the session meta data
*/
HashMap<String, Object> getInfo() {
HashMap<String, Object> m = New.hashMap();
m.putAll(map);
m.put("lastAccess", new Timestamp(lastAccess).toString());
try {
m.put("url", conn == null ?
"${text.admin.notConnected}" : conn.getMetaData().getURL());
m.put("user", conn == null ?
"-" : conn.getMetaData().getUserName());
m.put("lastQuery", commandHistory.size() == 0 ?
"" : commandHistory.get(0));
m.put("executing", executingStatement == null ?
"${text.admin.no}" : "${text.admin.yes}");
} catch (SQLException e) {
DbException.traceThrowable(e);
}
return m;
}
void setConnection(Connection conn) throws SQLException {
this.conn = conn;
if (conn == null) {
meta = null;
} else {
meta = conn.getMetaData();
}
contents = new DbContents();
}
DatabaseMetaData getMetaData() {
return meta;
}
Connection getConnection() {
return conn;
}
DbContents getContents() {
return contents;
}
/**
* Shutdown the server when disconnecting.
*/
void setShutdownServerOnDisconnect() {
this.shutdownServerOnDisconnect = true;
}
boolean getShutdownServerOnDisconnect() {
return shutdownServerOnDisconnect;
}
/**
* Close the connection and stop the statement if one is currently
* executing.
*/
void close() {
if (executingStatement != null) {
try {
executingStatement.cancel();
} catch (Exception e) {
// ignore
}
}
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
// ignore
}
}
}
}
\ No newline at end of file
This diff is collapsed. Click to expand it.