mirror of
https://github.com/zyphlar/LanternPowerMonitor.git
synced 2024-03-08 14:07:47 +00:00
Initial Commit
This commit is contained in:
66
util/lantern-util-servlet/pom.xml
Normal file
66
util/lantern-util-servlet/pom.xml
Normal file
@@ -0,0 +1,66 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.lanternsoftware.util</groupId>
|
||||
<artifactId>lantern-util-servlet</artifactId>
|
||||
<name>lantern-util-servlet</name>
|
||||
<version>1.0.0</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>${project.groupId}</groupId>
|
||||
<artifactId>lantern-util-common</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.freemarker</groupId>
|
||||
<artifactId>freemarker</artifactId>
|
||||
<version>2.3.23</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax</groupId>
|
||||
<artifactId>javaee-api</artifactId>
|
||||
<version>7.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.2</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>testCompile</goal>
|
||||
</goals>
|
||||
<phase>compile</phase>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<optimize>true</optimize>
|
||||
<showDeprecation>true</showDeprecation>
|
||||
<encoding>UTF-8</encoding>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-source-plugin</artifactId>
|
||||
<version>3.2.1</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>jar</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.lanternsoftware.util.servlet;
|
||||
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
|
||||
import com.lanternsoftware.util.NullUtils;
|
||||
|
||||
public class BasicAuth {
|
||||
private final String username;
|
||||
private final String password;
|
||||
|
||||
public BasicAuth(HttpServletRequest _req) {
|
||||
String u = null;
|
||||
String p = null;
|
||||
String auth = _req.getHeader("Authorization");
|
||||
if (auth != null && auth.startsWith("Basic")) {
|
||||
String credentials = new String(Base64.decodeBase64(auth.substring("Basic".length()).trim()), StandardCharsets.UTF_8);
|
||||
String[] values = credentials.split(":", 2);
|
||||
if (values.length == 2) {
|
||||
u = values[0];
|
||||
p = values[1];
|
||||
}
|
||||
}
|
||||
username = u;
|
||||
password = p;
|
||||
}
|
||||
|
||||
public BasicAuth(String _username, String _password) {
|
||||
username = _username;
|
||||
password = _password;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public static String toHeader(String _username, String _password) {
|
||||
return "Basic " + Base64.encodeBase64String(NullUtils.toByteArray(_username + ":" + _password));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.lanternsoftware.util.servlet;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
import freemarker.cache.MruCacheStorage;
|
||||
import freemarker.template.Configuration;
|
||||
import freemarker.template.DefaultObjectWrapperBuilder;
|
||||
import freemarker.template.TemplateExceptionHandler;
|
||||
|
||||
public abstract class FreemarkerConfigUtil {
|
||||
public static final Configuration createConfig(Class<?> _templateClassLoader, String _templatePath, int _cacheMaxTemplateCount) {
|
||||
Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
|
||||
cfg.setClassForTemplateLoading(_templateClassLoader, _templatePath);
|
||||
cfg.setObjectWrapper(new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_23).build());
|
||||
cfg.setDefaultEncoding("UTF-8");
|
||||
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.DEBUG_HANDLER);
|
||||
cfg.setCacheStorage(new MruCacheStorage(_cacheMaxTemplateCount, Math.max(1, _cacheMaxTemplateCount/2)));
|
||||
return cfg;
|
||||
}
|
||||
|
||||
public static final Configuration createFileSystemConfig(String _templatePath, int _cacheMaxTemplateCount) {
|
||||
try {
|
||||
Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
|
||||
cfg.setDirectoryForTemplateLoading(new File(_templatePath));
|
||||
cfg.setObjectWrapper(new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_23).build());
|
||||
cfg.setDefaultEncoding("UTF-8");
|
||||
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.DEBUG_HANDLER);
|
||||
cfg.setCacheStorage(new MruCacheStorage(_cacheMaxTemplateCount, Math.max(1, _cacheMaxTemplateCount/2)));
|
||||
return cfg;
|
||||
}
|
||||
catch (IOException _e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package com.lanternsoftware.util.servlet;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.http.Cookie;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.lanternsoftware.util.CollectionUtils;
|
||||
import com.lanternsoftware.util.NullUtils;
|
||||
|
||||
import freemarker.template.Configuration;
|
||||
|
||||
public abstract class FreemarkerServlet extends HttpServlet {
|
||||
protected static final Logger LOG = LoggerFactory.getLogger(FreemarkerServlet.class);
|
||||
|
||||
protected abstract Configuration getFreemarkerConfig();
|
||||
|
||||
public static String[] getPath(HttpServletRequest _request) {
|
||||
String sPath = _request.getRequestURI().substring(_request.getContextPath().length());
|
||||
if (sPath.startsWith("/"))
|
||||
sPath = sPath.substring(1);
|
||||
String[] path = sPath.split("/");
|
||||
if ((path == null) || (path.length == 0) || (path[0].length() == 0))
|
||||
return new String[] { "index" };
|
||||
int iExtPos = CollectionUtils.last(path).lastIndexOf(".");
|
||||
if (iExtPos > -1) {
|
||||
path[path.length - 1] = CollectionUtils.last(path).substring(0, iExtPos);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
public static void redirect(HttpServletResponse _response, String _sURL) throws IOException {
|
||||
_response.sendRedirect(_response.encodeRedirectURL(_sURL));
|
||||
}
|
||||
|
||||
public static void setResponseHtml(HttpServletResponse _response, String _sHtml) {
|
||||
setResponseEntity(_response, "text/html", _sHtml);
|
||||
}
|
||||
|
||||
public static void setResponseEntity(HttpServletResponse _response, String _sContentType, String _sEntity) {
|
||||
setResponseEntity(_response, 200, _sContentType, _sEntity);
|
||||
}
|
||||
|
||||
public static void setResponseEntity(HttpServletResponse _response, String _sContentType, byte[] _btData) {
|
||||
setResponseEntity(_response, 200, _sContentType, _btData);
|
||||
}
|
||||
|
||||
public static void setResponseEntity(HttpServletResponse _response, int _iStatus, String _sContentType, String _sEntity) {
|
||||
setResponseEntity(_response, _iStatus, _sContentType, NullUtils.toByteArray(_sEntity));
|
||||
}
|
||||
|
||||
public static void setResponseEntity(HttpServletResponse _response, int _iStatus, String _sContentType, byte[] _btData) {
|
||||
OutputStream os = null;
|
||||
try {
|
||||
_response.setStatus(_iStatus);
|
||||
_response.setCharacterEncoding("UTF-8");
|
||||
_response.setContentType(_sContentType);
|
||||
if ((_btData != null) && (_btData.length > 0)) {
|
||||
_response.setContentLength(_btData.length);
|
||||
os = _response.getOutputStream();
|
||||
os.write(_btData);
|
||||
}
|
||||
else
|
||||
_response.setContentLength(0);
|
||||
}
|
||||
catch (Exception e) {
|
||||
if (!e.getClass().getSimpleName().equals("ClientAbortException"))
|
||||
LOG.error("Failed to set response entity", e);
|
||||
}
|
||||
finally {
|
||||
IOUtils.closeQuietly(os);
|
||||
}
|
||||
}
|
||||
|
||||
public void render(HttpServletResponse _rep, String _sHtmlResourceKey, Map<String, Object> _mapModel) {
|
||||
String html = FreemarkerUtil.render(getFreemarkerConfig(), _sHtmlResourceKey, _mapModel);
|
||||
if (html == null)
|
||||
_rep.setStatus(500);
|
||||
else
|
||||
setResponseHtml(_rep, html);
|
||||
}
|
||||
|
||||
protected Map<String, Object> simpleModel(String _name, Object _value) {
|
||||
Map<String, Object> mapModel = new HashMap<String, Object>();
|
||||
mapModel.put(_name, _value);
|
||||
return mapModel;
|
||||
}
|
||||
|
||||
public static <T> T getSessionVar(HttpServletRequest _req, String _name) {
|
||||
return (T) _req.getSession().getAttribute(_name);
|
||||
}
|
||||
|
||||
public static void putSessionVar(HttpServletRequest _req, String _name, Object _var) {
|
||||
_req.getSession().setAttribute(_name, _var);
|
||||
}
|
||||
|
||||
protected String relativeOffset(HttpServletRequest _req) {
|
||||
String[] path = getPath(_req);
|
||||
StringBuilder offset = new StringBuilder();
|
||||
for (int i = 1; i < CollectionUtils.size(path); i++) {
|
||||
offset.append("../");
|
||||
}
|
||||
return offset.toString();
|
||||
}
|
||||
|
||||
protected Cookie getCookie(HttpServletRequest _req, String _name) {
|
||||
if (_req.getCookies() != null) {
|
||||
for (Cookie c : _req.getCookies()) {
|
||||
if (NullUtils.isEqual(c.getName(), _name))
|
||||
return c;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.lanternsoftware.util.servlet;
|
||||
|
||||
import java.io.StringWriter;
|
||||
import java.util.Map;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import freemarker.template.Configuration;
|
||||
import freemarker.template.Template;
|
||||
|
||||
public abstract class FreemarkerUtil {
|
||||
protected static final Logger LOG = LoggerFactory.getLogger(FreemarkerUtil.class);
|
||||
|
||||
public static String render(Configuration _config, String _templateName, Map<String, Object>_model) {
|
||||
try {
|
||||
Template temp = _config.getTemplate(_templateName);
|
||||
StringWriter writer = new StringWriter();
|
||||
temp.process(_model, writer);
|
||||
writer.close();
|
||||
return writer.toString();
|
||||
}
|
||||
catch (Exception e) {
|
||||
LOG.error("Failed to render html", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
package com.lanternsoftware.util.servlet;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Date;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Index;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.Lob;
|
||||
import javax.persistence.SequenceGenerator;
|
||||
import javax.persistence.Table;
|
||||
|
||||
import org.apache.commons.io.IOUtils;
|
||||
|
||||
import com.lanternsoftware.util.NullUtils;
|
||||
|
||||
public class SchemaUtils {
|
||||
public static void printStatements(String _sourceCodeFolder) {
|
||||
Map<String, Class<?>> mapClasses = new TreeMap<>();
|
||||
searchFile(new File(_sourceCodeFolder), mapClasses);
|
||||
for (Class<?> c : mapClasses.values()) {
|
||||
System.out.println(SchemaUtils.generateTableCreateStatement(c));
|
||||
System.out.println(SchemaUtils.generateSequenceCreateStatement(c));
|
||||
System.out.println(SchemaUtils.generateIndexCreateStatements(c));
|
||||
}
|
||||
}
|
||||
|
||||
private static void searchFile(File _f, Map<String, Class<?>> _mapClasses) {
|
||||
if (_f == null)
|
||||
return;
|
||||
if (_f.isDirectory()) {
|
||||
for (File child : _f.listFiles()) {
|
||||
searchFile(child, _mapClasses);
|
||||
}
|
||||
}
|
||||
else if (_f.getName().endsWith(".java")) {
|
||||
try {
|
||||
String sSource = IOUtils.toString(new FileInputStream(_f));
|
||||
if (!sSource.contains("@Table"))
|
||||
return;
|
||||
int iPackagePos = sSource.indexOf("package ");
|
||||
int iPackageEnd = sSource.indexOf(";", iPackagePos);
|
||||
String sPackageName = sSource.substring(iPackagePos + 8, iPackageEnd);
|
||||
int iClassPos = sSource.indexOf("public class") + 12;
|
||||
while (sSource.charAt(iClassPos) == ' ')
|
||||
iClassPos++;
|
||||
int iNewLineN = sSource.indexOf("\n", iClassPos);
|
||||
int iNewLineR = sSource.indexOf("\r", iClassPos);
|
||||
int iSpace = sSource.indexOf(" ", iClassPos);
|
||||
int iClassEnd = NullUtils.min((iNewLineN == -1) ? Integer.MAX_VALUE : iNewLineN, (iNewLineR == -1) ? Integer.MAX_VALUE : iNewLineR, (iSpace == -1) ? Integer.MAX_VALUE : iSpace);
|
||||
String sClassName = sSource.substring(iClassPos, iClassEnd);
|
||||
String fullName = sPackageName + "." + sClassName;
|
||||
Class<?> clazz = Class.forName(fullName);
|
||||
if (!clazz.isAnnotationPresent(Table.class))
|
||||
return;
|
||||
_mapClasses.put(fullName, clazz);
|
||||
}
|
||||
catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static String generateTableCreateStatement(Class<?> _entity) {
|
||||
Table table = _entity.getAnnotation(Table.class);
|
||||
if (table == null)
|
||||
return null;
|
||||
StringBuilder sql = new StringBuilder("CREATE TABLE ");
|
||||
sql.append(table.name());
|
||||
sql.append(" (");
|
||||
boolean bFirst = true;
|
||||
for (Field f : _entity.getDeclaredFields()) {
|
||||
String name = null;
|
||||
Column column = f.getAnnotation(Column.class);
|
||||
JoinColumn join = f.getAnnotation(JoinColumn.class);
|
||||
if (column != null)
|
||||
name = column.name();
|
||||
else if (join != null)
|
||||
name = join.name();
|
||||
if (name == null)
|
||||
continue;
|
||||
StringBuilder col = new StringBuilder(name);
|
||||
col.append(" ");
|
||||
if (NullUtils.isOneOf(f.getType(), Byte.TYPE, byte.class))
|
||||
col.append("NUMBER(3,0)");
|
||||
if (NullUtils.isOneOf(f.getType(), Short.TYPE, Short.class))
|
||||
col.append("NUMBER(5,0)");
|
||||
else if (NullUtils.isOneOf(f.getType(), Integer.TYPE, Integer.class))
|
||||
col.append("NUMBER(10,0)");
|
||||
else if (NullUtils.isOneOf(f.getType(), Long.TYPE, Long.class))
|
||||
col.append("NUMBER(19,0)");
|
||||
else if (NullUtils.isOneOf(f.getType(), Double.TYPE, Double.class, Float.TYPE, Float.class))
|
||||
col.append("NUMBER(19,4)");
|
||||
else if (NullUtils.isOneOf(f.getType(), Boolean.TYPE, Boolean.class))
|
||||
col.append("NUMBER(1,0)");
|
||||
else if (f.getType().equals(String.class) || f.getType().isEnum() || (join != null)) {
|
||||
if (f.getAnnotation(Lob.class) != null)
|
||||
col.append("CLOB");
|
||||
else
|
||||
col.append("VARCHAR(255)");
|
||||
}
|
||||
else if (f.getType().equals(Date.class))
|
||||
col.append("TIMESTAMP");
|
||||
else
|
||||
continue;
|
||||
if (f.getAnnotation(Id.class) != null)
|
||||
col.append(" PRIMARY KEY");
|
||||
if (!bFirst)
|
||||
sql.append(",");
|
||||
else
|
||||
bFirst = false;
|
||||
sql.append(col);
|
||||
}
|
||||
sql.append(");");
|
||||
return sql.toString();
|
||||
}
|
||||
|
||||
public static String generateSequenceCreateStatement(Class<?> _entity) {
|
||||
StringBuilder statements = new StringBuilder();
|
||||
for (Field f : _entity.getDeclaredFields()) {
|
||||
SequenceGenerator seq = f.getAnnotation(SequenceGenerator.class);
|
||||
if (seq == null)
|
||||
continue;
|
||||
statements.append("CREATE SEQUENCE \"");
|
||||
statements.append(seq.name());
|
||||
statements.append("\" MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 1000 NOCACHE NOORDER NOCYCLE;\n");
|
||||
}
|
||||
return statements.toString();
|
||||
}
|
||||
|
||||
public static String generateIndexCreateStatements(Class<?> _entity) {
|
||||
Table table = _entity.getAnnotation(Table.class);
|
||||
if (table == null)
|
||||
return null;
|
||||
StringBuilder statements = new StringBuilder();
|
||||
Index[] indexes = table.indexes();
|
||||
if (indexes != null) {
|
||||
for (Index index : indexes) {
|
||||
statements.append("CREATE ");
|
||||
if (index.unique())
|
||||
statements.append("UNIQUE ");
|
||||
statements.append("INDEX \"");
|
||||
statements.append(index.name());
|
||||
statements.append("\" ON \"");
|
||||
statements.append(table.name());
|
||||
statements.append("\" (");
|
||||
statements.append(formatIndexFields(index.columnList()));
|
||||
statements.append(
|
||||
") PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT);\n");
|
||||
}
|
||||
}
|
||||
return statements.toString();
|
||||
}
|
||||
|
||||
private static String formatIndexFields(String _fields) {
|
||||
String[] fields = NullUtils.makeNotNull(_fields).split(",");
|
||||
StringBuilder builder = null;
|
||||
if (fields != null) {
|
||||
for (String field : fields) {
|
||||
if (NullUtils.isEmpty(field))
|
||||
continue;
|
||||
if (builder == null)
|
||||
builder = new StringBuilder();
|
||||
else
|
||||
builder.append(",");
|
||||
builder.append("\"");
|
||||
builder.append(field);
|
||||
builder.append("\"");
|
||||
}
|
||||
}
|
||||
if (builder == null)
|
||||
return "";
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
public static String generateTablespaceCreateStatement(String _name, String _dataFilePath, int _iStartSizeMB, int _iMaxSize) {
|
||||
StringBuilder sql = new StringBuilder("CREATE TABLESPACE ");
|
||||
sql.append(_name.toUpperCase());
|
||||
sql.append(" DATAFILE '");
|
||||
sql.append(_dataFilePath);
|
||||
sql.append("' SIZE ");
|
||||
sql.append(_iStartSizeMB * 1024 * 1024);
|
||||
sql.append(" AUTOEXTEND ON NEXT 1 MAXSIZE ");
|
||||
sql.append(_iMaxSize * 1024 * 1024);
|
||||
sql.append(" BLOCKSIZE 8192 DEFAULT NOCOMPRESS ONLINE EXTENT MANAGEMENT LOCAL AUTOALLOCATE;\n");
|
||||
return sql.toString();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user