Args
var argsjs = require('component-args.js');
var main = () => {
var args = argsjs.parseDefARGs(['C', 'color']);
println('-C, --color Color');
println('-c, --config file Config')
println();
var isColorOn = args.flg('C', 'color');
var configFile = args.val('c', 'config');
println('-C, --color :' + isColorOn);
println('-c, --config :' + configFile);
};
main();
CMD Line
var System = java.lang.System;
var StandaloneMainInteractive = Packages.me.hatter.tools.jssp.main.StandaloneMainInteractive;
var ConsoleReadTool = Packages.me.hatter.tools.commons.console.ConsoleReadTool;
var main = () => {
StandaloneMainInteractive.initJLine();
ConsoleReadTool.from('cmd> ').loop((ln) => {
var cmd = $STR(ln);
if (cmd == 'exit' || cmd == 'quit') {
println('+ Bye!');
System.exit(0);
}
if (ln != '') {
println(ln);
}
});
};
main();
Component
requireJS('component-helloworld.js');
var main = () => {
println(helloworld());
};
main();
–OR–
var helloworld = require('component-helloworld2.js');
var main = () => {
println(helloworld.sayhello());
};
main();
DataAccess Entity
{
"table": "sample",
"fields": [
{
"name": "id", "pk": true, "type": "int"
},
{
"name": "title", "type": "string"
}
]
}
requireJAR('dataaccess-1.0.jar');
var dataaccessentity = require('component-dataaccessentity.js');
var DataAccessUtil = Packages.me.hatter.tools.dataaccess.util.DataAccessUtil;
var SQLiteDialectImpl = Packages.me.hatter.tools.dataaccess.dialect.impl.SQLiteDialectImpl;
var main = () => {
var files = $$.file('.').listFiles();
var allCreateSQLs = [];
$ARRAY(files).filter((f) => { return f.isFile() && f.getName().endsWith('.entity.json') })
.forEach((f) => {
println('Entity JSON file: ' + f);
var json = $$.rFile(f).string();
var clazz = dataaccessentity.getClass(json);
var createSQL = DataAccessUtil.generateCreateSQL(clazz, new SQLiteDialectImpl());
println('...... ' + clazz);
allCreateSQLs.push(createSQL + ';');
});
println();
if (allCreateSQLs.length == 0) {
println('No Create SQL Generated.');
} else {
println('All Create SQL:');
allCreateSQLs.forEach((sql) => {
println(' ' + sql);
});
}
};
main();
$ runjs generatecreatesql.js
Entity JSON file: ./sample.entity.json
...... class dataaccessentity.Entity_sample_0
All Create SQL:
create table sample ( id INTEGER PRIMARY KEY, title TEXT );
Database
requireJAR('jdbc.sqlite-3.6.7.jar');
requireJAR('dataaccess-1.0.jar');
var DataAccessObjectUtil = Packages.me.hatter.tools.dataaccess.util.DataAccessObjectUtil;
// CREATE TABLE test (id INTEGER, name TEXT, value TEXT);
var main = () => {
var db = $$.file($$.prop('user.home'), 'temp', 'test.db');
var dao = DataAccessObjectUtil.createSqliteObject(db);
println('Inserted: ' + dao.exec("insert into test values(?, ?, ?)", 100, 'bbb', 'xxx'));
var list = dao.simpleQuery().select('id, name, value').from('test').list();
$EACH(list, (e) => {
println(e);
});
};
main();
–OR–
var sqliteda = require('component-sqlitedataaccess-ex.js');
var main = () => {
var db = $$.file('~', 'temp', 'test.db');
var dao = sqliteda.createDAO(db);
var list = dao.simpleQuery().select('id, name, value').from('test').list();
$EACH(list, (e) => {
println(e);
});
};
main();
Excel
requireJAR('poi-3.15.jar');
var FileOutputStream = java.io.FileOutputStream;
var HSSFWorkbook = Packages.org.apache.poi.hssf.usermodel.HSSFWorkbook;
var HSSFSheet = Packages.org.apache.poi.hssf.usermodel.HSSFSheet;
var HSSFRow = Packages.org.apache.poi.hssf.usermodel.HSSFRow;
var HSSFCell = Packages.org.apache.poi.hssf.usermodel.HSSFCell;
var Cell = Packages.org.apache.poi.ss.usermodel.Cell;
var main = () => {
var book = new HSSFWorkbook();
var sheet = book.createSheet('sample sheet');
$EACH($RANGE(0, 20), (r) => {
var row = sheet.createRow(r);
$EACH($RANGE(0, 10), (c) => {
var cell = row.createCell(c);
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue($$.str('' + r + '-' + c));
});
});
var fout = new FileOutputStream('test.xls');
book.write(fout);
fout.close();
};
main();
GnuPG
var main = () => {
var FINGERPRINT = '6FAFC0E0170985AA71545483C794B1646A886CD6';
println('Key ID: ' + FINGERPRINT);
var result = $$.shell().commands('/bin/sh', '-c', 'echo "Hello World!" | gpg -r ' + FINGERPRINT + ' -e -a').start();
var std = result[0].string();
var err = result[1].string();
println('STD OUT:\n' + std);
println('ERR OUT:\n' + err);
var result2 = $$.shell().commands('/bin/sh', '-c', 'echo \'' + std + '\' | gpg').start();
var std2 = result2[0].string();
var err2 = result2[1].string();
println('STD OUT:\n' + std2);
println('ERR OUT:\n' + err2);
};
main();
HTTP Server
var InetSocketAddress = java.net.InetSocketAddress;
var Executors = java.util.concurrent.Executors;
var Bytes = Packages.me.hatter.tools.commons.bytes.Bytes;
var HttpServer = Packages.com.sun.net.httpserver.HttpServer;
var main = () => {
var port = 8080;
var addr = new InetSocketAddress(port);
var httpServer = HttpServer.create(addr, 0);
var httpserverThreads = 2;
httpServer.setExecutor(Executors.newFixedThreadPool(httpserverThreads));
httpServer.createContext("/", (httpExchange) => {
try {
println('Request received: ' + httpExchange.getRequestURI());
var bs = Bytes.from('Hello World.\n').getBytes();
httpExchange.sendResponseHeaders(200, 0);
var responseHeaders = httpExchange.getResponseHeaders();
responseHeaders.set('Content-Type', 'text/plain;charset=UTF-8');
responseHeaders.set('Content-Length', bs.length);
var response = httpExchange.getResponseBody();
response.write(bs);
response.close();
} catch(e) {
println('ERROR: ' + e);
}
});
println("Start listen...");
httpServer.start();
};
main();
–OR–
requireJS('component-httpserver.js');
serveHTTP(8080, (httpExchange) => {
return 'Hello World.';
});
–OR–
var httpserver = require('component-httpserver-ex.js');
httpserver.serveHTTP(8080, (httpExchange) => {
return 'Hello World.';
});
–OR–
var httpserver = require('component-httpserver-ex.js');
httpserver.serveHTTP(8080, (httpExchange) => {
return httpserver.handleFile(httpExchange, { handleDir: true }) || {
status: 404, text: 'Resource not found.' };
});
Swing
var JFrame = javax.swing.JFrame;
var JLabel = javax.swing.JLabel;
var JPanel = javax.swing.JPanel;
var JButton = javax.swing.JButton;
var JTextArea = javax.swing.JTextArea;
var Toolkit = java.awt.Toolkit;
var BorderLayout = java.awt.BorderLayout;
var WindowListener = java.awt.event.WindowListener;
var Proxy = java.lang.reflect.Proxy;
var CountDownLatch = java.util.concurrent.CountDownLatch;
try {
//javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getCrossPlatformLookAndFeelClassName());
} catch (e) { /* IGNORE */ }
function FutureResult() {
this.result = null;
this.countDown = new CountDownLatch(1);
}
FutureResult.prototype.set = (result) => {
this.result = result;
this.countDown.countDown();
};
FutureResult.prototype.get = () => {
this.countDown.await();
return this.result;
};
var showWindow = (title, text, message, editable) => {
var result = new FutureResult();
var f = new JFrame(title || "Hatter's Frame");
f.addWindowListener(Proxy.newProxyInstance(
Proxy.class.getClassLoader(),
[WindowListener.class],
(proxy, method, args) => {
if (method && method.name == "windowClosing") {
f.setVisible(false);
f.dispose();
result.set(null);
}
}
));
var text = new JTextArea(text || "", 30, 80);
text.setEditable(!!editable);
var label = new JLabel(message || "This is default message!");
var btnOK = null;
if (editable) {
btnOK = new JButton("OK!");
btnOK.addActionListener(() => {
var t = text.getText();
f.setVisible(false);
f.dispose();
result.set(t);
});
}
var btnCancel = new JButton("Cancel");
btnCancel.addActionListener(() => {
f.setVisible(false);
f.dispose();
result.set(null);
});
var pane = new JPanel();
if (btnOK != null) {
pane.add(btnOK);
}
pane.add(btnCancel);
f.getContentPane().add(label, BorderLayout.NORTH);
f.getContentPane().add(pane, BorderLayout.SOUTH);
f.getContentPane().add(text, BorderLayout.CENTER);
f.pack();
var dim = Toolkit.getDefaultToolkit().getScreenSize();
f.setLocation((dim.width / 2) - (f.getSize().width / 2), (dim.height / 2) - (f.getSize().height / 2));
f.setVisible(true);
return result;
};
var gpgResult = $$.shell().commands('sh', '-c', 'cat msg.txt.asc | gpg').start();
println(gpgResult[1].rStream().rReader().string());
var msg = gpgResult[0].rStream().rReader().string();
var result = showWindow('Decrypt', msg, 'Message of: msg.txt.asc', true);
println("WAIT!");
println("RESULT: " + result.get());
println("DONE!");
//showWindow().get();
Nashorn
Java.type("int[]");
Java.type('java.util.ArrayList');
var Arrays = Java.type('java.util.Arrays');
var a = Arrays.asList(1, 2, 3, 4);
for each (var e in a) { println(e); }
var System = Java.type('java.lang.System');
System.out.println(10); // 10
System.out["println"](11.0); // 11.0
System.out["println(double)"](12); // 12.0
var Arrays = Java.type('java.util.Arrays');
var a = Arrays.asList(1, 2, 3, 4);
var jsArray = Java.from(list);
var javaArray = Java.to([3, 5, 7, 11], "int[]");
load('script.js');
loadWithNewGlobal('script.js');