提交 e2f5284c authored 作者: Thomas Mueller's avatar Thomas Mueller

Limit line length to 80 characters

上级 81985ba2
......@@ -14,41 +14,62 @@ import java.util.HashMap;
*/
public class HtmlConverter {
private static final HashMap<String, Character> CHAR_MAP = new HashMap<String, Character>();
private static final HashMap<Character, String> CODE_MAP = new HashMap<Character, String>();
private static final HashMap<String, Character> CHAR_MAP =
new HashMap<String, Character>();
private static final HashMap<Character, String> CODE_MAP =
new HashMap<Character, String>();
private static final String[] CHARS = { "quot:34", "amp:38", "lt:60", "gt:62", "nbsp:160", "iexcl:161", "cent:162",
"pound:163", "curren:164", "yen:165", "brvbar:166", "sect:167", "uml:168", "copy:169", "ordf:170",
"laquo:171", "not:172", "shy:173", "reg:174", "macr:175", "deg:176", "plusmn:177", "sup2:178", "sup3:179",
"acute:180", "micro:181", "para:182", "middot:183", "cedil:184", "sup1:185", "ordm:186", "raquo:187",
"frac14:188", "frac12:189", "frac34:190", "iquest:191", "Agrave:192", "Aacute:193", "Acirc:194",
"Atilde:195", "Auml:196", "Aring:197", "AElig:198", "Ccedil:199", "Egrave:200", "Eacute:201", "Ecirc:202",
"Euml:203", "Igrave:204", "Iacute:205", "Icirc:206", "Iuml:207", "ETH:208", "Ntilde:209", "Ograve:210",
"Oacute:211", "Ocirc:212", "Otilde:213", "Ouml:214", "times:215", "Oslash:216", "Ugrave:217", "Uacute:218",
"Ucirc:219", "Uuml:220", "Yacute:221", "THORN:222", "szlig:223", "agrave:224", "aacute:225", "acirc:226",
"atilde:227", "auml:228", "aring:229", "aelig:230", "ccedil:231", "egrave:232", "eacute:233", "ecirc:234",
"euml:235", "igrave:236", "iacute:237", "icirc:238", "iuml:239", "eth:240", "ntilde:241", "ograve:242",
"oacute:243", "ocirc:244", "otilde:245", "ouml:246", "divide:247", "oslash:248", "ugrave:249",
"uacute:250", "ucirc:251", "uuml:252", "yacute:253", "thorn:254", "yuml:255", "Alpha:913", "alpha:945",
"Beta:914", "beta:946", "Gamma:915", "gamma:947", "Delta:916", "delta:948", "Epsilon:917", "epsilon:949",
"Zeta:918", "zeta:950", "Eta:919", "eta:951", "Theta:920", "theta:952", "Iota:921", "iota:953",
"Kappa:922", "kappa:954", "Lambda:923", "lambda:955", "Mu:924", "mu:956", "Nu:925", "nu:957", "Xi:926",
"xi:958", "Omicron:927", "omicron:959", "Pi:928", "pi:960", "Rho:929", "rho:961", "Sigma:931",
"sigmaf:962", "sigma:963", "Tau:932", "tau:964", "Upsilon:933", "upsilon:965", "Phi:934", "phi:966",
"Chi:935", "chi:967", "Psi:936", "psi:968", "Omega:937", "omega:969", "thetasym:977", "upsih:978",
"piv:982", "forall:8704", "part:8706", "exist:8707", "empty:8709", "nabla:8711", "isin:8712", "notin:8713",
"ni:8715", "prod:8719", "sum:8721", "minus:8722", "lowast:8727", "radic:8730", "prop:8733", "infin:8734",
"ang:8736", "and:8743", "or:8744", "cap:8745", "cup:8746", "int:8747", "there4:8756", "sim:8764",
"cong:8773", "asymp:8776", "ne:8800", "equiv:8801", "le:8804", "ge:8805", "sub:8834", "sup:8835",
"nsub:8836", "sube:8838", "supe:8839", "oplus:8853", "otimes:8855", "perp:8869", "sdot:8901", "loz:9674",
"lceil:8968", "rceil:8969", "lfloor:8970", "rfloor:8971", "lang:9001", "rang:9002", "larr:8592",
"uarr:8593", "rarr:8594", "darr:8595", "harr:8596", "crarr:8629", "lArr:8656", "uArr:8657", "rArr:8658",
"dArr:8659", "hArr:8660", "bull:8226", "prime:8242", "oline:8254", "frasl:8260", "weierp:8472",
"image:8465", "real:8476", "trade:8482", "euro:8364", "alefsym:8501", "spades:9824", "clubs:9827",
"hearts:9829", "diams:9830", "ensp:8194", "emsp:8195", "thinsp:8201", "zwnj:8204", "zwj:8205", "lrm:8206",
"rlm:8207", "ndash:8211", "mdash:8212", "lsquo:8216", "rsquo:8217", "sbquo:8218", "ldquo:8220",
"rdquo:8221", "bdquo:8222", "dagger:8224", "Dagger:8225", "hellip:8230", "permil:8240", "lsaquo:8249",
"rsaquo:8250" };
private static final String[] CHARS = { "quot:34", "amp:38", "lt:60",
"gt:62", "nbsp:160", "iexcl:161", "cent:162", "pound:163",
"curren:164", "yen:165", "brvbar:166", "sect:167", "uml:168",
"copy:169", "ordf:170", "laquo:171", "not:172", "shy:173",
"reg:174", "macr:175", "deg:176", "plusmn:177", "sup2:178",
"sup3:179", "acute:180", "micro:181", "para:182", "middot:183",
"cedil:184", "sup1:185", "ordm:186", "raquo:187", "frac14:188",
"frac12:189", "frac34:190", "iquest:191", "Agrave:192",
"Aacute:193", "Acirc:194", "Atilde:195", "Auml:196", "Aring:197",
"AElig:198", "Ccedil:199", "Egrave:200", "Eacute:201", "Ecirc:202",
"Euml:203", "Igrave:204", "Iacute:205", "Icirc:206", "Iuml:207",
"ETH:208", "Ntilde:209", "Ograve:210", "Oacute:211", "Ocirc:212",
"Otilde:213", "Ouml:214", "times:215", "Oslash:216", "Ugrave:217",
"Uacute:218", "Ucirc:219", "Uuml:220", "Yacute:221", "THORN:222",
"szlig:223", "agrave:224", "aacute:225", "acirc:226", "atilde:227",
"auml:228", "aring:229", "aelig:230", "ccedil:231", "egrave:232",
"eacute:233", "ecirc:234", "euml:235", "igrave:236", "iacute:237",
"icirc:238", "iuml:239", "eth:240", "ntilde:241", "ograve:242",
"oacute:243", "ocirc:244", "otilde:245", "ouml:246", "divide:247",
"oslash:248", "ugrave:249", "uacute:250", "ucirc:251", "uuml:252",
"yacute:253", "thorn:254", "yuml:255", "Alpha:913", "alpha:945",
"Beta:914", "beta:946", "Gamma:915", "gamma:947", "Delta:916",
"delta:948", "Epsilon:917", "epsilon:949", "Zeta:918", "zeta:950",
"Eta:919", "eta:951", "Theta:920", "theta:952", "Iota:921",
"iota:953", "Kappa:922", "kappa:954", "Lambda:923", "lambda:955",
"Mu:924", "mu:956", "Nu:925", "nu:957", "Xi:926", "xi:958",
"Omicron:927", "omicron:959", "Pi:928", "pi:960", "Rho:929",
"rho:961", "Sigma:931", "sigmaf:962", "sigma:963", "Tau:932",
"tau:964", "Upsilon:933", "upsilon:965", "Phi:934", "phi:966",
"Chi:935", "chi:967", "Psi:936", "psi:968", "Omega:937",
"omega:969", "thetasym:977", "upsih:978", "piv:982", "forall:8704",
"part:8706", "exist:8707", "empty:8709", "nabla:8711", "isin:8712",
"notin:8713", "ni:8715", "prod:8719", "sum:8721", "minus:8722",
"lowast:8727", "radic:8730", "prop:8733", "infin:8734", "ang:8736",
"and:8743", "or:8744", "cap:8745", "cup:8746", "int:8747",
"there4:8756", "sim:8764", "cong:8773", "asymp:8776", "ne:8800",
"equiv:8801", "le:8804", "ge:8805", "sub:8834", "sup:8835",
"nsub:8836", "sube:8838", "supe:8839", "oplus:8853", "otimes:8855",
"perp:8869", "sdot:8901", "loz:9674", "lceil:8968", "rceil:8969",
"lfloor:8970", "rfloor:8971", "lang:9001", "rang:9002",
"larr:8592", "uarr:8593", "rarr:8594", "darr:8595", "harr:8596",
"crarr:8629", "lArr:8656", "uArr:8657", "rArr:8658", "dArr:8659",
"hArr:8660", "bull:8226", "prime:8242", "oline:8254", "frasl:8260",
"weierp:8472", "image:8465", "real:8476", "trade:8482",
"euro:8364", "alefsym:8501", "spades:9824", "clubs:9827",
"hearts:9829", "diams:9830", "ensp:8194", "emsp:8195",
"thinsp:8201", "zwnj:8204", "zwj:8205", "lrm:8206", "rlm:8207",
"ndash:8211", "mdash:8212", "lsquo:8216", "rsquo:8217",
"sbquo:8218", "ldquo:8220", "rdquo:8221", "bdquo:8222",
"dagger:8224", "Dagger:8225", "hellip:8230", "permil:8240",
"lsaquo:8249", "rsaquo:8250" };
private HtmlConverter() {
// utility class
......
......@@ -73,16 +73,20 @@ public class Indexer {
File file = new File(dir);
setNoIndex("index.html", "html/header.html", "html/search.html",
"html/frame.html", "html/fragments.html",
"html/sourceError.html", "html/source.html", "html/mainWeb.html",
"javadoc/index.html", "javadoc/classes.html", "javadoc/allclasses-frame.html",
"javadoc/allclasses-noframe.html", "javadoc/constant-values.html", "javadoc/overview-frame.html",
"html/sourceError.html", "html/source.html",
"html/mainWeb.html", "javadoc/index.html",
"javadoc/classes.html", "javadoc/allclasses-frame.html",
"javadoc/allclasses-noframe.html",
"javadoc/constant-values.html", "javadoc/overview-frame.html",
"javadoc/overview-summary.html", "javadoc/serialized-form.html");
output = new PrintWriter(new FileWriter(destDir + "/index.js"));
readPages("", file, 0);
output.println("var pages=new Array();");
output.println("var ref=new Array();");
output.println("var ignored='';");
output.println("function Page(title, file) { this.title=title; this.file=file; }");
output.println("function Page(title, file) { ");
output.println(" this.title=title; this.file=file;");
output.println("}");
output.println("function load() {");
sortWords();
removeOverflowRelations();
......@@ -174,8 +178,8 @@ public class Indexer {
private void listPages() {
for (Page p : pages) {
output.println("pages[" + p.id + "]=new Page('" + convertUTF(p.title) + "', '" + p.fileName
+ "');");
output.println("pages[" + p.id + "]=new Page('"
+ convertUTF(p.title) + "', '" + p.fileName + "');");
}
}
......@@ -333,7 +337,8 @@ public class Indexer {
}
// this list of constants needs to be the same in search.js
// (char) 160: nbsp
StringTokenizer t = new StringTokenizer(text, " \t\r\n\"'.,:;!&/\\?%@`[]{}()+-=<>|*^~#$" + (char) 160, false);
StringTokenizer t = new StringTokenizer(text,
" \t\r\n\"'.,:;!&/\\?%@`[]{}()+-=<>|*^~#$" + (char) 160, false);
while (t.hasMoreTokens()) {
String token = t.nextToken();
if (token.length() < MIN_WORD_SIZE) {
......
......@@ -84,11 +84,14 @@ public class CacheLIRS<K, V> extends AbstractMap<K, V> {
* of the stack before the current item is moved
*/
@SuppressWarnings("unchecked")
public CacheLIRS(long maxMemory, int averageMemory, int segmentCount, int stackMoveDistance) {
public CacheLIRS(long maxMemory, int averageMemory, int segmentCount,
int stackMoveDistance) {
setMaxMemory(maxMemory);
setAverageMemory(averageMemory);
if (Integer.bitCount(segmentCount) != 1) {
throw new IllegalArgumentException("The segment count must be a power of 2, is " + segmentCount);
throw new IllegalArgumentException(
"The segment count must be a power of 2, is "
+ segmentCount);
}
this.segmentCount = segmentCount;
this.segmentMask = segmentCount - 1;
......@@ -513,7 +516,8 @@ public class CacheLIRS<K, V> extends AbstractMap<K, V> {
* @param stackMoveDistance the number of other entries to be moved to
* the top of the stack before moving an entry to the top
*/
Segment(CacheLIRS<K, V> cache, long maxMemory, int averageMemory, int stackMoveDistance) {
Segment(CacheLIRS<K, V> cache, long maxMemory, int averageMemory,
int stackMoveDistance) {
this.cache = cache;
setMaxMemory(maxMemory);
setAverageMemory(averageMemory);
......@@ -589,7 +593,8 @@ public class CacheLIRS<K, V> extends AbstractMap<K, V> {
}
if (e.isHot()) {
if (e != stack.stackNext) {
if (stackMoveDistance == 0 || stackMoveCounter - e.topMove > stackMoveDistance) {
if (stackMoveDistance == 0
|| stackMoveCounter - e.topMove > stackMoveDistance) {
access(key, hash);
}
}
......@@ -612,7 +617,8 @@ public class CacheLIRS<K, V> extends AbstractMap<K, V> {
}
if (e.isHot()) {
if (e != stack.stackNext) {
if (stackMoveDistance == 0 || stackMoveCounter - e.topMove > stackMoveDistance) {
if (stackMoveDistance == 0
|| stackMoveCounter - e.topMove > stackMoveDistance) {
// move a hot entry to the top of the stack
// unless it is already there
boolean wasEnd = e == stack.stackPrev;
......
......@@ -62,11 +62,13 @@ public class FilePathZip2 extends FilePath {
}
@Override
public FilePath createTempFile(String suffix, boolean deleteOnExit, boolean inTempDir) throws IOException {
public FilePath createTempFile(String suffix, boolean deleteOnExit,
boolean inTempDir) throws IOException {
if (!inTempDir) {
throw new IOException("File system is read-only");
}
return new FilePathDisk().getPath(name).createTempFile(suffix, deleteOnExit, true);
return new FilePathDisk().getPath(name).createTempFile(suffix,
deleteOnExit, true);
}
@Override
......@@ -358,7 +360,8 @@ class FileZip2 extends FileBase {
@Override
public int read(ByteBuffer dst) throws IOException {
seek();
int len = in.read(dst.array(), dst.arrayOffset() + dst.position(), dst.remaining());
int len = in.read(dst.array(), dst.arrayOffset() + dst.position(),
dst.remaining());
if (len > 0) {
dst.position(dst.position() + len);
pos += len;
......@@ -421,7 +424,8 @@ class FileZip2 extends FileBase {
}
@Override
public synchronized FileLock tryLock(long position, long size, boolean shared) throws IOException {
public synchronized FileLock tryLock(long position, long size,
boolean shared) throws IOException {
if (shared) {
// cast to FileChannel to avoid JDK 1.7 ambiguity
......
......@@ -334,7 +334,8 @@ public class FileShell extends Tool {
}
}
private static void zip(String zipFileName, String base, ArrayList<String> source) {
private static void zip(String zipFileName, String base,
ArrayList<String> source) {
FileUtils.delete(zipFileName);
OutputStream fileOut = null;
try {
......@@ -388,14 +389,17 @@ public class FileShell extends Tool {
}
String fileName = entry.getName();
// restoring windows backups on linux and vice versa
fileName = fileName.replace('\\', SysProperties.FILE_SEPARATOR.charAt(0));
fileName = fileName.replace('/', SysProperties.FILE_SEPARATOR.charAt(0));
fileName = fileName.replace('\\',
SysProperties.FILE_SEPARATOR.charAt(0));
fileName = fileName.replace('/',
SysProperties.FILE_SEPARATOR.charAt(0));
if (fileName.startsWith(SysProperties.FILE_SEPARATOR)) {
fileName = fileName.substring(1);
}
OutputStream o = null;
try {
o = FileUtils.newOutputStream(targetDir + SysProperties.FILE_SEPARATOR + fileName, false);
o = FileUtils.newOutputStream(targetDir
+ SysProperties.FILE_SEPARATOR + fileName, false);
IOUtils.copy(zipIn, o);
o.close();
} finally {
......@@ -412,7 +416,8 @@ public class FileShell extends Tool {
}
}
private int readFileList(String[] list, int i, ArrayList<String> target, boolean recursive) throws IOException {
private int readFileList(String[] list, int i, ArrayList<String> target,
boolean recursive) throws IOException {
while (i < list.length) {
String c = list[i++];
if (";".equals(c)) {
......@@ -453,23 +458,40 @@ public class FileShell extends Tool {
private void showHelp() {
println("Commands are case sensitive");
println("? or help Display this help");
println("cat <file> Print the contents of the file");
println("cd <dir> Change the directory");
println("chmod -w <file> Make the file read-only");
println("cp <source> <target> Copy a file");
println("head <file> Print the first few lines of the contents");
println("ls [<dir>] Print the directory contents");
println("mkdir <dir> Create a directory (including parent directories)");
println("mv <source> <target> Rename a file or directory");
println("pwd Print the current working directory");
println("rm <file> Remove a file");
println("rm -r <dir> Remove a directory, recursively");
println("rm -rf <dir> Remove a directory, recursively; force");
println("touch <file> Update the last modified date (creates the file)");
println("truncate -s <size> <file> Set the file length");
println("unzip <zip> Extract all files from the zip file");
println("zip [-r] <zip> <files..> Create a zip file (-r to recurse directories)");
println("? or help " +
"Display this help");
println("cat <file> " +
"Print the contents of the file");
println("cd <dir> " +
"Change the directory");
println("chmod -w <file> " +
"Make the file read-only");
println("cp <source> <target> " +
"Copy a file");
println("head <file> " +
"Print the first few lines of the contents");
println("ls [<dir>] " +
"Print the directory contents");
println("mkdir <dir> " +
"Create a directory (including parent directories)");
println("mv <source> <target> " +
"Rename a file or directory");
println("pwd " +
"Print the current working directory");
println("rm <file> " +
"Remove a file");
println("rm -r <dir> " +
"Remove a directory, recursively");
println("rm -rf <dir> " +
"Remove a directory, recursively; force");
println("touch <file> " +
"Update the last modified date (creates the file)");
println("truncate -s <size> <file> " +
"Set the file length");
println("unzip <zip> " +
"Extract all files from the zip file");
println("zip [-r] <zip> <files..> " +
"Create a zip file (-r to recurse directories)");
println("exit Exit");
println("");
}
......
......@@ -68,7 +68,8 @@ public class FtpClient {
if (message != null) {
int idxSpace = message.indexOf(' ');
int idxMinus = message.indexOf('-');
int idx = idxSpace < 0 ? idxMinus : idxMinus < 0 ? idxSpace : Math.min(idxSpace, idxMinus);
int idx = idxSpace < 0 ? idxMinus : idxMinus < 0 ? idxSpace
: Math.min(idxSpace, idxMinus);
if (idx < 0) {
code = 0;
} else {
......@@ -86,7 +87,8 @@ public class FtpClient {
readLine();
}
if (code != expected) {
throw new IOException("Expected: " + expected + " got: " + code + " " + message);
throw new IOException("Expected: " + expected + " got: " + code
+ " " + message);
}
}
......@@ -227,7 +229,8 @@ public class FtpClient {
readCode(226, 227);
int first = message.indexOf('(') + 1;
int last = message.indexOf(')');
String[] address = StringUtils.arraySplit(message.substring(first, last), ',', true);
String[] address = StringUtils.arraySplit(
message.substring(first, last), ',', true);
StatementBuilder buff = new StatementBuilder();
for (int i = 0; i < 4; i++) {
buff.appendExceptFirst(".");
......@@ -273,7 +276,8 @@ public class FtpClient {
* @param out the output stream
* @param restartAt restart at the given position (0 if no restart is required).
*/
void retrieve(String fileName, OutputStream out, long restartAt) throws IOException {
void retrieve(String fileName, OutputStream out, long restartAt)
throws IOException {
passive();
if (restartAt > 0) {
send("REST " + restartAt);
......
......@@ -47,14 +47,16 @@ public class FtpControl extends Thread {
@Override
public void run() {
try {
output = new PrintWriter(new OutputStreamWriter(control.getOutputStream(), Constants.UTF8));
output = new PrintWriter(new OutputStreamWriter(
control.getOutputStream(), Constants.UTF8));
if (stop) {
reply(421, "Too many users");
} else {
reply(220, SERVER_NAME);
// TODO need option to configure the serverIpAddress?
serverIpAddress = control.getLocalAddress().getHostAddress().replace('.', ',');
BufferedReader input = new BufferedReader(new InputStreamReader(control.getInputStream()));
BufferedReader input = new BufferedReader(
new InputStreamReader(control.getInputStream()));
while (!stop) {
String command = null;
try {
......@@ -169,7 +171,9 @@ public class FtpControl extends Thread {
case 'D':
if ("DELE".equals(command)) {
String fileName = getFileName(param);
if (!readonly && FileUtils.exists(fileName) && !FileUtils.isDirectory(fileName) && FileUtils.tryDelete(fileName)) {
if (!readonly && FileUtils.exists(fileName)
&& !FileUtils.isDirectory(fileName)
&& FileUtils.tryDelete(fileName)) {
if (server.getAllowTask() && fileName.endsWith(FtpServer.TASK_SUFFIX)) {
server.stopTask(fileName);
}
......@@ -217,7 +221,8 @@ public class FtpControl extends Thread {
data = new FtpData(server, control.getInetAddress(), dataSocket);
data.start();
int port = dataSocket.getLocalPort();
reply(227, "Passive Mode (" + serverIpAddress + "," + (port >> 8) + "," + (port & 255) + ")");
reply(227, "Passive Mode (" + serverIpAddress + ","
+ (port >> 8) + "," + (port & 255) + ")");
} else if ("PORT".equals(command)) {
String[] list = StringUtils.arraySplit(param, ',', true);
String host = list[0] + "." + list[1] + "." + list[2] + "." + list[3];
......@@ -227,7 +232,8 @@ public class FtpControl extends Thread {
data = new FtpData(server, address, port);
reply(200, "Ok");
} else {
server.trace("Port REJECTED:" + address + " expected:" + control.getInetAddress());
server.trace("Port REJECTED:" + address + " expected:"
+ control.getInetAddress());
reply(550, "Failed");
}
}
......@@ -304,7 +310,8 @@ public class FtpControl extends Thread {
}
} else if ("STOR".equals(command)) {
String fileName = getFileName(param);
if (!readonly && !FileUtils.exists(fileName) || !FileUtils.isDirectory(fileName)) {
if (!readonly && !FileUtils.exists(fileName)
|| !FileUtils.isDirectory(fileName)) {
reply(150, "Starting transfer");
try {
data.receive(fileName);
......@@ -368,7 +375,9 @@ public class FtpControl extends Thread {
private void processRemoveDir(String param) {
String fileName = getFileName(param);
if (!readonly && FileUtils.exists(fileName) && FileUtils.isDirectory(fileName) && FileUtils.tryDelete(fileName)) {
if (!readonly && FileUtils.exists(fileName)
&& FileUtils.isDirectory(fileName)
&& FileUtils.tryDelete(fileName)) {
reply(250, "Ok");
} else {
reply(500, "Failed");
......
......@@ -71,12 +71,16 @@ public class FtpServer extends Tool implements Service {
private int port = DEFAULT_PORT;
private int openConnectionCount;
private final SimpleDateFormat dateFormatNew = new SimpleDateFormat("MMM dd HH:mm", Locale.ENGLISH);
private final SimpleDateFormat dateFormatOld = new SimpleDateFormat("MMM dd yyyy", Locale.ENGLISH);
private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
private final SimpleDateFormat dateFormatNew = new SimpleDateFormat(
"MMM dd HH:mm", Locale.ENGLISH);
private final SimpleDateFormat dateFormatOld = new SimpleDateFormat(
"MMM dd yyyy", Locale.ENGLISH);
private final SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyyMMddHHmmss");
private String root = DEFAULT_ROOT;
private String writeUserName = DEFAULT_WRITE, writePassword = DEFAULT_WRITE_PASSWORD;
private String writeUserName = DEFAULT_WRITE,
writePassword = DEFAULT_WRITE_PASSWORD;
private String readUserName = DEFAULT_READ;
private final HashMap<String, Process> tasks = new HashMap<String, Process>();
......@@ -234,7 +238,9 @@ public class FtpServer extends Tool implements Service {
buff.append(' ');
Date now = new Date(), mod = new Date(FileUtils.lastModified(fileName));
String date;
if (mod.after(now) || Math.abs((now.getTime() - mod.getTime()) / 1000 / 60 / 60 / 24) > 180) {
if (mod.after(now)
|| Math.abs((now.getTime() - mod.getTime()) /
1000 / 60 / 60 / 24) > 180) {
synchronized (dateFormatOld) {
date = dateFormatOld.format(mod);
}
......@@ -296,7 +302,8 @@ public class FtpServer extends Tool implements Service {
String getDirectoryListing(String directory, boolean listDirectories) {
StringBuilder buff = new StringBuilder();
for (String fileName : FileUtils.newDirectoryStream(directory)) {
if (!FileUtils.isDirectory(fileName) || (FileUtils.isDirectory(fileName) && listDirectories)) {
if (!FileUtils.isDirectory(fileName)
|| (FileUtils.isDirectory(fileName) && listDirectories)) {
appendFile(buff, fileName);
}
}
......@@ -311,7 +318,8 @@ public class FtpServer extends Tool implements Service {
* @return true if this user may write
*/
boolean checkUserPasswordWrite(String userName, String password) {
return userName.equals(this.writeUserName) && password.equals(this.writePassword);
return userName.equals(this.writeUserName)
&& password.equals(this.writePassword);
}
/**
......@@ -451,8 +459,10 @@ public class FtpServer extends Tool implements Service {
Properties prop = SortedProperties.loadProperties(path);
String command = prop.getProperty("command");
String outFile = path.substring(0, path.length() - TASK_SUFFIX.length());
String errorFile = root + "/" + prop.getProperty("error", outFile + ".err.txt");
String outputFile = root + "/" + prop.getProperty("output", outFile + ".out.txt");
String errorFile = root + "/"
+ prop.getProperty("error", outFile + ".err.txt");
String outputFile = root + "/"
+ prop.getProperty("output", outFile + ".out.txt");
trace("start process: " + path + " / " + command);
Process p = Runtime.getRuntime().exec(command, null, new File(root));
new StreamRedirect(path, p.getErrorStream(), errorFile).start();
......
......@@ -99,7 +99,8 @@ public class PgTcpRedirect {
}
}
private boolean processClient(InputStream inStream, OutputStream outStream) throws IOException {
private boolean processClient(InputStream inStream,
OutputStream outStream) throws IOException {
DataInputStream dataIn = new DataInputStream(inStream);
ByteArrayOutputStream buff = new ByteArrayOutputStream();
DataOutputStream dataOut = new DataOutputStream(buff);
......@@ -121,7 +122,8 @@ public class PgTcpRedirect {
println("SSLRequest");
} else {
println("StartupMessage");
println(" version " + version + " (" + (version >> 16) + "." + (version & 0xff) + ")");
println(" version " + version + " (" + (version >> 16)
+ "." + (version & 0xff) + ")");
while (true) {
String param = readStringNull(dataIn);
if (param.length() == 0) {
......@@ -266,7 +268,8 @@ public class PgTcpRedirect {
return true;
}
private boolean processServer(InputStream inStream, OutputStream outStream) throws IOException {
private boolean processServer(InputStream inStream,
OutputStream outStream) throws IOException {
DataInputStream dataIn = new DataInputStream(inStream);
ByteArrayOutputStream buff = new ByteArrayOutputStream();
DataOutputStream dataOut = new DataOutputStream(buff);
......@@ -453,7 +456,8 @@ public class PgTcpRedirect {
}
case 'S': {
println("ParameterStatus");
println(" parameter " + readStringNull(dataIn) + " = " + readStringNull(dataIn));
println(" parameter " + readStringNull(dataIn) + " = "
+ readStringNull(dataIn));
break;
}
case '1': {
......@@ -466,7 +470,8 @@ public class PgTcpRedirect {
}
case 'Z': {
println("ReadyForQuery");
println(" status (I:idle, T:transaction, E:failed): " + (char) dataIn.readByte());
println(" status (I:idle, T:transaction, E:failed): "
+ (char) dataIn.readByte());
break;
}
case 'T': {
......
......@@ -49,25 +49,34 @@ public class SecureKeyStoreBuilder {
private static void printKeystore(KeyStore store, String password)
throws KeyStoreException, NoSuchAlgorithmException,
UnrecoverableKeyException, CertificateEncodingException {
System.out.println("KeyStore store = KeyStore.getInstance(\""+store.getType()+"\");");
System.out.println("KeyStore store = KeyStore.getInstance(\""
+ store.getType() + "\");");
System.out.println("store.load(null, password.toCharArray());");
//System.out.println("keystore provider="+store.getProvider().getName());
Enumeration<String> en = store.aliases();
while (en.hasMoreElements()) {
String alias = en.nextElement();
Key key = store.getKey(alias, password.toCharArray());
System.out.println("KeyFactory keyFactory = KeyFactory.getInstance(\"" + key.getAlgorithm() + "\");");
System.out.println(
"KeyFactory keyFactory = KeyFactory.getInstance(\""
+ key.getAlgorithm() + "\");");
System.out.println("store.load(null, password.toCharArray());");
String pkFormat = key.getFormat();
String encoded = StringUtils.convertBytesToHex(key.getEncoded());
System.out.println(pkFormat + "EncodedKeySpec keySpec = new " + pkFormat + "EncodedKeySpec(getBytes(\""
System.out.println(
pkFormat + "EncodedKeySpec keySpec = new "
+ pkFormat + "EncodedKeySpec(getBytes(\""
+ encoded + "\"));");
System.out.println("PrivateKey privateKey = keyFactory.generatePrivate(keySpec);");
System.out.println(
"PrivateKey privateKey = keyFactory.generatePrivate(keySpec);");
System.out.println("Certificate[] certs = {");
for (Certificate cert : store.getCertificateChain(alias)) {
System.out.println(" CertificateFactory.getInstance(\""+cert.getType()+"\").");
System.out.println(
" CertificateFactory.getInstance(\""+cert.getType()+"\").");
String enc = StringUtils.convertBytesToHex(cert.getEncoded());
System.out.println(" generateCertificate(new ByteArrayInputStream(getBytes(\""+enc+"\"))),");
System.out.println(
" generateCertificate(new ByteArrayInputStream(getBytes(\""
+ enc + "\"))),");
// PublicKey pubKey = cert.getPublicKey();
// System.out.println(" pubKey algorithm="+pubKey.getAlgorithm());
// System.out.println(" pubKey format="+pubKey.getFormat());
......@@ -75,7 +84,8 @@ public class SecureKeyStoreBuilder {
// Utils.convertBytesToString(pubKey.getEncoded()));
}
System.out.println("};");
System.out.println("store.setKeyEntry(\""+alias+"\", privateKey, password.toCharArray(), certs);");
System.out.println("store.setKeyEntry(\"" + alias
+ "\", privateKey, password.toCharArray(), certs);");
}
}
......
......@@ -195,7 +195,8 @@ public class InPlaceStableMergeSort<T> {
* @param from2 the index of the first element in the second source array
* @param to2 the index of the last element in the second source array
*/
private void mergeSmall(T[] target, int pos, T[] s1, int from1, int to1, T[] s2, int from2, int to2) {
private void mergeSmall(T[] target, int pos, T[] s1, int from1, int to1,
T[] s2, int from2, int to2) {
T x1 = s1[from1], x2 = s2[from2];
while (true) {
if (comp.compare(x1, x2) <= 0) {
......
......@@ -22,7 +22,8 @@ public class ArrayUtils {
* @param right the index of the rightmost element
* @param comp the comparison class
*/
public static <T> void binaryInsertionSort(T[] d, int left, int right, Comparator<T> comp) {
public static <T> void binaryInsertionSort(T[] d, int left, int right,
Comparator<T> comp) {
for (int i = left + 1; i <= right; i++) {
T t = d[i];
int l = left;
......@@ -50,7 +51,8 @@ public class ArrayUtils {
* @param right the index of the rightmost element
* @param comp the comparison class
*/
public static <T> void insertionSort(T[] d, int left, int right, Comparator<T> comp) {
public static <T> void insertionSort(T[] d, int left, int right,
Comparator<T> comp) {
for (int i = left + 1, j; i <= right; i++) {
T t = d[i];
for (j = i - 1; j >= left && comp.compare(d[j], t) > 0; j--) {
......
......@@ -124,7 +124,8 @@ public class FileViewer extends Tool {
}
}
private static long find(RandomAccessFile file, byte[] find, boolean quiet) throws IOException {
private static long find(RandomAccessFile file, byte[] find, boolean quiet)
throws IOException {
long pos = file.getFilePointer();
long length = file.length();
int bufferSize = 4 * 1024;
......@@ -176,7 +177,8 @@ public class FileViewer extends Tool {
System.out.println("-----------------------------------------------");
}
private static ArrayList<String> readLines(RandomAccessFile file, int maxLines) throws IOException {
private static ArrayList<String> readLines(RandomAccessFile file,
int maxLines) throws IOException {
ArrayList<String> lines = new ArrayList<String>();
ByteArrayOutputStream buff = new ByteArrayOutputStream(100);
boolean lastNewline = false;
......
......@@ -34,8 +34,10 @@ public class Migrate {
private static final String USER = "sa";
private static final String PASSWORD = "sa";
private static final File OLD_H2_FILE = new File("./h2-1.2.127.jar");
private static final String DOWNLOAD_URL = "http://repo2.maven.org/maven2/com/h2database/h2/1.2.127/h2-1.2.127.jar";
private static final String CHECKSUM = "056e784c7cf009483366ab9cd8d21d02fe47031a";
private static final String DOWNLOAD_URL =
"http://repo2.maven.org/maven2/com/h2database/h2/1.2.127/h2-1.2.127.jar";
private static final String CHECKSUM =
"056e784c7cf009483366ab9cd8d21d02fe47031a";
private static final String TEMP_SCRIPT = "backup.sql";
private final PrintStream sysOut = System.out;
private boolean quiet;
......@@ -47,7 +49,8 @@ public class Migrate {
* @throws Exception if conversion fails
*/
public static void main(String... args) throws Exception {
new Migrate().execute(new File(args.length == 1 ? args[0] : "."), true, USER, PASSWORD, false);
new Migrate().execute(new File(args.length == 1 ? args[0] : "."), true,
USER, PASSWORD, false);
}
/**
......@@ -61,7 +64,8 @@ public class Migrate {
* @param runQuiet to run in quiet mode
* @throws Exception if conversion fails
*/
public void execute(File file, boolean recursive, String user, String password, boolean runQuiet) throws Exception {
public void execute(File file, boolean recursive, String user,
String password, boolean runQuiet) throws Exception {
String pathToJavaExe = getJavaExecutablePath();
this.quiet = runQuiet;
if (file.isDirectory() && recursive) {
......@@ -97,9 +101,11 @@ public class Migrate {
private static String getJavaExecutablePath() {
String pathToJava;
if (File.separator.equals("\\")) {
pathToJava = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java.exe";
pathToJava = System.getProperty("java.home") + File.separator
+ "bin" + File.separator + "java.exe";
} else {
pathToJava = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
pathToJava = System.getProperty("java.home") + File.separator
+ "bin" + File.separator + "java";
}
if (!new File(pathToJava).exists()) {
// Fallback to old behaviour
......
......@@ -39,14 +39,15 @@ public class Db {
* doesn't actually hold column tokens, as those are bound to the query
* itself.
*/
private static final Map<Object, Token> TOKENS =
Collections.synchronizedMap(new WeakIdentityHashMap<Object, Token>());
private static final Map<Object, Token> TOKENS = Collections
.synchronizedMap(new WeakIdentityHashMap<Object, Token>());
private final Connection conn;
private final Map<Class<?>, TableDefinition<?>> classMap = New.hashMap();
private final SQLDialect dialect;
private DbUpgrader dbUpgrader = new DefaultDbUpgrader();
private final Set<Class<?>> upgradeChecked = Collections.synchronizedSet(new HashSet<Class<?>>());
private final Set<Class<?>> upgradeChecked = Collections
.synchronizedSet(new HashSet<Class<?>>());
private int todoDocumentNewFeaturesInHtmlFile;
......@@ -74,7 +75,8 @@ public class Db {
public static Db open(String url, String user, String password) {
try {
Connection conn = JdbcUtils.getConnection(null, url, user, password);
Connection conn = JdbcUtils
.getConnection(null, url, user, password);
return new Db(conn);
} catch (SQLException e) {
throw convert(e);
......@@ -148,12 +150,14 @@ public class Db {
// flag as checked immediately because calls are nested.
upgradeChecked.add(dbUpgrader.getClass());
JQDatabase model = dbUpgrader.getClass().getAnnotation(JQDatabase.class);
JQDatabase model = dbUpgrader.getClass().getAnnotation(
JQDatabase.class);
if (model.version() > 0) {
DbVersion v = new DbVersion();
DbVersion dbVersion =
// (SCHEMA="" && TABLE="") == DATABASE
from(v).where(v.schema).is("").and(v.table).is("").selectFirst();
from(v).where(v.schema).is("").and(v.table).is("")
.selectFirst();
if (dbVersion == null) {
// database has no version registration, but model specifies
// version: insert DbVersion entry and return.
......@@ -186,10 +190,10 @@ public class Db {
if (model.tableVersion > 0) {
// table is using JaQu version tracking.
DbVersion v = new DbVersion();
String schema = StringUtils.isNullOrEmpty(model.schemaName) ? "" : model.schemaName;
DbVersion dbVersion =
from(v).where(v.schema).like(schema).and(v.table)
.like(model.tableName).selectFirst();
String schema = StringUtils.isNullOrEmpty(model.schemaName) ? ""
: model.schemaName;
DbVersion dbVersion = from(v).where(v.schema).like(schema)
.and(v.table).like(model.tableName).selectFirst();
if (dbVersion == null) {
// table has no version registration, but model specifies
// version: insert DbVersion entry
......@@ -204,7 +208,8 @@ public class Db {
&& (dbUpgrader != null)) {
// table is an older version than model
boolean success = dbUpgrader.upgradeTable(this, schema,
model.tableName, dbVersion.version, model.tableVersion);
model.tableName, dbVersion.version,
model.tableVersion);
if (success) {
dbVersion.version = model.tableVersion;
update(dbVersion);
......@@ -227,7 +232,8 @@ public class Db {
Table table = (Table) t;
Define.define(def, table);
} else if (clazz.isAnnotationPresent(JQTable.class)) {
// annotated classes skip the Define().define() static initializer
// annotated classes skip the Define().define() static
// initializer
T t = instance(clazz);
def.mapObject(t);
}
......@@ -293,7 +299,8 @@ public class Db {
PreparedStatement prepare(String sql, boolean returnGeneratedKeys) {
try {
if (returnGeneratedKeys) {
return conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
return conn.prepareStatement(sql,
Statement.RETURN_GENERATED_KEYS);
}
return conn.prepareStatement(sql);
} catch (SQLException e) {
......@@ -337,12 +344,12 @@ public class Db {
}
}
// <X> FieldDefinition<X> getFieldDefinition(X x) {
// return aliasMap.get(x).getFieldDefinition();
// }
//
// <X> SelectColumn<X> getSelectColumn(X x) {
// return aliasMap.get(x);
// }
// <X> FieldDefinition<X> getFieldDefinition(X x) {
// return aliasMap.get(x).getFieldDefinition();
// }
//
// <X> SelectColumn<X> getSelectColumn(X x) {
// return aliasMap.get(x);
// }
}
......@@ -38,7 +38,8 @@ public class DbInspector {
*
* @param dateTimeClass the new class
*/
public void setPreferredDateTimeClass(Class<? extends java.util.Date> dateTimeClass) {
public void setPreferredDateTimeClass(
Class<? extends java.util.Date> dateTimeClass) {
this.dateTimeClass = dateTimeClass;
}
......@@ -80,7 +81,8 @@ public class DbInspector {
* @param throwOnError if errors should cause validation to fail
* @return a list of validation remarks
*/
public <T> List<ValidationRemark> validateModel(T model, boolean throwOnError) {
public <T> List<ValidationRemark> validateModel(T model,
boolean throwOnError) {
try {
TableInspector inspector = getTable(model);
inspector.read(metaData);
......@@ -112,22 +114,24 @@ public class DbInspector {
Class<T> clazz = (Class<T>) model.getClass();
TableDefinition<T> def = db.define(clazz);
boolean forceUpperCase = getMetaData().storesUpperCaseIdentifiers();
String schema = (forceUpperCase && def.schemaName != null) ?
def.schemaName.toUpperCase() : def.schemaName;
String table = forceUpperCase ? def.tableName.toUpperCase() : def.tableName;
String schema = (forceUpperCase && def.schemaName != null) ? def.schemaName
.toUpperCase() : def.schemaName;
String table = forceUpperCase ? def.tableName.toUpperCase()
: def.tableName;
List<TableInspector> tables = getTables(schema, table);
return tables.get(0);
}
/**
* Returns a list of tables. This method always returns at least one element.
* If no table is found, an exception is thrown.
* Returns a list of tables. This method always returns at least one
* element. If no table is found, an exception is thrown.
*
* @param schema the schema name
* @param table the table name
* @return a list of table inspectors (always contains at least one element)
*/
private List<TableInspector> getTables(String schema, String table) throws SQLException {
private List<TableInspector> getTables(String schema, String table)
throws SQLException {
ResultSet rs = null;
try {
rs = getMetaData().getSchemas();
......@@ -137,24 +141,27 @@ public class DbInspector {
}
JdbcUtils.closeSilently(rs);
String jaquTables = DbVersion.class.getAnnotation(JQTable.class).name();
String jaquTables = DbVersion.class.getAnnotation(JQTable.class)
.name();
List<TableInspector> tables = New.arrayList();
if (schemaList.size() == 0) {
schemaList.add(null);
}
for (String s : schemaList) {
rs = getMetaData().getTables(null, s, null, new String[] { "TABLE" });
rs = getMetaData().getTables(null, s, null,
new String[] { "TABLE" });
while (rs.next()) {
String t = rs.getString("TABLE_NAME");
if (!t.equalsIgnoreCase(jaquTables)) {
tables.add(new TableInspector(s, t,
getMetaData().storesUpperCaseIdentifiers(), dateTimeClass));
tables.add(new TableInspector(s, t, getMetaData()
.storesUpperCaseIdentifiers(), dateTimeClass));
}
}
}
if (StringUtils.isNullOrEmpty(schema) && StringUtils.isNullOrEmpty(table)) {
if (StringUtils.isNullOrEmpty(schema)
&& StringUtils.isNullOrEmpty(table)) {
// all schemas and tables
return tables;
}
......@@ -166,9 +173,10 @@ public class DbInspector {
}
}
if (matches.size() == 0) {
throw new RuntimeException(
MessageFormat.format("Failed to find schema={0} table={1}",
schema == null ? "" : schema, table == null ? "" : table));
throw new RuntimeException(MessageFormat.format(
"Failed to find schema={0} table={1}",
schema == null ? "" : schema, table == null ? ""
: table));
}
return matches;
} finally {
......
......@@ -39,7 +39,8 @@ public interface DbUpgrader {
* @return true for successful upgrade. If the upgrade is successful, the
* version registry is automatically updated.
*/
boolean upgradeTable(Db db, String schema, String table, int fromVersion, int toVersion);
boolean upgradeTable(Db db, String schema, String table, int fromVersion,
int toVersion);
/**
* The default database upgrader. It throws runtime exception instead of
......@@ -50,12 +51,15 @@ public interface DbUpgrader {
@Override
public boolean upgradeDatabase(Db db, int fromVersion, int toVersion) {
throw new RuntimeException("Please provide your own DbUpgrader implementation.");
throw new RuntimeException(
"Please provide your own DbUpgrader implementation.");
}
@Override
public boolean upgradeTable(Db db, String schema, String table, int fromVersion, int toVersion) {
throw new RuntimeException("Please provide your own DbUpgrader implementation.");
public boolean upgradeTable(Db db, String schema, String table,
int fromVersion, int toVersion) {
throw new RuntimeException(
"Please provide your own DbUpgrader implementation.");
}
}
......
......@@ -12,7 +12,8 @@ import org.h2.jaqu.Table.JQTable;
/**
* A system table to track database and table versions.
*/
@JQTable(name = "_jq_versions", primaryKey = "schemaName tableName", memoryTable = true)
@JQTable(name = "_jq_versions",
primaryKey = "schemaName tableName", memoryTable = true)
public class DbVersion {
@JQColumn(name = "schemaName", allowNull = false)
......
......@@ -34,12 +34,14 @@ public class Define {
public static void hashIndex(Object column) {
checkInDefine();
currentTableDefinition.addIndex(IndexType.HASH, new Object [] { column });
currentTableDefinition
.addIndex(IndexType.HASH, new Object[] { column });
}
public static void uniqueHashIndex(Object column) {
checkInDefine();
currentTableDefinition.addIndex(IndexType.UNIQUE_HASH, new Object [] { column });
currentTableDefinition.addIndex(IndexType.UNIQUE_HASH,
new Object[] { column });
}
public static void maxLength(Object column, int length) {
......@@ -62,9 +64,10 @@ public class Define {
private static void checkInDefine() {
if (currentTable == null) {
throw new RuntimeException("This method may only be called " +
"from within the define() method, and the define() method " +
"is called by the framework.");
throw new RuntimeException(
"This method may only be called "
+ "from within the define() method, and the define() method "
+ "is called by the framework.");
}
}
......
......@@ -26,7 +26,8 @@ public class ModelUtils {
* The list of supported data types. It is used by the runtime mapping for
* CREATE statements.
*/
private static final Map<Class<?>, String> SUPPORTED_TYPES = new HashMap<Class<?>, String>();
private static final Map<Class<?>, String> SUPPORTED_TYPES =
new HashMap<Class<?>, String>();
static {
Map<Class<?>, String> m = SUPPORTED_TYPES;
......@@ -50,7 +51,8 @@ public class ModelUtils {
* Convert SQL type aliases to the list of supported types.
* This map is used by generation and validation.
*/
private static final Map<String, String> SQL_TYPES = new HashMap<String, String>();
private static final Map<String, String> SQL_TYPES =
new HashMap<String, String>();
static {
Map<String, String> m = SQL_TYPES;
......@@ -99,12 +101,15 @@ public class ModelUtils {
m.put("SMALLDATETIME", "TIMESTAMP");
}
private static final List<String> KEYWORDS = Arrays.asList("abstract", "assert", "boolean", "break", "byte", "case",
"catch", "char", "class", "const", "continue", "default", "do", "double", "else", "enum", "extends",
"final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface",
"long", "native", "new", "package", "private", "protected", "public", "return", "short", "static",
"strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "try", "void",
"volatile", "while", "false", "null", "true");
private static final List<String> KEYWORDS = Arrays.asList("abstract",
"assert", "boolean", "break", "byte", "case", "catch", "char",
"class", "const", "continue", "default", "do", "double", "else",
"enum", "extends", "final", "finally", "float", "for", "goto",
"if", "implements", "import", "instanceof", "int", "interface",
"long", "native", "new", "package", "private", "protected",
"public", "return", "short", "static", "strictfp", "super",
"switch", "synchronized", "this", "throw", "throws", "transient",
"try", "void", "volatile", "while", "false", "null", "true");
private int todoReviewWholeClass;
......
......@@ -31,9 +31,11 @@ public class Query<T> {
private final Db db;
private SelectTable<T> from;
private final ArrayList<Token> conditions = New.arrayList();
private final ArrayList<UpdateColumn> updateColumnDeclarations = New.arrayList();
private final ArrayList<UpdateColumn> updateColumnDeclarations = New
.arrayList();
private final ArrayList<SelectTable<?>> joins = New.arrayList();
private final IdentityHashMap<Object, SelectColumn<T>> aliasMap = ClassUtils.newIdentityHashMap();
private final IdentityHashMap<Object, SelectColumn<T>> aliasMap = ClassUtils
.newIdentityHashMap();
private final ArrayList<OrderExpression<T>> orderByList = New.arrayList();
private Object[] groupByExpressions;
private long limit;
......@@ -46,7 +48,8 @@ public class Query<T> {
@SuppressWarnings("unchecked")
static <T> Query<T> from(Db db, T alias) {
Query<T> query = new Query<T>(db);
TableDefinition<T> def = (TableDefinition<T>) db.define(alias.getClass());
TableDefinition<T> def = (TableDefinition<T>) db.define(alias
.getClass());
query.from = new SelectTable<T>(db, query, alias, false);
def.initSelectObject(query.from, alias, query.aliasMap);
return query;
......@@ -253,7 +256,8 @@ public class Query<T> {
try {
Object obj = f.get(filter);
if (obj == from.getAlias()) {
List<TableDefinition.FieldDefinition> fields = from.getAliasDefinition().getFields();
List<TableDefinition.FieldDefinition> fields = from
.getAliasDefinition().getFields();
String name = f.getName();
for (TableDefinition.FieldDefinition field : fields) {
String n = name + "." + field.field.getName();
......@@ -266,7 +270,8 @@ public class Query<T> {
throw new RuntimeException(e);
}
}
Token filterCode = new ClassReader().decompile(filter, fieldMap, "where");
Token filterCode = new ClassReader().decompile(filter, fieldMap,
"where");
// String filterQuery = filterCode.toString();
conditions.add(filterCode);
return new QueryWhere<T>(this);
......@@ -301,16 +306,16 @@ public class Query<T> {
*/
public Query<T> orderBy(Object... expressions) {
for (Object expr : expressions) {
OrderExpression<T> e =
new OrderExpression<T>(this, expr, false, false, false);
OrderExpression<T> e = new OrderExpression<T>(this, expr, false,
false, false);
addOrderBy(e);
}
return this;
}
public Query<T> orderByDesc(Object expr) {
OrderExpression<T> e =
new OrderExpression<T>(this, expr, true, false, false);
OrderExpression<T> e = new OrderExpression<T>(this, expr, true, false,
false);
addOrderBy(e);
return this;
}
......@@ -410,7 +415,8 @@ public class Query<T> {
*/
@SuppressWarnings("unchecked")
public <U> QueryJoin innerJoin(U alias) {
TableDefinition<T> def = (TableDefinition<T>) db.define(alias.getClass());
TableDefinition<T> def = (TableDefinition<T>) db.define(alias
.getClass());
SelectTable<T> join = new SelectTable(db, this, alias, false);
def.initSelectObject(join, alias, aliasMap);
joins.add(join);
......
......@@ -59,8 +59,8 @@ public interface SQLDialect {
boolean supportsMemoryTables();
/**
* Default implementation of an SQL dialect.
* Designed for an H2 database, and may be suitable for others.
* Default implementation of an SQL dialect. Designed for an H2 database,
* and may be suitable for others.
*/
public static class DefaultSQLDialect implements SQLDialect {
......@@ -78,10 +78,11 @@ public interface SQLDialect {
}
@Override
public String getCreateIndex(String schema, String table, IndexDefinition index) {
public String getCreateIndex(String schema, String table,
IndexDefinition index) {
StatementBuilder buff = new StatementBuilder();
buff.append("CREATE ");
switch(index.type) {
switch (index.type) {
case STANDARD:
break;
case UNIQUE:
......@@ -99,7 +100,7 @@ public interface SQLDialect {
buff.append(" ON ");
buff.append(table);
buff.append("(");
for (String col:index.columnNames) {
for (String col : index.columnNames) {
buff.appendExceptFirst(", ");
buff.append(col);
}
......
......@@ -91,7 +91,8 @@ public class SQLStatement {
}
}
private static void setValue(PreparedStatement prep, int parameterIndex, Object x) {
private static void setValue(PreparedStatement prep, int parameterIndex,
Object x) {
try {
prep.setObject(parameterIndex, x);
} catch (SQLException e) {
......
......@@ -15,7 +15,7 @@ import org.h2.util.New;
*
* @param <T> the table class
*/
class SelectTable <T> {
class SelectTable<T> {
private static int asCounter;
private final Query<T> query;
......@@ -51,7 +51,8 @@ class SelectTable <T> {
void appendSQL(SQLStatement stat) {
if (query.isJoin()) {
stat.appendTable(aliasDef.schemaName, aliasDef.tableName).appendSQL(" AS " + as);
stat.appendTable(aliasDef.schemaName, aliasDef.tableName)
.appendSQL(" AS " + as);
} else {
stat.appendTable(aliasDef.schemaName, aliasDef.tableName);
}
......
......@@ -354,7 +354,8 @@ class TableDefinition<T> {
}
SQLStatement stat = new SQLStatement(db);
StatementBuilder buff = new StatementBuilder("UPDATE ");
buff.append(db.getDialect().getTableName(schemaName, tableName)).append(" SET ");
buff.append(db.getDialect().getTableName(schemaName, tableName))
.append(" SET ");
buff.resetCount();
for (FieldDefinition field : fields) {
......
......@@ -62,6 +62,7 @@ public class TableInspector {
/**
* Tests to see if this TableInspector represents schema.table.
* <p>
*
* @param schema the schema name
* @param table the table name
* @return true if the table matches
......@@ -123,7 +124,8 @@ public class TableInspector {
ColumnInspector col = new ColumnInspector();
col.name = rs.getString("COLUMN_NAME");
col.type = rs.getString("TYPE_NAME");
col.clazz = ModelUtils.getClassForSqlType(col.type, dateTimeClass);
col.clazz = ModelUtils.getClassForSqlType(col.type,
dateTimeClass);
col.size = rs.getInt("COLUMN_SIZE");
col.allowNull = rs.getInt("NULLABLE") == DatabaseMetaData.columnNullable;
col.isAutoIncrement = rs.getBoolean("IS_AUTOINCREMENT");
......@@ -143,15 +145,16 @@ public class TableInspector {
}
/**
* Generates a model (class definition) from this table.
* The model includes indexes, primary keys, default values, maxLengths,
* and allowNull information.
* Generates a model (class definition) from this table. The model includes
* indexes, primary keys, default values, maxLengths, and allowNull
* information.
* <p>
* The caller may optionally set a destination package name, whether or not
* to include the schema name (setting schema can be a problem when using
* the model between databases), and if to automatically trim strings for
* those that have a maximum length.
* <p>
*
* @return a complete model (class definition) for this table as a string
*/
String generateModel(String packageName, boolean annotateSchema,
......@@ -234,14 +237,16 @@ public class TableInspector {
// class declaration
String clazzName = ModelUtils.convertTableToClassName(table);
model.append(MessageFormat.format("public class {0} '{'", clazzName)).append(EOL);
model.append(MessageFormat.format("public class {0} '{'", clazzName))
.append(EOL);
model.append(EOL);
// field declarations
model.append(fields);
// default constructor
model.append("\t" + "public ").append(clazzName).append("() {").append(EOL);
model.append("\t" + "public ").append(clazzName).append("() {")
.append(EOL);
model.append("\t}").append(EOL);
// end of class body
......@@ -253,7 +258,8 @@ public class TableInspector {
/**
* Generates the specified index annotation.
*/
void generateIndexAnnotations(AnnotationBuilder ap, String parameter, IndexType type) {
void generateIndexAnnotations(AnnotationBuilder ap, String parameter,
IndexType type) {
List<IndexInspector> list = getIndexes(type);
if (list.size() == 0) {
// no matching indexes
......@@ -263,7 +269,7 @@ public class TableInspector {
ap.addParameter(parameter, list.get(0).getColumnsString());
} else {
List<String> parameters = New.arrayList();
for (IndexInspector index:list) {
for (IndexInspector index : list) {
parameters.add(index.getColumnsString());
}
ap.addParameter(parameter, parameters);
......@@ -273,7 +279,7 @@ public class TableInspector {
private List<IndexInspector> getIndexes(IndexType type) {
List<IndexInspector> list = New.arrayList();
for (IndexInspector index:indexes.values()) {
for (IndexInspector index : indexes.values()) {
if (index.type.equals(type)) {
list.add(index);
}
......@@ -281,11 +287,12 @@ public class TableInspector {
return list;
}
private StatementBuilder generateColumn(Set<String> imports, ColumnInspector col,
boolean trimStrings) {
private StatementBuilder generateColumn(Set<String> imports,
ColumnInspector col, boolean trimStrings) {
StatementBuilder sb = new StatementBuilder();
Class<?> clazz = col.clazz;
String column = ModelUtils.convertColumnToFieldName(col.name.toLowerCase());
String column = ModelUtils.convertColumnToFieldName(col.name
.toLowerCase());
sb.append('\t');
if (clazz == null) {
// unsupported type
......@@ -375,19 +382,26 @@ public class TableInspector {
// model class definition validation
if (!Modifier.isPublic(def.getModelClass().getModifiers())) {
remarks.add(error(table, "SCHEMA",
MessageFormat.format("Class {0} MUST BE PUBLIC!",
def.getModelClass().getCanonicalName())).throwError(throwError));
remarks.add(error(
table,
"SCHEMA",
MessageFormat.format("Class {0} MUST BE PUBLIC!", def
.getModelClass().getCanonicalName())).throwError(
throwError));
}
// Schema Validation
if (!StringUtils.isNullOrEmpty(schema)) {
if (StringUtils.isNullOrEmpty(def.schemaName)) {
remarks.add(consider(table, "SCHEMA",
remarks.add(consider(
table,
"SCHEMA",
MessageFormat.format("@{0}(name={1})",
JQSchema.class.getSimpleName(), schema)));
} else if (!schema.equalsIgnoreCase(def.schemaName)) {
remarks.add(error(table, "SCHEMA",
remarks.add(error(
table,
"SCHEMA",
MessageFormat.format("@{0}(name={1}) != {2}",
JQSchema.class.getSimpleName(), def.schemaName,
schema)).throwError(throwError));
......@@ -407,17 +421,19 @@ public class TableInspector {
}
/**
* Validates an inspected index from the database against the IndexDefinition
* within the TableDefinition.
* Validates an inspected index from the database against the
* IndexDefinition within the TableDefinition.
*/
private <T> void validate(List<ValidationRemark> remarks, TableDefinition<T> def,
IndexInspector index, boolean throwError) {
private <T> void validate(List<ValidationRemark> remarks,
TableDefinition<T> def, IndexInspector index, boolean throwError) {
List<IndexDefinition> defIndexes = def.getIndexes(IndexType.STANDARD);
List<IndexInspector> dbIndexes = getIndexes(IndexType.STANDARD);
if (defIndexes.size() > dbIndexes.size()) {
remarks.add(warn(table, IndexType.STANDARD.name(), "More model indexes than database indexes"));
remarks.add(warn(table, IndexType.STANDARD.name(),
"More model indexes than database indexes"));
} else if (defIndexes.size() < dbIndexes.size()) {
remarks.add(warn(table, IndexType.STANDARD.name(), "Model class is missing indexes"));
remarks.add(warn(table, IndexType.STANDARD.name(),
"Model class is missing indexes"));
}
// TODO complete index validation.
// need to actually compare index types and columns within each index.
......@@ -428,40 +444,50 @@ public class TableInspector {
* existence, supported type, type mapping, default value, defined lengths,
* primary key, autoincrement.
*/
private void validate(List<ValidationRemark> remarks, FieldDefinition fieldDef,
boolean throwError) {
private void validate(List<ValidationRemark> remarks,
FieldDefinition fieldDef, boolean throwError) {
// unknown field
String field = forceUpperCase ?
fieldDef.columnName.toUpperCase() : fieldDef.columnName;
String field = forceUpperCase ? fieldDef.columnName.toUpperCase()
: fieldDef.columnName;
if (!columns.containsKey(field)) {
// unknown column mapping
remarks.add(error(table, fieldDef,
"Does not exist in database!").throwError(throwError));
remarks.add(error(table, fieldDef, "Does not exist in database!")
.throwError(throwError));
return;
}
ColumnInspector col = columns.get(field);
Class<?> fieldClass = fieldDef.field.getType();
Class<?> jdbcClass = ModelUtils.getClassForSqlType(col.type, dateTimeClass);
Class<?> jdbcClass = ModelUtils.getClassForSqlType(col.type,
dateTimeClass);
// supported type check
// JaQu maps to VARCHAR for unsupported types.
if (fieldDef.dataType.equals("VARCHAR")
&& (fieldClass != String.class)) {
remarks.add(error(table, fieldDef,
if (fieldDef.dataType.equals("VARCHAR") && (fieldClass != String.class)) {
remarks.add(error(
table,
fieldDef,
"JaQu does not currently implement support for "
+ fieldClass.getName()).throwError(throwError));
}
// number types
if (!fieldClass.equals(jdbcClass)) {
if (Number.class.isAssignableFrom(fieldClass)) {
remarks.add(warn(table, col,
MessageFormat.format("Precision mismatch: ModelObject={0}, ColumnObject={1}",
fieldClass.getSimpleName(), jdbcClass.getSimpleName())));
remarks.add(warn(
table,
col,
MessageFormat
.format("Precision mismatch: ModelObject={0}, ColumnObject={1}",
fieldClass.getSimpleName(),
jdbcClass.getSimpleName())));
} else {
if (!Date.class.isAssignableFrom(jdbcClass)) {
remarks.add(warn(table, col,
MessageFormat.format("Object Mismatch: ModelObject={0}, ColumnObject={1}",
fieldClass.getSimpleName(), jdbcClass.getSimpleName())));
remarks.add(warn(
table,
col,
MessageFormat
.format("Object Mismatch: ModelObject={0}, ColumnObject={1}",
fieldClass.getSimpleName(),
jdbcClass.getSimpleName())));
}
}
}
......@@ -470,14 +496,14 @@ public class TableInspector {
if (fieldClass == String.class) {
if ((fieldDef.maxLength != col.size)
&& (col.size < Integer.MAX_VALUE)) {
remarks.add(warn(table, col,
MessageFormat.format("{0}.maxLength={1}, ColumnMaxLength={2}",
JQColumn.class.getSimpleName(),
fieldDef.maxLength, col.size)));
remarks.add(warn(table, col, MessageFormat.format(
"{0}.maxLength={1}, ColumnMaxLength={2}",
JQColumn.class.getSimpleName(), fieldDef.maxLength,
col.size)));
}
if (fieldDef.maxLength > 0 && !fieldDef.trimString) {
remarks.add(consider(table, col,
MessageFormat.format("{0}.truncateToMaxLength=true"
remarks.add(consider(table, col, MessageFormat.format(
"{0}.truncateToMaxLength=true"
+ " will prevent RuntimeExceptions on"
+ " INSERT or UPDATE, but will clip data!",
JQColumn.class.getSimpleName())));
......@@ -486,7 +512,8 @@ public class TableInspector {
// numeric autoIncrement
if (fieldDef.isAutoIncrement != col.isAutoIncrement) {
remarks.add(warn(table, col, MessageFormat.format("{0}.isAutoIncrement={1}"
remarks.add(warn(table, col, MessageFormat.format(
"{0}.isAutoIncrement={1}"
+ " while Column autoIncrement={2}",
JQColumn.class.getSimpleName(), fieldDef.isAutoIncrement,
col.isAutoIncrement)));
......@@ -494,8 +521,12 @@ public class TableInspector {
// default value
if (!col.isAutoIncrement && !col.isPrimaryKey) {
// check Model.defaultValue format
if (!ModelUtils.isProperlyFormattedDefaultValue(fieldDef.defaultValue)) {
remarks.add(error(table, col, MessageFormat.format("{0}.defaultValue=\"{1}\""
if (!ModelUtils
.isProperlyFormattedDefaultValue(fieldDef.defaultValue)) {
remarks.add(error(
table,
col,
MessageFormat.format("{0}.defaultValue=\"{1}\""
+ " is improperly formatted!",
JQColumn.class.getSimpleName(),
fieldDef.defaultValue)).throwError(throwError));
......@@ -506,33 +537,35 @@ public class TableInspector {
if (StringUtils.isNullOrEmpty(fieldDef.defaultValue)
&& !StringUtils.isNullOrEmpty(col.defaultValue)) {
// Model.defaultValue is NULL, Column.defaultValue is NOT NULL
remarks.add(warn(table, col, MessageFormat.format("{0}.defaultValue=\"\""
remarks.add(warn(table, col, MessageFormat.format(
"{0}.defaultValue=\"\""
+ " while column default=\"{1}\"",
JQColumn.class.getSimpleName(), col.defaultValue)));
} else if (!StringUtils.isNullOrEmpty(fieldDef.defaultValue)
&& StringUtils.isNullOrEmpty(col.defaultValue)) {
// Column.defaultValue is NULL, Model.defaultValue is NOT NULL
remarks.add(warn(table, col, MessageFormat.format("{0}.defaultValue=\"{1}\""
remarks.add(warn(table, col, MessageFormat.format(
"{0}.defaultValue=\"{1}\""
+ " while column default=\"\"",
JQColumn.class.getSimpleName(), fieldDef.defaultValue)));
} else if (!StringUtils.isNullOrEmpty(fieldDef.defaultValue)
&& !StringUtils.isNullOrEmpty(col.defaultValue)) {
if (!fieldDef.defaultValue.equals(col.defaultValue)) {
// Model.defaultValue != Column.defaultValue
remarks.add(warn(table, col, MessageFormat.format("{0}.defaultValue=\"{1}\""
remarks.add(warn(table, col, MessageFormat.format(
"{0}.defaultValue=\"{1}\""
+ " while column default=\"{2}\"",
JQColumn.class.getSimpleName(), fieldDef.defaultValue,
col.defaultValue)));
JQColumn.class.getSimpleName(),
fieldDef.defaultValue, col.defaultValue)));
}
}
// sanity check Model.defaultValue literal value
if (!ModelUtils.isValidDefaultValue(fieldDef.field.getType(),
fieldDef.defaultValue)) {
remarks.add(error(table, col,
MessageFormat.format("{0}.defaultValue=\"{1}\" is invalid!",
JQColumn.class.getSimpleName(),
fieldDef.defaultValue)));
remarks.add(error(table, col, MessageFormat.format(
"{0}.defaultValue=\"{1}\" is invalid!",
JQColumn.class.getSimpleName(), fieldDef.defaultValue)));
}
}
}
......@@ -611,8 +644,8 @@ public class TableInspector {
}
/**
* Convenience class based on StatementBuilder for creating the
* annotation parameter list.
* Convenience class based on StatementBuilder for creating the annotation
* parameter list.
*/
private static class AnnotationBuilder extends StatementBuilder {
AnnotationBuilder() {
......@@ -633,7 +666,7 @@ public class TableInspector {
@SuppressWarnings("unchecked")
List<Object> list = (List<Object>) value;
StatementBuilder flat = new StatementBuilder();
for (Object o:list) {
for (Object o : list) {
flat.appendExceptFirst(", ");
if (o instanceof String) {
flat.append('\"');
......
......@@ -30,7 +30,8 @@ public class ValidationRemark {
private final String fieldName;
private final String message;
private ValidationRemark(Level level, String table, String type, String message) {
private ValidationRemark(Level level, String table, String type,
String message) {
this.level = level;
this.table = table;
this.fieldType = type;
......@@ -38,7 +39,8 @@ public class ValidationRemark {
this.message = message;
}
private ValidationRemark(Level level, String table, FieldDefinition field, String message) {
private ValidationRemark(Level level, String table, FieldDefinition field,
String message) {
this.level = level;
this.table = table;
this.fieldType = field.dataType;
......@@ -46,7 +48,8 @@ public class ValidationRemark {
this.message = message;
}
private ValidationRemark(Level level, String table, ColumnInspector col, String message) {
private ValidationRemark(Level level, String table, ColumnInspector col,
String message) {
this.level = level;
this.table = table;
this.fieldType = col.type;
......@@ -54,31 +57,38 @@ public class ValidationRemark {
this.message = message;
}
public static ValidationRemark consider(String table, String type, String message) {
public static ValidationRemark consider(String table, String type,
String message) {
return new ValidationRemark(Level.CONSIDER, table, type, message);
}
public static ValidationRemark consider(String table, ColumnInspector col, String message) {
public static ValidationRemark consider(String table, ColumnInspector col,
String message) {
return new ValidationRemark(Level.CONSIDER, table, col, message);
}
public static ValidationRemark warn(String table, ColumnInspector col, String message) {
public static ValidationRemark warn(String table, ColumnInspector col,
String message) {
return new ValidationRemark(Level.WARN, table, col, message);
}
public static ValidationRemark warn(String table, String type, String message) {
public static ValidationRemark warn(String table, String type,
String message) {
return new ValidationRemark(Level.WARN, table, type, message);
}
public static ValidationRemark error(String table, ColumnInspector col, String message) {
public static ValidationRemark error(String table, ColumnInspector col,
String message) {
return new ValidationRemark(Level.ERROR, table, col, message);
}
public static ValidationRemark error(String table, String type, String message) {
public static ValidationRemark error(String table, String type,
String message) {
return new ValidationRemark(Level.ERROR, table, type, message);
}
public static ValidationRemark error(String table, FieldDefinition field, String message) {
public static ValidationRemark error(String table, FieldDefinition field,
String message) {
return new ValidationRemark(Level.ERROR, table, field, message);
}
......
......@@ -44,7 +44,8 @@ public class ClassReader {
}
}
public Token decompile(Object instance, Map<String, Object> fields, String method) {
public Token decompile(Object instance, Map<String, Object> fields,
String method) {
this.fieldMap = fields;
this.convertMethodName = method;
Class<?> clazz = instance.getClass();
......@@ -52,7 +53,9 @@ public class ClassReader {
debug("class name " + className);
ByteArrayOutputStream buff = new ByteArrayOutputStream();
try {
InputStream in = clazz.getClassLoader().getResource(className.replace('.', '/') + ".class").openStream();
InputStream in = clazz.getClassLoader()
.getResource(className.replace('.', '/') + ".class")
.openStream();
while (true) {
int x = in.read();
if (x < 0) {
......@@ -73,7 +76,7 @@ public class ClassReader {
constantPool = new Constant[constantPoolCount];
for (int i = 1; i < constantPoolCount; i++) {
int type = readByte();
switch(type) {
switch (type) {
case 1:
constantPool[i] = ConstantString.get(readString());
break;
......@@ -84,7 +87,8 @@ public class ClassReader {
}
case 4: {
int x = readInt();
constantPool[i] = ConstantNumber.get("" + Float.intBitsToFloat(x), x, Constant.Type.FLOAT);
constantPool[i] = ConstantNumber.get(
"" + Float.intBitsToFloat(x), x, Constant.Type.FLOAT);
break;
}
case 5: {
......@@ -95,38 +99,46 @@ public class ClassReader {
}
case 6: {
long x = readLong();
constantPool[i] = ConstantNumber.get("" + Double.longBitsToDouble(x), x, Constant.Type.DOUBLE);
constantPool[i] = ConstantNumber.get(
"" + Double.longBitsToDouble(x), x,
Constant.Type.DOUBLE);
i++;
break;
}
case 7: {
int x = readShort();
constantPool[i] = ConstantNumber.get(null, x, ConstantNumber.Type.CLASS_REF);
constantPool[i] = ConstantNumber.get(null, x,
ConstantNumber.Type.CLASS_REF);
break;
}
case 8: {
int x = readShort();
constantPool[i] = ConstantNumber.get(null, x, ConstantNumber.Type.STRING_REF);
constantPool[i] = ConstantNumber.get(null, x,
ConstantNumber.Type.STRING_REF);
break;
}
case 9: {
int x = readInt();
constantPool[i] = ConstantNumber.get(null, x, ConstantNumber.Type.FIELD_REF);
constantPool[i] = ConstantNumber.get(null, x,
ConstantNumber.Type.FIELD_REF);
break;
}
case 10: {
int x = readInt();
constantPool[i] = ConstantNumber.get(null, x, ConstantNumber.Type.METHOD_REF);
constantPool[i] = ConstantNumber.get(null, x,
ConstantNumber.Type.METHOD_REF);
break;
}
case 11: {
int x = readInt();
constantPool[i] = ConstantNumber.get(null, x, ConstantNumber.Type.INTERFACE_METHOD_REF);
constantPool[i] = ConstantNumber.get(null, x,
ConstantNumber.Type.INTERFACE_METHOD_REF);
break;
}
case 12: {
int x = readInt();
constantPool[i] = ConstantNumber.get(null, x, ConstantNumber.Type.NAME_AND_TYPE);
constantPool[i] = ConstantNumber.get(null, x,
ConstantNumber.Type.NAME_AND_TYPE);
break;
}
default:
......@@ -160,7 +172,8 @@ public class ClassReader {
int accessFlags = readShort();
int nameIndex = readShort();
int descIndex = readShort();
debug(" " + constantPool[descIndex] + " " + constantPool[nameIndex] + " " + accessFlags);
debug(" " + constantPool[descIndex] + " " + constantPool[nameIndex]
+ " " + accessFlags);
readAttributes();
}
......@@ -1001,7 +1014,8 @@ public class ClassReader {
// break;
case 148: {
Token b = stack.pop(), a = stack.pop();
stack.push(new Function("SIGN", Operation.get(a, Operation.Type.SUBTRACT, b)));
stack.push(new Function("SIGN", Operation.get(a,
Operation.Type.SUBTRACT, b)));
op = "lcmp";
break;
}
......@@ -1020,37 +1034,43 @@ public class ClassReader {
case 153:
condition = true;
nextPc = getAbsolutePos(pos, readShort());
stack.push(Operation.get(stack.pop(), Operation.Type.EQUALS, ConstantNumber.get(0)));
stack.push(Operation.get(stack.pop(), Operation.Type.EQUALS,
ConstantNumber.get(0)));
op = "ifeq " + nextPc;
break;
case 154:
condition = true;
nextPc = getAbsolutePos(pos, readShort());
stack.push(Operation.get(stack.pop(), Operation.Type.NOT_EQUALS, ConstantNumber.get(0)));
stack.push(Operation.get(stack.pop(), Operation.Type.NOT_EQUALS,
ConstantNumber.get(0)));
op = "ifne " + nextPc;
break;
case 155:
condition = true;
nextPc = getAbsolutePos(pos, readShort());
stack.push(Operation.get(stack.pop(), Operation.Type.SMALLER, ConstantNumber.get(0)));
stack.push(Operation.get(stack.pop(), Operation.Type.SMALLER,
ConstantNumber.get(0)));
op = "iflt " + nextPc;
break;
case 156:
condition = true;
nextPc = getAbsolutePos(pos, readShort());
stack.push(Operation.get(stack.pop(), Operation.Type.BIGGER_EQUALS, ConstantNumber.get(0)));
stack.push(Operation.get(stack.pop(), Operation.Type.BIGGER_EQUALS,
ConstantNumber.get(0)));
op = "ifge " + nextPc;
break;
case 157:
condition = true;
nextPc = getAbsolutePos(pos, readShort());
stack.push(Operation.get(stack.pop(), Operation.Type.BIGGER, ConstantNumber.get(0)));
stack.push(Operation.get(stack.pop(), Operation.Type.BIGGER,
ConstantNumber.get(0)));
op = "ifgt " + nextPc;
break;
case 158:
condition = true;
nextPc = getAbsolutePos(pos, readShort());
stack.push(Operation.get(stack.pop(), Operation.Type.SMALLER_EQUALS, ConstantNumber.get(0)));
stack.push(Operation.get(stack.pop(),
Operation.Type.SMALLER_EQUALS, ConstantNumber.get(0)));
op = "ifle " + nextPc;
break;
case 159: {
......@@ -1198,7 +1218,10 @@ public class ClassReader {
case 180: {
String field = getField(readShort());
Token p = stack.pop();
String s = p + "." + field.substring(field.lastIndexOf('.') + 1, field.indexOf(' '));
String s = p
+ "."
+ field.substring(field.lastIndexOf('.') + 1,
field.indexOf(' '));
if (s.startsWith("this.")) {
s = s.substring(5);
}
......@@ -1239,7 +1262,8 @@ public class ClassReader {
// break;
// }
case 187: {
String className = constantPool[constantPool[readShort()].intValue()].toString();
String className = constantPool[constantPool[readShort()]
.intValue()].toString();
op = "new " + className;
break;
}
......@@ -1367,9 +1391,9 @@ public class ClassReader {
int field = constantPool[fieldRef].intValue();
int classIndex = field >>> 16;
int nameAndType = constantPool[field & 0xffff].intValue();
String className = constantPool[constantPool[classIndex].intValue()] + "." +
constantPool[nameAndType >>> 16] + " " +
constantPool[nameAndType & 0xffff];
String className = constantPool[constantPool[classIndex].intValue()]
+ "." + constantPool[nameAndType >>> 16] + " "
+ constantPool[nameAndType & 0xffff];
return className;
}
......@@ -1377,9 +1401,9 @@ public class ClassReader {
int method = constantPool[methodRef].intValue();
int classIndex = method >>> 16;
int nameAndType = constantPool[method & 0xffff].intValue();
String className = constantPool[constantPool[classIndex].intValue()] + "." +
constantPool[nameAndType >>> 16] + " " +
constantPool[nameAndType & 0xffff];
String className = constantPool[constantPool[classIndex].intValue()]
+ "." + constantPool[nameAndType >>> 16] + " "
+ constantPool[nameAndType & 0xffff];
return className;
}
......@@ -1409,7 +1433,8 @@ public class ClassReader {
if (x < 0x80) {
chars[j] = (char) x;
} else if (x >= 0xe0) {
chars[j] = (char) (((x & 0xf) << 12) + ((buff[p++] & 0x3f) << 6) + (buff[p++] & 0x3f));
chars[j] = (char) (((x & 0xf) << 12)
+ ((buff[p++] & 0x3f) << 6) + (buff[p++] & 0x3f));
} else {
chars[j] = (char) (((x & 0x1f) << 6) + (buff[p++] & 0x3f));
}
......@@ -1433,7 +1458,8 @@ public class ClassReader {
private int readInt() {
byte[] buff = data;
return (buff[pos++] << 24) + ((buff[pos++] & 0xff) << 16) + ((buff[pos++] & 0xff) << 8) + (buff[pos++] & 0xff);
return (buff[pos++] << 24) + ((buff[pos++] & 0xff) << 16)
+ ((buff[pos++] & 0xff) << 8) + (buff[pos++] & 0xff);
}
private long readLong() {
......
......@@ -93,8 +93,8 @@ public class ClassUtils {
}
}
}
throw new RuntimeException("Exception trying to create " +
clazz.getName() + ": " + e, e);
throw new RuntimeException("Exception trying to create "
+ clazz.getName() + ": " + e, e);
}
}
......@@ -122,7 +122,9 @@ public class ClassUtils {
Reader r = c.getCharacterStream();
return IOUtils.readStringAndClose(r, -1);
} catch (Exception e) {
throw new RuntimeException("Error converting CLOB to String: " + e.toString(), e);
throw new RuntimeException(
"Error converting CLOB to String: " + e.toString(),
e);
}
}
return o.toString();
......@@ -143,8 +145,8 @@ public class ClassUtils {
return n.floatValue();
}
}
throw new RuntimeException("Can not convert the value " + o +
" from " + currentType + " to " + targetType);
throw new RuntimeException("Can not convert the value " + o + " from "
+ currentType + " to " + targetType);
}
@SuppressWarnings("unchecked")
......
......@@ -71,7 +71,8 @@ public class GenerateModels {
try {
annotateSchema = Boolean.parseBoolean(args[++i]);
} catch (Throwable t) {
throw new SQLException("Can not parse -annotateSchema value");
throw new SQLException(
"Can not parse -annotateSchema value");
}
} else if (arg.equals("-trimStrings")) {
try {
......@@ -99,14 +100,14 @@ public class GenerateModels {
* @param schema the schema to read from. null for all schemas.
* @param table the table to model. null for all tables within schema.
* @param packageName the package name of the model classes.
* @param folder destination folder for model classes (package path not included)
* @param folder destination folder for model classes (package path not
* included)
* @param annotateSchema includes the schema in the table model annotations
* @param trimStrings automatically trim strings that exceed maxLength
*/
public static void execute(String url, String user, String password,
String schema, String table, String packageName, String folder,
boolean annotateSchema, boolean trimStrings)
throws SQLException {
boolean annotateSchema, boolean trimStrings) throws SQLException {
Connection conn = null;
try {
org.h2.Driver.load();
......@@ -126,17 +127,21 @@ public class GenerateModels {
for (String model : models) {
Matcher m = p.matcher(model);
if (m.find()) {
String className = m.group().substring("class".length()).trim();
String className = m.group().substring("class".length())
.trim();
File classFile = new File(parentFile, className + ".java");
Writer o = new FileWriter(classFile, false);
PrintWriter writer = new PrintWriter(new BufferedWriter(o));
writer.write(model);
writer.close();
System.out.println("Generated " + classFile.getAbsolutePath());
System.out.println("Generated "
+ classFile.getAbsolutePath());
}
}
} catch (IOException io) {
throw DbException.convertIOException(io, "could not generate model").getSQLException();
throw DbException
.convertIOException(io, "could not generate model")
.getSQLException();
} finally {
JdbcUtils.closeSilently(conn);
}
......@@ -148,14 +153,15 @@ public class GenerateModels {
* @param option the unsupported option
* @return this method never returns normally
*/
protected SQLException throwUnsupportedOption(String option) throws SQLException {
protected SQLException throwUnsupportedOption(String option)
throws SQLException {
showUsage();
throw new SQLException("Unsupported option: " + option);
}
protected void showUsage() {
out.println("GenerateModels");
out.println("Usage: java "+getClass().getName());
out.println("Usage: java " + getClass().getName());
out.println();
out.println("(*) -url jdbc:h2:~test");
out.println(" -user <string>");
......
......@@ -58,17 +58,20 @@ public class ClassObj {
/**
* The per-instance fields.
*/
LinkedHashMap<String, FieldObj> instanceFields = new LinkedHashMap<String, FieldObj>();
LinkedHashMap<String, FieldObj> instanceFields =
new LinkedHashMap<String, FieldObj>();
/**
* The static fields of this class.
*/
LinkedHashMap<String, FieldObj> staticFields = new LinkedHashMap<String, FieldObj>();
LinkedHashMap<String, FieldObj> staticFields =
new LinkedHashMap<String, FieldObj>();
/**
* The methods.
*/
LinkedHashMap<String, ArrayList<MethodObj>> methods = new LinkedHashMap<String, ArrayList<MethodObj>>();
LinkedHashMap<String, ArrayList<MethodObj>> methods =
new LinkedHashMap<String, ArrayList<MethodObj>>();
/**
* The list of native statements.
......@@ -125,6 +128,7 @@ public class ClassObj {
staticFields.put(field.name, field);
}
@Override
public String toString() {
if (isPrimitive) {
return "j" + className;
......@@ -178,10 +182,12 @@ public class ClassObj {
return instanceFields.get(name);
}
@Override
public int hashCode() {
return className.hashCode();
}
@Override
public boolean equals(Object other) {
if (other instanceof ClassObj) {
ClassObj c = (ClassObj) other;
......@@ -240,7 +246,8 @@ class MethodObj {
/**
* The parameter list.
*/
LinkedHashMap<String, FieldObj> parameters = new LinkedHashMap<String, FieldObj>();
LinkedHashMap<String, FieldObj> parameters =
new LinkedHashMap<String, FieldObj>();
/**
* Whether this method is final.
......@@ -262,6 +269,7 @@ class MethodObj {
*/
boolean isConstructor;
@Override
public String toString() {
return name;
}
......@@ -328,6 +336,7 @@ class FieldObj {
*/
ClassObj declaredClass;
@Override
public String toString() {
return name;
}
......@@ -368,6 +377,7 @@ class Type {
return arrayLevel > 0 || !classObj.isPrimitive;
}
@Override
public String toString() {
return asString();
}
......@@ -414,14 +424,17 @@ class Type {
return buff.toString();
}
@Override
public int hashCode() {
return toString().hashCode();
}
@Override
public boolean equals(Object other) {
if (other instanceof Type) {
Type t = (Type) other;
return t.classObj.equals(classObj) && t.arrayLevel == arrayLevel && t.isVarArgs == isVarArgs;
return t.classObj.equals(classObj) && t.arrayLevel == arrayLevel
&& t.isVarArgs == isVarArgs;
}
return false;
}
......
......@@ -30,6 +30,7 @@ public interface Expr {
* The base expression class.
*/
abstract class ExprBase implements Expr {
@Override
public final String toString() {
return "_" + asString() + "_";
}
......@@ -75,6 +76,7 @@ class CallExpr extends ExprBase {
}
}
@Override
public String asString() {
StringBuilder buff = new StringBuilder();
initMethod();
......@@ -112,11 +114,13 @@ class CallExpr extends ExprBase {
return buff.toString();
}
@Override
public Type getType() {
initMethod();
return method.returnType;
}
@Override
public void setType(Type type) {
this.type = type;
}
......@@ -148,15 +152,18 @@ class AssignExpr extends ExprBase {
*/
Type type;
@Override
public String asString() {
right.setType(left.getType());
return left.asString() + " " + op + " " + right.asString();
}
@Override
public Type getType() {
return left.getType();
}
@Override
public void setType(Type type) {
this.type = type;
}
......@@ -183,14 +190,18 @@ class ConditionalExpr extends ExprBase {
*/
Expr ifFalse;
@Override
public String asString() {
return condition.asString() + " ? " + ifTrue.asString() + " : " + ifFalse.asString();
return condition.asString() + " ? " + ifTrue.asString() + " : "
+ ifFalse.asString();
}
@Override
public Type getType() {
return ifTrue.getType();
}
@Override
public void setType(Type type) {
ifTrue.setType(type);
ifFalse.setType(type);
......@@ -217,6 +228,7 @@ class LiteralExpr extends ExprBase {
this.className = className;
}
@Override
public String asString() {
if ("null".equals(literal)) {
Type t = getType();
......@@ -228,6 +240,7 @@ class LiteralExpr extends ExprBase {
return literal;
}
@Override
public Type getType() {
if (type == null) {
type = new Type();
......@@ -236,6 +249,7 @@ class LiteralExpr extends ExprBase {
return type;
}
@Override
public void setType(Type type) {
this.type = type;
}
......@@ -269,6 +283,7 @@ class OpExpr extends ExprBase {
this.context = context;
}
@Override
public String asString() {
if (left == null) {
return op + right.asString();
......@@ -316,6 +331,7 @@ class OpExpr extends ExprBase {
op.equals(">=") || op.equals("<=") || op.equals("!=");
}
@Override
public Type getType() {
if (left == null) {
return right.getType();
......@@ -343,6 +359,7 @@ class OpExpr extends ExprBase {
return lt;
}
@Override
public void setType(Type type) {
this.type = type;
}
......@@ -374,6 +391,7 @@ class NewExpr extends ExprBase {
*/
Type type;
@Override
public String asString() {
boolean refCount = type.refCount;
StringBuilder buff = new StringBuilder();
......@@ -416,6 +434,7 @@ class NewExpr extends ExprBase {
return buff.toString();
}
@Override
public Type getType() {
Type t = new Type();
t.classObj = classObj;
......@@ -423,6 +442,7 @@ class NewExpr extends ExprBase {
return t;
}
@Override
public void setType(Type type) {
this.type = type;
}
......@@ -451,10 +471,12 @@ class StringExpr extends ExprBase {
this.context = context;
}
@Override
public String asString() {
return constantName;
}
@Override
public Type getType() {
if (type == null) {
type = new Type();
......@@ -517,6 +539,7 @@ class StringExpr extends ExprBase {
return buff.toString();
}
@Override
public void setType(Type type) {
// ignore
}
......@@ -550,6 +573,7 @@ class VariableExpr extends ExprBase {
this.context = context;
}
@Override
public String asString() {
init();
StringBuilder buff = new StringBuilder();
......@@ -586,11 +610,13 @@ class VariableExpr extends ExprBase {
}
}
@Override
public Type getType() {
init();
return field.type;
}
@Override
public void setType(Type type) {
this.type = type;
}
......@@ -612,10 +638,12 @@ class ArrayInitExpr extends ExprBase {
*/
Type type;
@Override
public Type getType() {
return type;
}
@Override
public String asString() {
StringBuilder buff = new StringBuilder("{ ");
int i = 0;
......@@ -629,6 +657,7 @@ class ArrayInitExpr extends ExprBase {
return buff.toString();
}
@Override
public void setType(Type type) {
this.type = type;
}
......@@ -650,14 +679,17 @@ class CastExpr extends ExprBase {
*/
Type type;
@Override
public Type getType() {
return type;
}
@Override
public String asString() {
return "(" + type.asString() + ") " + expr.asString();
}
@Override
public void setType(Type type) {
this.type = type;
}
......@@ -684,6 +716,7 @@ class ArrayAccessExpr extends ExprBase {
*/
Type type;
@Override
public Type getType() {
Type t = new Type();
t.classObj = base.getType().classObj;
......@@ -691,10 +724,12 @@ class ArrayAccessExpr extends ExprBase {
return t;
}
@Override
public String asString() {
return base.asString() + "->at(" + index.asString() + ")";
}
@Override
public void setType(Type type) {
this.type = type;
}
......
......@@ -32,7 +32,8 @@ public class JavaParser {
*/
public static final boolean REF_COUNT_STATIC = false;
private static final HashMap<String, ClassObj> BUILT_IN_CLASSES = New.hashMap();
private static final HashMap<String, ClassObj> BUILT_IN_CLASSES = New
.hashMap();
private static final int TOKEN_LITERAL_CHAR = 0;
private static final int TOKEN_LITERAL_STRING = 1;
......@@ -42,7 +43,8 @@ public class JavaParser {
private static final int TOKEN_OTHER = 5;
private static final HashSet<String> RESERVED = New.hashSet();
private static final HashMap<String, String> JAVA_IMPORT_MAP = New.hashMap();
private static final HashMap<String, String> JAVA_IMPORT_MAP = New
.hashMap();
private final ArrayList<ClassObj> allClasses = New.arrayList();
......@@ -57,24 +59,28 @@ public class JavaParser {
private FieldObj thisPointer;
private final HashMap<String, String> importMap = New.hashMap();
private final HashMap<String, ClassObj> classes = New.hashMap();
private final LinkedHashMap<String, FieldObj> localVars = new LinkedHashMap<String, FieldObj>();
private final LinkedHashMap<String, FieldObj> localVars =
new LinkedHashMap<String, FieldObj>();
private final HashMap<String, MethodObj> allMethodsMap = New.hashMap();
private final ArrayList<Statement> nativeHeaders = New.arrayList();
private final HashMap<String, String> stringToStringConstantMap = New.hashMap();
private final HashMap<String, String> stringConstantToStringMap = New.hashMap();
private final HashMap<String, String> stringToStringConstantMap = New
.hashMap();
private final HashMap<String, String> stringConstantToStringMap = New
.hashMap();
public JavaParser() {
addBuiltInTypes();
}
private void addBuiltInTypes() {
String[] list = { "abstract", "continue", "for", "new", "switch", "assert", "default", "if",
"package", "synchronized", "boolean", "do", "goto", "private", "this", "break", "double", "implements",
"protected", "throw", "byte", "else", "import", "public", "throws", "case", "enum", "instanceof",
"return", "transient", "catch", "extends", "int", "short", "try", "char", "final", "interface",
"static", "void", "class", "finally", "long", "strictfp", "volatile", "const", "float", "native",
String[] list = { "abstract", "continue", "for", "new", "switch",
"assert", "default", "if", "package", "synchronized",
"boolean", "do", "goto", "private", "this", "break", "double",
"implements", "protected", "throw", "byte", "else", "import",
"public", "throws", "case", "enum", "instanceof", "return",
"transient", "catch", "extends", "int", "short", "try", "char",
"final", "interface", "static", "void", "class", "finally",
"long", "strictfp", "volatile", "const", "float", "native",
"super", "while", "true", "false", "null" };
for (String s : list) {
RESERVED.add(s);
......@@ -89,9 +95,11 @@ public class JavaParser {
addBuiltInType(id++, true, 6, "long");
addBuiltInType(id++, true, 7, "float");
addBuiltInType(id++, true, 8, "double");
String[] java = { "Boolean", "Byte", "Character", "Class", "ClassLoader", "Double", "Float",
"Integer", "Long", "Math", "Number", "Object", "Runtime", "Short", "String", "StringBuffer",
"StringBuilder", "System", "Thread", "ThreadGroup", "ThreadLocal", "Throwable", "Void" };
String[] java = { "Boolean", "Byte", "Character", "Class",
"ClassLoader", "Double", "Float", "Integer", "Long", "Math",
"Number", "Object", "Runtime", "Short", "String",
"StringBuffer", "StringBuilder", "System", "Thread",
"ThreadGroup", "ThreadLocal", "Throwable", "Void" };
for (String s : java) {
JAVA_IMPORT_MAP.put(s, "java.lang." + s);
addBuiltInType(id++, false, 0, "java.lang." + s);
......@@ -127,7 +135,8 @@ public class JavaParser {
throw new RuntimeException("not a primitive type: " + classObj);
}
private void addBuiltInType(int id, boolean primitive, int primitiveType, String type) {
private void addBuiltInType(int id, boolean primitive, int primitiveType,
String type) {
ClassObj c = new ClassObj();
c.id = id;
c.className = type;
......@@ -169,12 +178,14 @@ public class JavaParser {
readToken();
parseCompilationUnit();
} catch (Exception e) {
throw new RuntimeException(source.substring(0, current.index) + "[*]" + source.substring(current.index), e);
throw new RuntimeException(source.substring(0, current.index)
+ "[*]" + source.substring(current.index), e);
}
}
private static String cleanPackageName(String name) {
if (name.startsWith("org.h2.java.lang") || name.startsWith("org.h2.java.io")) {
if (name.startsWith("org.h2.java.lang")
|| name.startsWith("org.h2.java.io")) {
return name.substring("org.h2.".length());
}
return name;
......@@ -187,7 +198,8 @@ public class JavaParser {
}
while (readIf("import")) {
String importPackageName = cleanPackageName(readQualifiedIdentifier());
String importClass = importPackageName.substring(importPackageName.lastIndexOf('.') + 1);
String importClass = importPackageName.substring(importPackageName
.lastIndexOf('.') + 1);
importMap.put(importClass, importPackageName);
read(";");
}
......@@ -215,7 +227,8 @@ public class JavaParser {
}
classObj.isPublic = isPublic;
classObj.isInterface = isInterface;
classObj.className = packageName == null ? "" : (packageName + ".") + name;
classObj.className = packageName == null ? "" : (packageName + ".")
+ name;
// import this class
importMap.put(name, classObj.className);
addClass(classObj);
......@@ -360,7 +373,8 @@ public class JavaParser {
}
if (readIf("(")) {
if (type.classObj != classObj) {
throw getSyntaxException("Constructor of wrong type: " + type);
throw getSyntaxException("Constructor of wrong type: "
+ type);
}
method.name = "";
method.isConstructor = true;
......@@ -373,7 +387,8 @@ public class JavaParser {
} else {
String name = readIdentifier();
if (name.endsWith("Method")) {
name = name.substring(0, name.length() - "Method".length());
name = name.substring(0,
name.length() - "Method".length());
}
method.name = name;
if (readIf("(")) {
......@@ -518,7 +533,8 @@ public class JavaParser {
} else if (readIf("/*")) {
boolean isC = readIdentifierIf("c");
int start = current.index;
while (source.charAt(current.index) != '*' || source.charAt(current.index + 1) != '/') {
while (source.charAt(current.index) != '*'
|| source.charAt(current.index + 1) != '/') {
current.index++;
}
String s = source.substring(start, current.index).trim();
......@@ -582,7 +598,9 @@ public class JavaParser {
switchStat.setDefaultBlock(block);
while (true) {
block.instructions.add(readStatement());
if (current.token.equals("case") || current.token.equals("default") || current.token.equals("}")) {
if (current.token.equals("case")
|| current.token.equals("default")
|| current.token.equals("}")) {
break;
}
}
......@@ -592,7 +610,9 @@ public class JavaParser {
StatementBlock block = new StatementBlock();
while (true) {
block.instructions.add(readStatement());
if (current.token.equals("case") || current.token.equals("default") || current.token.equals("}")) {
if (current.token.equals("case")
|| current.token.equals("default")
|| current.token.equals("}")) {
break;
}
}
......@@ -699,8 +719,10 @@ public class JavaParser {
private Expr readExpr() {
Expr expr = readExpr1();
String assign = current.token;
if (readIf("=") || readIf("+=") || readIf("-=") || readIf("*=") || readIf("/=") || readIf("&=") || readIf("|=")
|| readIf("^=") || readIf("%=") || readIf("<<=") || readIf(">>=") || readIf(">>>=")) {
if (readIf("=") || readIf("+=") || readIf("-=") || readIf("*=")
|| readIf("/=") || readIf("&=") || readIf("|=") || readIf("^=")
|| readIf("%=") || readIf("<<=") || readIf(">>=")
|| readIf(">>>=")) {
AssignExpr assignOp = new AssignExpr();
assignOp.left = expr;
assignOp.op = assign;
......@@ -914,7 +936,8 @@ public class JavaParser {
return expr;
}
String prefix = current.token;
if (readIf("++") || readIf("--") || readIf("!") || readIf("~") || readIf("+") || readIf("-")) {
if (readIf("++") || readIf("--") || readIf("!") || readIf("~")
|| readIf("+") || readIf("-")) {
OpExpr expr = new OpExpr(this);
expr.op = prefix;
expr.right = readExpr3();
......@@ -1180,7 +1203,8 @@ public class JavaParser {
private String readIdentifier() {
if (current.type != TOKEN_IDENTIFIER) {
throw getSyntaxException("identifier expected, got " + current.token);
throw getSyntaxException("identifier expected, got "
+ current.token);
}
String result = current.token;
readToken();
......@@ -1210,7 +1234,8 @@ public class JavaParser {
}
private RuntimeException getSyntaxException(String message) {
return new RuntimeException(message, new ParseException(source, current.index));
return new RuntimeException(message, new ParseException(source,
current.index));
}
/**
......@@ -1322,7 +1347,9 @@ public class JavaParser {
current.type = TOKEN_IDENTIFIER;
}
return;
} else if (Character.isDigit(ch) || (ch == '.' && Character.isDigit(source.charAt(current.index + 1)))) {
} else if (Character.isDigit(ch)
|| (ch == '.' && Character.isDigit(source
.charAt(current.index + 1)))) {
String s = source.substring(current.index);
current.token = "0" + readNumber(s);
current.index += current.token.length() - 1;
......@@ -1374,17 +1401,20 @@ public class JavaParser {
case '@':
break;
case '.':
if (source.charAt(current.index) == '.' && source.charAt(current.index + 1) == '.') {
if (source.charAt(current.index) == '.'
&& source.charAt(current.index + 1) == '.') {
current.index += 2;
}
break;
case '+':
if (source.charAt(current.index) == '=' || source.charAt(current.index) == '+') {
if (source.charAt(current.index) == '='
|| source.charAt(current.index) == '+') {
current.index++;
}
break;
case '-':
if (source.charAt(current.index) == '=' || source.charAt(current.index) == '-') {
if (source.charAt(current.index) == '='
|| source.charAt(current.index) == '-') {
current.index++;
}
break;
......@@ -1408,7 +1438,8 @@ public class JavaParser {
}
break;
case '/':
if (source.charAt(current.index) == '*' || source.charAt(current.index) == '/'
if (source.charAt(current.index) == '*'
|| source.charAt(current.index) == '/'
|| source.charAt(current.index) == '=') {
current.index++;
}
......@@ -1454,7 +1485,8 @@ public class JavaParser {
i = 2;
while (true) {
char ch = s.charAt(i);
if ((ch < '0' || ch > '9') && (ch < 'a' || ch > 'f') && (ch < 'A' || ch > 'F')) {
if ((ch < '0' || ch > '9') && (ch < 'a' || ch > 'f')
&& (ch < 'A' || ch > 'F')) {
break;
}
i++;
......@@ -1480,7 +1512,8 @@ public class JavaParser {
}
}
if (s.charAt(i) == 'f' || s.charAt(i) == 'F' || s.charAt(i) == 'd'
|| s.charAt(i) == 'D' || s.charAt(i) == 'L' || s.charAt(i) == 'l') {
|| s.charAt(i) == 'D' || s.charAt(i) == 'L'
|| s.charAt(i) == 'l') {
i++;
}
}
......@@ -1529,7 +1562,8 @@ public class JavaParser {
break;
case 'u': {
try {
c = (char) (Integer.parseInt(s.substring(i + 1, i + 5), 16));
c = (char) (Integer.parseInt(s.substring(i + 1, i + 5),
16));
} catch (NumberFormatException e) {
throw getFormatException(s, i);
}
......@@ -1540,7 +1574,8 @@ public class JavaParser {
default:
if (c >= '0' && c <= '9') {
try {
c = (char) (Integer.parseInt(s.substring(i, i + 3), 8));
c = (char) (Integer.parseInt(s.substring(i, i + 3),
8));
} catch (NumberFormatException e) {
throw getFormatException(s, i);
}
......@@ -1636,7 +1671,8 @@ public class JavaParser {
if (m.isConstructor) {
out.print(" " + toC(c.className) + "(");
} else {
out.print(" " + m.returnType.asString() + " " + m.name + "(");
out.print(" " + m.returnType.asString() + " "
+ m.name + "(");
}
int i = 0;
for (FieldObj p : m.parameters.values()) {
......@@ -1652,14 +1688,17 @@ public class JavaParser {
}
out.println("};");
}
ArrayList<String> constantNames = New.arrayList(stringConstantToStringMap.keySet());
ArrayList<String> constantNames = New
.arrayList(stringConstantToStringMap.keySet());
Collections.sort(constantNames);
for (String c : constantNames) {
String s = stringConstantToStringMap.get(c);
if (JavaParser.REF_COUNT_STATIC) {
out.println("ptr<java_lang_String> " + c + " = STRING(L\"" + s + "\");");
out.println("ptr<java_lang_String> " + c + " = STRING(L\"" + s
+ "\");");
} else {
out.println("java_lang_String* " + c + " = STRING(L\"" + s + "\");");
out.println("java_lang_String* " + c + " = STRING(L\"" + s
+ "\");");
}
}
}
......@@ -1694,11 +1733,14 @@ public class JavaParser {
continue;
}
if (m.isStatic) {
out.print(m.returnType.asString() + " " + toC(c.className + "_" + m.name) + "(");
out.print(m.returnType.asString() + " "
+ toC(c.className + "_" + m.name) + "(");
} else if (m.isConstructor) {
out.print(toC(c.className) + "::" + toC(c.className) + "(");
out.print(toC(c.className) + "::" + toC(c.className)
+ "(");
} else {
out.print(m.returnType.asString() + " " + toC(c.className) + "::" + m.name + "(");
out.print(m.returnType.asString() + " "
+ toC(c.className) + "::" + m.name + "(");
}
int i = 0;
for (FieldObj p : m.parameters.values()) {
......
......@@ -30,6 +30,7 @@ public interface Statement {
*/
abstract class StatementBase implements Statement {
@Override
public boolean isEnd() {
return false;
}
......@@ -48,10 +49,12 @@ class ReturnStatement extends StatementBase {
private MethodObj method;
@Override
public void setMethod(MethodObj method) {
this.method = method;
}
@Override
public String asString() {
if (expr == null) {
return "return;";
......@@ -84,10 +87,12 @@ class DoWhileStatement extends StatementBase {
*/
Statement block;
@Override
public void setMethod(MethodObj method) {
block.setMethod(method);
}
@Override
public String asString() {
return "do {\n" + block + "} while (" + condition.asString() + ");";
}
......@@ -99,10 +104,12 @@ class DoWhileStatement extends StatementBase {
*/
class ContinueStatement extends StatementBase {
@Override
public void setMethod(MethodObj method) {
// ignore
}
@Override
public String asString() {
return "continue;";
}
......@@ -114,10 +121,12 @@ class ContinueStatement extends StatementBase {
*/
class BreakStatement extends StatementBase {
@Override
public void setMethod(MethodObj method) {
// ignore
}
@Override
public String asString() {
return "break;";
}
......@@ -129,10 +138,12 @@ class BreakStatement extends StatementBase {
*/
class EmptyStatement extends StatementBase {
@Override
public void setMethod(MethodObj method) {
// ignore
}
@Override
public String asString() {
return ";";
}
......@@ -146,13 +157,15 @@ class SwitchStatement extends StatementBase {
private StatementBlock defaultBlock;
private final ArrayList<Expr> cases = new ArrayList<Expr>();
private final ArrayList<StatementBlock> blocks = new ArrayList<StatementBlock>();
private final ArrayList<StatementBlock> blocks =
new ArrayList<StatementBlock>();
private final Expr expr;
public SwitchStatement(Expr expr) {
this.expr = expr;
}
@Override
public void setMethod(MethodObj method) {
defaultBlock.setMethod(method);
for (StatementBlock b : blocks) {
......@@ -160,6 +173,7 @@ class SwitchStatement extends StatementBase {
}
}
@Override
public String asString() {
StringBuilder buff = new StringBuilder();
buff.append("switch (").append(expr.asString()).append(") {\n");
......@@ -203,10 +217,12 @@ class ExprStatement extends StatementBase {
this.expr = expr;
}
@Override
public void setMethod(MethodObj method) {
// ignore
}
@Override
public String asString() {
return expr.asString() + ";";
}
......@@ -228,10 +244,12 @@ class WhileStatement extends StatementBase {
*/
Statement block;
@Override
public void setMethod(MethodObj method) {
block.setMethod(method);
}
@Override
public String asString() {
String w = "while (" + condition.asString() + ")";
String s = block.toString();
......@@ -260,6 +278,7 @@ class IfStatement extends StatementBase {
*/
Statement elseBlock;
@Override
public void setMethod(MethodObj method) {
block.setMethod(method);
if (elseBlock != null) {
......@@ -267,6 +286,7 @@ class IfStatement extends StatementBase {
}
}
@Override
public String asString() {
String w = "if (" + condition.asString() + ") {\n";
String s = block.asString();
......@@ -318,10 +338,12 @@ class ForStatement extends StatementBase {
*/
Expr iterable;
@Override
public void setMethod(MethodObj method) {
block.setMethod(method);
}
@Override
public String asString() {
StringBuffer buff = new StringBuffer();
buff.append("for (");
......@@ -372,12 +394,14 @@ class StatementBlock extends StatementBase {
*/
final ArrayList<Statement> instructions = new ArrayList<Statement>();
@Override
public void setMethod(MethodObj method) {
for (Statement s : instructions) {
s.setMethod(method);
}
}
@Override
public String asString() {
StringBuilder buff = new StringBuilder();
for (Statement s : instructions) {
......@@ -404,10 +428,12 @@ class VarDecStatement extends StatementBase {
private final ArrayList<String> variables = new ArrayList<String>();
private final ArrayList<Expr> values = new ArrayList<Expr>();
@Override
public void setMethod(MethodObj method) {
// ignore
}
@Override
public String asString() {
StringBuilder buff = new StringBuilder();
buff.append(type.asString()).append(' ');
......@@ -460,14 +486,17 @@ class StatementNative extends StatementBase {
this.code = code;
}
@Override
public void setMethod(MethodObj method) {
// ignore
}
@Override
public String asString() {
return code;
}
@Override
public boolean isEnd() {
return code.equals("return;");
}
......
......@@ -25,6 +25,7 @@ public class Test extends TestBase {
new Test().test();
}
@Override
public void test() throws IOException {
// g++ -o test test.cpp
// chmod +x test
......
......@@ -11,6 +11,7 @@ package org.h2.java.lang;
*/
public class Object {
@Override
public int hashCode() {
return 0;
}
......@@ -19,6 +20,7 @@ public class Object {
return other == this;
}
@Override
public java.lang.String toString() {
return "?";
}
......
......@@ -166,6 +166,7 @@ public class String {
System.arraycopy(chars, offset, this.chars, 0, count);
}
@Override
public int hashCode() {
int h = hash;
if (h == 0) {
......
......@@ -51,6 +51,7 @@ public class StringBuilder {
return this;
}
@Override
public java.lang.String toString() {
return new java.lang.String(buffer, 0, length);
}
......
......@@ -28,7 +28,8 @@ public class System {
* @param destPos the first element in the destination
* @param length the number of element to copy
*/
public static void arraycopy(char[] src, int srcPos, char[] dest, int destPos, int length) {
public static void arraycopy(char[] src, int srcPos, char[] dest,
int destPos, int length) {
/* c:
memmove(((jchar*)dest->getPointer()) + destPos,
((jchar*)src->getPointer()) + srcPos, sizeof(jchar) * length);
......@@ -47,7 +48,8 @@ public class System {
* @param destPos the first element in the destination
* @param length the number of element to copy
*/
public static void arraycopy(byte[] src, int srcPos, byte[] dest, int destPos, int length) {
public static void arraycopy(byte[] src, int srcPos, byte[] dest,
int destPos, int length) {
/* c:
memmove(((jbyte*)dest->getPointer()) + destPos,
((jbyte*)src->getPointer()) + srcPos, sizeof(jbyte) * length);
......
......@@ -79,7 +79,8 @@ public class Railroads {
}
private void map(String key, ResultSet rs, boolean railroads) throws Exception {
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
ArrayList<HashMap<String, String>> list;
list = new ArrayList<HashMap<String, String>>();
while (rs.next()) {
HashMap<String, String> map = new HashMap<String, String>();
ResultSetMetaData meta = rs.getMetaData();
......@@ -119,7 +120,8 @@ public class Railroads {
int div = 3;
int part = (list.size() + div - 1) / div;
for (int i = 0, start = 0; i < div; i++, start += part) {
List<HashMap<String, String>> listThird = list.subList(start, Math.min(start + part, list.size()));
List<HashMap<String, String>> listThird = list.subList(start,
Math.min(start + part, list.size()));
session.put(key + "-" + i, listThird);
}
rs.close();
......
......@@ -113,7 +113,8 @@ public class FunctionsMySQL {
* @return a formatted date/time String in the format "yyyy-MM-dd HH:mm:ss".
*/
public static String fromUnixTime(int seconds) {
SimpleDateFormat formatter = new SimpleDateFormat(DATE_TIME_FORMAT, Locale.ENGLISH);
SimpleDateFormat formatter = new SimpleDateFormat(DATE_TIME_FORMAT,
Locale.ENGLISH);
return formatter.format(new Date(seconds * 1000L));
}
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论