Archive for the ‘java’ Category

Lift: Replacing JavaScript with JVM Applets

Tuesday, May 18th, 2010

Java applets were originally introduced to provide interactive features for web applications (Wikipedia). With javascript based libraries (jquery, yui), proprietary plugins (flash, silverlight or javaFX) and the oncoming HTML5 this intended purpose disappeared, but java applets remain useful for following reasons:

  • Scala/Java is type safe: You can find errors early.
  • You can use the same language like you used for your web application.
  • The Implementation is browser independent.

Example: Distributed Computation of Perfect Numbers

Definition: Perfect Number (Wikipedia)

Testing numbers for perfection is a simple but process-time consuming task. It isn’t complicated to distribute the calculation on several computers.  You can easily think of other domains where similar types of computations could be useful.

Application Overview

Instead of a javascript a java applet is used to factorize numbers. With the typical features of the lift framework, the application looks as follows:

PerfectNumbers Overview

Details: Server -> Client Communication

The snippet: You can deploy your java/scala applet with your web application.


You can invoke your applet method like a javascript function:

// OnLoad(JsRaw("findFactors('"+ c.toJson +"');"))
   OnLoad(JsRaw(c.toJsCall))

Update your case class:

case class JobPackage(ticket: Int,
                   start: Long,
                   end: Long,
                   master: Long) {
  import net.liftweb.json._
  import net.liftweb.json.JsonDSL._
  def toJson = {
    val json = ("ticket" -> ticket) ~
      ("start" -> start) ~
      ("end"-> end) ~
      ("master" -> master)

    compact(JsonAST.render(json))
  }

  def toJsCall = "$('#some-div').html($('#clientEngine').get(0).doCalc(" + ticket
  + ", " + start + ", "+ end +", " + master +"));"

Client -> Server Communication

Add your ajax call to your applet:

JSONObject serverPackage = new JSONObject();
...
private void sendResult() {
		try {
			String sps = serverPackage.toString();
			getAppletContext().showDocument(
					new URL("javascript:replyResult('replyResult', '" + sps + "')"));
		} catch (MalformedURLException e) {
			errorText = "Error: " + e.getMessage();
		}
	}

and dispatch the result:

  def PMCall(s: String) = { 

    logger.info("PMCall "  + s)

    val cResJs = net.liftweb.json.JsonParser.parse(s)
    val ticket  = (cResJs \\ "ticket").extract[Int]

    // With 2.8: facs.extract[List[Long]]
    val facs = for{
      JInt(fac) <- cResJs \\ "factors"
    } yield fac.extract[Long]

    PerfectNumberMaster ! PerfectNumberMaster.CalcDone(ticket , facs)
    Empty
  }

Download and run the example

The Sourcecode is available here.
Type: mvn jetty:run and open the url http://localhost:8080

Configure the Apache Derby DB Network/Client Mode in 5 Minutes

Sunday, May 24th, 2009

It is very easy to use Apache Derby with the embedded JDBC driver. The disadvantage of this solution is that you can only open one connection at a time. If you are developing an application with data persistence, it is often helpful to monitor the database from a different application (e.g. the Data Source Explorer from Eclipse). If you are not interested in reading the administration guide (http://db.apache.org/derby/docs/dev/adminguide/) you can follow these simple steps to configure Derby for Network/Client Mode:

Step  1: Download Apache Derby

Download the bin distribution from: http://db.apache.org/derby/derby_downloads.html

Step 2: Install

Unpack the archive in an appropriate application directory.

Step 3: Create a database directory

For example: mkdir db_storage

Step 4: Set environment variables:

Set DERBY_HOME and add its bin directory to your system path. Also amend your CLATHPATH with the Derby jars.

For example on your mac:

export DERBY_HOME=/Users/.../Programme/db-derby-10.5.1.1-bin

export PATH=$PATH:$DERBY_HOME/bin

export CLASSPATH="$DERBY_HOME/lib/derbynet.jar:$DERBY_HOME/lib/derbytools.jar:\ $DERBY_HOME/lib/derbyclient.jar:$DERBY_HOME/lib/derby.jar:$CLASSPATH"

On Windows systems:

SET CLASSPATH="%DERBY_HOME%/lib/derbynet.jar;%DERBY_HOME%/lib/derbytools.jar;%DERBY_HOME%/lib/derbyclient.jar;%DERBY_HOME%/lib/derby.jar;%DERBY_HOME%;%CLASSPATH%"

(You probably want to put it in a script or batch.)

Step 5: Create the database

Open a terminal/shell/command prompt, change into the database directory (Step3) and start ij.

Type:

connect ‘jdbc:derby:simple;create=true’;
exit;

Step 6: Database Configuration

In your database directory create the file derby.properties.

Add the following lines:

derby.connection.requireAuthentication=TRUE
derby.authentication.provider=BUILTIN
derby.user.alice=mypass

Step 7: Start Derby

Type:

startNetworkServer

on your mac or

startNetworkServer.bat

on your Windows system.

Step 8: Create a user schema and add a table

Open a new terminal/shell/command prompt, change into the database directory  and start ij.

Type:

CONNECT ‘jdbc:derby://localhost:1527/simple’ user ‘alice’ password ‘mypass’;
Create schema alice;

create table dummy (id int primary key, text varchar(20));

insert into dummy values (1, ‘eins’);

insert into dummy values (10, ‘zehn’);

insert into dummy values (100, ‘einhundert’);

exit;

Step 9: Connect from your IDE:

you can now use the derby jdbc network client driver to connect to your database.

connect

Wecker(engl. alarm-clock) on ubuntu

Monday, April 20th, 2009

You can use my small java application “wecker” on Ubuntu.

weckerwithubuntu

You can find it here: http://yousry.de/AppWecker.html.

Memory-Game on Ubuntu

Sunday, April 19th, 2009

You can now play my 3D memory-game on Ubuntu/Linux.

memorygameonubuntu

Make sure you have installed java6 from sun.

You can find it here: http://www.yousry.de/Memory-Game.html

Update: Memory Game

Wednesday, April 15th, 2009

You can find a small bugfix release of the memory-game. Reason was a newly discovered VM coredump under Vista (ogl library conflict).

Update: Verschlüsselung (eng.: Encryption)

Saturday, April 11th, 2009

First results show comparable processing speeds to commercial or proprietary products. A backport to Java5 / Mac was successful. The application may be used on all current desktop operation systems.

Algorithm Windows Mac
SHA1AndDESede
MD5AndTripleDES
SHA1AndRC2_40
MD5AndDES

In subsequent versions, major functional enhancements are planned. The complex user interface will be simplified.

Tasks until alpha release:

  • The user interface must be completed.
  • Software testing.

Tasks until beta release:

  • Add new encryption algorithms.
  • Add simplified user interface.
  • Add server functionality.
  • Batch processing.
  • Create API documentation.