File generation with SBT
11 years ago
val maxMemColumn = new TableColumn[MyTableRow, Long]("Max")
maxMemColumn.setCellValueFactory(new PropertyValueFactory[MyTableRow, Long]("maxMem"))
It would be nice to abstract this call, create a template for it.
Looking at the TableColumn API,
another way to bind a cell to an object value is to use setCellValueFactory on the TableColumn:
firstNameCol.setCellValueFactory(new CallbackNote that firstNameProperty is of type ObservableValue. We can therefore remove all the other properties from MyTableRow and just leave the ones which are of type ObservableValue... We are then left with:, ObservableValue >() { public ObservableValue call(CellDataFeatures p) { // p.getValue() returns the Person instance for a particular TableView row return p.getValue().firstNameProperty(); } });
sealed class MyTableRow2 {
val totMem = new SimpleLongProperty(0L)
val maxMem = new SimpleLongProperty(0L)
val freeMem = new SimpleLongProperty(0L)
val usedMem = new SimpleLongProperty(0L)
}
Now, let's try to write a generic create column Scala function (newCol_2 below):
private def newCol_2[R, V](displayName: String, get: (R) => ObservableValue[V]): TableColumn[R, V] = {
val column = new TableColumn[R, V](displayName)
column.setCellValueFactory(new Callback[CellDataFeatures[R, V], ObservableValue[V]] {
override def call(p: CellDataFeatures[R, V]) : ObservableValue[V] = get(p.getValue())
})
column
}
the columns are now initialised like this:
val maxMemColumn = newCol_2("Max", {r:MyTableRow2 => r.maxMem})
val totalMemColumn = newCol_2("Tot", {r:MyTableRow2 => r.totMem})
val freeMemColumn = newCol_2("Free", {r:MyTableRow2 => r.freeMem})
val usedMemColumn = newCol_2("Used", {r:MyTableRow2 => r.usedMem})
import javafx.application.Application import javafx.beans.property.SimpleLongProperty import javafx.beans.property.SimpleObjectProperty import javafx.scene.control.cell.PropertyValueFactory import javafx.scene.control.TableColumn import javafx.scene.control.TableView import javafx.scene.layout.BorderPane import javafx.scene.paint.Color import javafx.scene.Scene import javafx.stage.Stage import javafx.util.Callback import javafx.scene.control.TableCellThen the class representing one line in the table (Note the use of a tuple2 what will later be used for the chart - not really needed as the row can be accessed in the custom renderer - but other posts will follow...):
sealed class MyTableRow {
val totMem = new SimpleLongProperty(0L)
def totMemProperty = totMem
def getTotMem : Long = totMem.get
def setTotMem(value: Long) = totMem.set(value)
val maxMem = new SimpleLongProperty(0L)
def maxMemProperty = maxMem
def getMaxMem : Long = maxMem.get
def setMaxMem(value: Long) = maxMem.set(value)
val freeMem = new SimpleLongProperty(0L)
def freeMemProperty = freeMem
def getFreeMem : Long = freeMem.get
def setFreeMem(value: Long) = freeMem.set(value)
val usedMem = new SimpleLongProperty(0L)
def usedMemProperty = usedMem
def getUsedMem : Long = usedMem.get
def setUsedMem(value: Long) = usedMem.set(value)
val chartData = new SimpleObjectProperty((0L, 0L))
def chartDataProperty = chartData
def getChartData : Tuple2[Long, Long] = chartData.get
def setChartData(value: Tuple2[Long, Long]) = chartData.set(value)
}
Then the main application:
sealed class MemTable extends Application {
def runInJFXThread(f: () => Unit) = javafx.application.Platform.runLater(new Runnable() {def run() {f()}})
val timer = new java.util.Timer
val table = new TableView[MyTableRow]
val tableData = javafx.collections.FXCollections.observableArrayList[MyTableRow]()
table.setItems(tableData)
val singleRow = new MyTableRow
tableData.addAll(singleRow)
override def start(stage: Stage) = {
val borderPane = new BorderPane
val scene = new Scene(borderPane, 400, 300, Color.WHITE)
borderPane.setCenter(table)
setupUI
stage.setTitle("Memory Table")
stage.setScene(scene)
stage.show
timer.schedule(new HeapSnapshotTask, 0L, 1000L)
}
sealed class HeapSnapshotTask extends java.util.TimerTask {
val inKb = 1024L
override def run = {
val r = Runtime.getRuntime
val totalMemory = r.totalMemory / inKb
val freeMemory = r.freeMemory / inKb
val maxMemory = r.maxMemory / inKb
val usedMemory = totalMemory - freeMemory
runInJFXThread{() => {
singleRow.totMem.set(totalMemory)
singleRow.maxMem.set(maxMemory)
singleRow.freeMem.set(freeMemory)
singleRow.usedMem.set(usedMemory)
singleRow.chartData.set((freeMemory, usedMemory))
}}
println("T = " + totalMemory + ", F = " + freeMemory + ", M = " + maxMemory + ", U = " + usedMemory)
}
}
private def setupUI = {
val memColumns = new TableColumn[MyTableRow, AnyRef]("Memory")
val maxMemColumn = new TableColumn[MyTableRow, Long]("Max")
maxMemColumn.setCellValueFactory(new PropertyValueFactory[MyTableRow, Long]("maxMem"))
val totalMemColumn = new TableColumn[MyTableRow, Long]("Total")
totalMemColumn.setCellValueFactory(new PropertyValueFactory[MyTableRow, Long]("totMem"))
val freeMemColumn = new TableColumn[MyTableRow, Long]("Free")
freeMemColumn.setCellValueFactory(new PropertyValueFactory[MyTableRow, Long]("freeMem"))
val usedMemColumn = new TableColumn[MyTableRow, Long]("Used")
usedMemColumn.setCellValueFactory(new PropertyValueFactory[MyTableRow, Long]("usedMem"))
val chartColumn = new TableColumn[MyTableRow, AnyRef]("Chart")
chartColumn.setCellValueFactory(new PropertyValueFactory[MyTableRow, AnyRef]("chartData"))
val chartRenderer = new Callback[TableColumn[MyTableRow, AnyRef], TableCell[MyTableRow, AnyRef]] {
override def call(col : TableColumn[MyTableRow, AnyRef]) : TableCell[MyTableRow, AnyRef] = {
new TableCell[MyTableRow, AnyRef] {
import javafx.scene.chart.PieChart
import javafx.collections.FXCollections
import javafx.scene.layout.Pane
import javafx.scene.control.Label
val usedMemData = new PieChart.Data("Used", 0.0)
val freeMemData = new PieChart.Data("Free", 0.0)
val pieChartData = FXCollections.observableArrayList(usedMemData, freeMemData)
val pieChart = new PieChart(pieChartData)
pieChart.setPrefSize(150, 150)
pieChart.setLabelsVisible(true)
pieChart.setLegendVisible(false)
val borderPane = new BorderPane
val southPane = new Pane
setGraphic(borderPane)
borderPane.setCenter(pieChart)
borderPane.setBottom(southPane)
val southLabel = new Label
southPane.getChildren().addAll(southLabel)
override def updateItem(value : AnyRef, empty : Boolean) = {
val row = getTableRow
if (row != null && value != null) {
val datum = value.asInstanceOf[Tuple2[Long, Long]]
val free = datum._1
val used = datum._2
usedMemData.setPieValue(used)
freeMemData.setPieValue(free)
val desc = "F="+free+" U="+used
southLabel.setText(desc)
} // if
} // updateItem
}
}
} // chartRenderer
chartColumn.setCellFactory(chartRenderer)
memColumns.getColumns().addAll(maxMemColumn, totalMemColumn, freeMemColumn, usedMemColumn)
table.getColumns().addAll(memColumns, chartColumn)
}
}
object MemTable {
def main(args: Array[String]): Unit = {
javafx.application.Application.launch(classOf[MemTable])
}
}
That's it for now
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.sql.DataSource;
interface ICallbackHandler {
void process(ResultSet rs);
}
final class JSqlTemplate {
DataSource ds = null;
public void query(final String sql, final ICallbackHandler cb) throws Exception {
final Connection conn = ds.getConnection();
final Statement stmt = conn.createStatement();
final ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) cb.process(rs);
rs.close();
stmt.close();
conn.close();
}
}
public class DBCallbackTest {
public static void main(String[] args) throws Exception {
new JSqlTemplate().query("select * from whatever", new ICallbackHandler() {
public void process(ResultSet rs) {
// get stuff here
}
});
}
}
In Scala, there is no need to define a ICallbackHandler .. you can just go for:
import javax.sql.DataSource
import java.sql.ResultSet
sealed class SSqlTemplate(dataSource: DataSource) {
def query(sql: String, rowHandler: (ResultSet) => Unit) = {
val conn = dataSource.getConnection
val stmt = conn.createStatement
val rs = stmt.executeQuery(sql)
while (rs.next) rowHandler(rs)
rs.close
stmt.close
conn.close
}
}
object SDbCallback {
def main(args: Array[String]): Unit = {
val ds:DataSource = null
new SSqlTemplate(ds).query("select * from whatever",
{(rs: ResultSet) =>
// get stuff here
})
}
}
import scalaz._
import Scalaz._
object Combi1 {
def combine[A](xs: List[A]): List[List[A]] = xs.replicate[List](xs.size).sequence
def main(args: Array[String]): Unit = {
val list = List(1, 1, 2, 3, 3, 3)
def isCorrect(list: List[Int]) : Boolean = {
list.count(i => i == 1) == 2 &&
list.count(i => i == 2) == 1 &&
list.count(i => i == 3) == 3
}
val combi = combine(list).filter(l => isCorrect(l)).distinct
println(combi.size + " elements")
combi.foreach(l => println(l))
}
}
package org.mychart
import javafx.application.Application
import javafx.scene.control.Label
import javafx.scene.Scene
import javafx.scene.paint.Color
import javafx.scene.layout.BorderPane
import javafx.stage.Stage
import javafx.scene.chart.PieChart
import javafx.collections.FXCollections
import javafx.scene.layout.Pane
sealed class RealtimeMemory extends Application {
val timer = new java.util.Timer
val usedMemData = new PieChart.Data("Used", 0.0)
val freeMemData = new PieChart.Data("Free", 0.0)
// val totalMemData = new PieChart.Data("Total", 0.0)
val pieChartData = FXCollections.observableArrayList(usedMemData, freeMemData)
val chart = new PieChart(pieChartData)
val southPane = new Pane
val southLabel = new Label
override def start(stage: Stage) = {
val borderPane = new BorderPane
val scene = new Scene(borderPane, 800, 600, Color.BEIGE)
stage.setTitle("JFX Xiphias Pricing Client")
stage.setScene(scene)
chart.setLabelsVisible(true)
chart.setLegendVisible(false)
borderPane.setCenter(chart)
borderPane.setBottom(southPane)
southPane.getChildren.addAll(southLabel)
stage.show
timer.schedule(new HeapSnapshotTask, 0L, 1000L)
}
def runInJFXThread(f: () => Unit) =
javafx.application.Platform.runLater( new Runnable() { def run() {f()} } )
sealed class HeapSnapshotTask extends java.util.TimerTask {
override def run = {
val r = Runtime.getRuntime
val totalMemory = r.totalMemory / 1024 / 1024
val freeMemory = r.freeMemory / 1024 / 1024
val maxMemory = r.maxMemory / 1024 / 1024
val usedMemory = totalMemory - freeMemory
usedMemData.setPieValue(usedMemory)
freeMemData.setPieValue(freeMemory)
// totalMemData.setPieValue(totalMemory)
runInJFXThread(()=>southLabel.setText(
"Max: " +maxMemory+", Used:"+usedMemory+
", Free:"+freeMemory+", Total:"+totalMemory))
}
}
}
object RealtimeMemory {
def main(args: Array[String]): Unit = {
javafx.application.Application.launch(classOf[RealtimeMemory])
}
}
package org.oogifu.crypto;
import org.apache.base64.Base64;
import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.BufferedBlockCipher;
import org.bouncycastle.crypto.engines.AESFastEngine;
import org.bouncycastle.crypto.paddings.PKCS7Padding;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.util.Arrays;
public final class BCEncryptionUtils {
private static final BCEncryptionUtils instance = new BCEncryptionUtils();
private transient byte rawKey[] = null;
private BCEncryptionUtils() {
}
public static BCEncryptionUtils getInstance() {
return instance;
}
public String getCipherInfo() {
return "AES-256 provided By Bouncy Castle";
}
public String getFormat() {
return "256";
}
public void setMasterPassword(String password) throws Exception {
final byte[] masterPassword = new byte[32];
Arrays.fill(masterPassword, (byte)0);
if (password.length() > 32) password = password.substring(0, 32);
final byte[] source = password.getBytes();
System.arraycopy(source, 0, masterPassword, 0, source.length);
rawKey = masterPassword;
}
public String decryptFromBase64(final String edata64) throws Exception {
final byte[] edb = Base64.decodeBase64(edata64);
final byte[] data = decode(edb);
return new String(data).trim();
}
public String encryptToBase64(final String data) throws Exception {
final byte[] newData = data.getBytes("UTF-8");
return Base64.encodeBase64String(encode(newData));
}
private byte[] encode(final byte[] inputBytes) throws Exception {
final BufferedBlockCipher cipher = getCipher(true);
final byte[] outputBytes = new byte[cipher.getOutputSize(inputBytes.length)];
int outputLen = cipher.processBytes(inputBytes, 0, inputBytes.length, outputBytes, 0);
outputLen += cipher.doFinal(outputBytes, outputLen);
return outputBytes;
}
private byte[] decode(final byte[] inputBytes) throws Exception {
final BufferedBlockCipher cipher = getCipher(false);
final byte[] outputBytes = new byte[cipher.getOutputSize(inputBytes.length)];
int outputLen = cipher.processBytes(inputBytes, 0, inputBytes.length, outputBytes, 0);
outputLen += cipher.doFinal(outputBytes, outputLen);
return outputBytes;
}
private BufferedBlockCipher getCipher(final boolean forEncryption) {
final BlockCipher aesEngine = new AESFastEngine();
final BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(aesEngine, new PKCS7Padding());
cipher.init(forEncryption, new KeyParameter(rawKey));
return cipher;
}
}