Ozkey Projects

My goal is to make notes of what I learn while actually making something useful in the process. To do this I started two projects:

Photo Album (Web).

I started this project to learn more about the ZK framework. Once I found how easy it was to use I decided to create a web application where I can upload my Photos and then create albums for family and friends to see.  To be able to achieve this I will have to learn more than just the ZK framework.

3D game

I’m the kind of person that gets bored easily and wants to do a million things at once so I also started a more “fun” project. The goal is to create a strategy game using a P2P network.

  • Jmonkey framework
  • 3D modelling
  • P2P networks

Security using AspectJ

Security using AspecJ

Today I will explain how I will be using AspecJ for security in my Ozkey Photo Album.
If you don’t know what aspects are I recommend you read about Aspect Oriented Programming first.

To explain why and how I will use aspects for security first I need to explain what ZK framework is and how the ZK framework actually works. In a nutshell ZK is the leading open source Ajax framework and in it’s core it has an event-driven engine. I will use a simple example to illustrate how it works.

We create the user interface a bit like HTML (but it is not HTML)

<?page title="Login" contentType="text/html;charset=UTF-8"?>
<zk>
<window title="Login" border="normal" width="400px" apply="security.LoginFowardComposer">
    <grid>
        <rows>
            <row>Login: <textbox id="login"/></row>
            <row>Password: <textbox id="password"/></row>
        </rows>
    </grid>
    <button label="Login" id="loginBTN" />
    <button label="Send money" id="sendMoneyBTN" />
</window>
</zk>

This is how it will look like

We then implement the “LoginFowardComposer” that extends the ZK “GenericForwardComposer”. This Class will be responsible for the definition and registration of the event listener for the “Login” and “Send money” button.

package security;
import ...

public class LoginFowardComposer  extends GenericForwardComposer{
    private static final long serialVersionUID = 1L;
    private Textbox login;
    private Textbox password;
    private Button loginBTN;
    private Label sendMoneyBTN;

    public void onClick$loginBTN(Event event) throws Exception{
    	//check login and set the user
    	System.out.println("Login");
    }

    public void onClick$sendMoneyBTN(Event event) throws Exception{
    	// Send the money
    	System.out.println("$$$ send money $$$");
    }
}

As you can see the there is nothing stopping the user from pressing the “send money” button at the moment. The correct thing to do would be to only enable the button after the user has logged in but in some cases disabling the button only looks like the function is disabled but the listener is still listening for the event so a hacker could send an Ajax request and trigger the event so we want to enforce security using aspects.

I will also use annotations so that we defined what events require no security e.g. login and what events require an “admin” role or an “owner” role.

Below is the enum for security roles:

public enum Role {ADMIN,OWNER,PUBLIC,MEMBER,NONE}

Below is the annotation interface that we will use to specify what role is needed for the event:

package security.aspect;

import java.lang.annotation.*; 

public interface Security {
	@Retention(RetentionPolicy.RUNTIME)
	public @interface SecurityCheck {
		Role level();
	}
}

Now that we defined the roles and the annotation interface we can annotate each method in the login composer with the new annotations.

package security;
import ...

public class LoginFowardComposer  extends GenericForwardComposer{

    private static final long serialVersionUID = 1L;
    private Textbox login;
    private Textbox password;
    private Button loginBTN;
    private Label sendMoneyBTN;

    @SecurityCheck(level=Role.NONE)
    public void onClick$loginBTN(Event event) throws Exception{
    	//check login and set the user's role
    	if(login.getValue().equalsIgnoreCase(password.getValue())){
    		Sessions.getCurrent().setAttribute("ROLE",Role.OWNER);
    	}

    }

    @SecurityCheck(level=Role.OWNER)
    public void onClick$sendMoneyBTN(Event event) throws Exception{
    	// Send the money
    	System.out.println("$$$ send money $$$");
    }
}

As you can see the login event requires no security and once you login it assigns you a role. in this example you are assigned the “OWNER” role. this role needs to be checked for the “sendMoney” event and this check will be done in an aspect.

Below is the aspects that will enforce the security defined in the annotation.

	pointcut checkSecurityLevel(security.aspect.Security.SecurityCheck annotation ):
		execution(@SecurityCheck * *..*(..)) &&
		@annotation(annotation);

	void around( security.aspect.Security.SecurityCheck annotation):
		checkSecurityLevel(annotation){
		Role role = (Role) Sessions.getCurrent().getAttribute("ROLE");
		if(role==null)role=Role.NONE;
		System.out.println(">level Required:"+annotation.level());
		System.out.println(">level actual:" + role.toString() );

		if(Role.NONE.toString().equalsIgnoreCase(annotation.level().toString())){
			proceed(annotation);
		}else{
			if(role== annotation.level()){
				System.out.println("LOGIN TRUE");
				proceed(annotation);
			}else{
				System.out.println("LOGIN FALSE");
			}
		}

As you can see above unless your ROLE is the same as the role needed the code will not execute. the problem with this method is that in the future a developer who does not know about how all this works could write a new event and not put a security annotation.

Security using AspecJ

Today I will explain how I will be using AspecJ for security in my Ozkey Photo Album.

If you don’t know what aspects are I recommend you read about Aspect Oriented Programming http://ozkey.com/notes/2010/aop101/ first.

To explain why and how I will use aspects for security first I need to explain what ZK framework is and how the ZK framework actually works. In a nutshell ZK is the leading open source Ajax framework and in it’s core it has an event-driven engine. I will use a simple example to illustrate how it works.

We create the user interface a bit like HTML (but it is not HTML)

<?page title=”Login” contentType=”text/html;charset=UTF-8″?>

<zk>

<window title=“Login” border=“normal” width=“300px” apply=“security.LoginFowardComposer”>

<grid>

<rows>

<row>Login: <textbox id=“login”/></row>

<row>Password: <textbox id=“password”/></row>

</rows>

</grid>

<button label=“Login” id=“loginBTN” />

<button label=“Show me the money” id=“showMoneyBTN” />

</window>

</zk>

We then implement the “LoginFowardComposer” that extends the ZK “GenericForwardComposer”. This Class will be responsible for the definition and registration of the event listener.

As you can see the there is nothing stopping the user from pressing the “send money” button at the moment. The correct thing to do would be to only enable the button after the user has logged in but in some cases disabling the button only looks like the function is disabled but the listener is still listening for the event so a hacker could send an Ajax request and trigger the event so we want to enforce security using aspects.

I will also use annotations so that we defined what events require no security e.g. login and what events require an “admin” role or an “owner” role.

Below is the enum for security roles:

Below is the annotation interface:

Below is the login composer with the new annotations.

Below is the aspects that will enforce the security defined in the annotation

the problem with this method is that in the future a developer who does not know about how all this works could write a new event and not put a security annotation.

Photo Album start

Ozkey Photo Album is starting to take shape. Last week I finished the code for uploading multiple images and this week I started to add some security using aspects. In theory the best way of adding security is using Spring but my hosting (Lunar Pages) doesn’t let me use it  so I will be using a framework I can use and learn in the process. I hope my next post will be about ZK and then how to add security using AspectJ

AOP102 – AspectJ

In our previous post we showed how to insert additional logging using Apects. In this example we will expand the previous example by using annotations to log additional information about the method.

First we will define our annotation (Download source code).

package com.ozkey.aop;
import java.lang.annotation.*; 

@Retention(RetentionPolicy.RUNTIME)
public @interface LogMe {
	String info();
}

Now we can attach some extra information to our methods using the annotation the code is as follows (Download source code):

package com.ozkey.aop;

public class App {

	public static void main(String[] args) {
		App myApp = new App();
		int result = myApp.add(myApp.getRandomNumber() , myApp.getRandomNumber());
		System.out.println("Result:"+result);
	}

	@LogMe(info="Geting a random number")
	public int getRandomNumber(){
		return (new java.util.Random()).nextInt(10)	;
	}
	@LogMe(info="Add numbers")
	public int add(int a,int b){

		return a+b;

	}
}

The point cut is the execution of any method that uses the @LogMe annotation (Download source code)

pointcut LogMePointCut(): execution(@LogMe * com.ozkey.aop..*(..));

The Advice looks for the annotation to log the information (Download source code).

Object around(): LogMePointCut(){
		LogMe logMe = null;
		MethodSignature methodSignature = ((MethodSignature)  thisJoinPointStaticPart.getSignature());
		Annotation[] annotations = methodSignature.getMethod().getAnnotations();
		for(int i=0 ; i < annotations.length ; i++){
			if (annotations[0] instanceof LogMe) {
				logMe = (LogMe) annotations[0];
			}
		}
		Object obj = proceed();
		if(obj!= null &&logMe!=null)	{
			System.out.println("+	info:" + logMe.info()+":" + obj.toString());
		}

		return obj;
	}

The output

+	info:Geting a random number:1
+	info:Geting a random number:8
+	info:Add numbers:9

(Download source code)

AOP101 – AspectJ

“We can view a complex software system as a combined implementation of multiple concerns. A typical system may consist of several kinds of concerns, including business logic, performance, data persistence, logging and debugging, authentication, security, multithread safety, error checking, and so on.” 1

Aspect Oriented Programming (AOP) Isolates secondary or supporting functions from the main program’s business logic by allowing the separation of cross-cutting concerns.

Terminology used in Aspect-oriented programming:

  • Cross-cutting concerns: Even though most classes in an OO model will perform a single, specific function, they often share common, secondary requirements with other classes. For example, we may want to add logging to classes within the data-access layer and also to classes in the UI layer whenever a thread enters or exits a method. Even though each class has a very different primary functionality, the code needed to perform the secondary functionality is often identical.
  • Join points: Points in a running program where additional behaviour can be usefully joined (like method call, object instantiation, or variable access).
  • Pointcut: The specific join points determined by an expression where additional behaviour needs to be applied.
  • Advice: This is the additional code that you want to code to run at a join point matched by a pointcut. The actions can be performed before, after, or around  the specified join point
  • Aspect: The combination of the pointcut and the advice is termed an aspect.

The most common example is the use of an Aspect for logging. I will show how Aspects, joinpoints, pointcuts, and advices come together to achieve this:
The example code below function is to get two random numbers and add them (Download source code). The result is then displayed. If we want to know what the original two random numbers are then we will have to add some extra logging.

package com.ozkey.aop;

public class App {

	public static void main(String[] args) {
		App myApp = new App();
		int result = myApp.add(myApp.getRandomNumber() , myApp.getRandomNumber());
		System.out.println("Result:"+result);
	}

	public int getRandomNumber(){
		return (new java.util.Random()).nextInt(10)	;
	}
	public int add(int a,int b){
		return a+b;
	}
}

The application output is

Result:6

Fist we define where we need to add extra logging. There are a few places where we could insert additional code. this points are called “joint points” (for example: method call, object instantiation, or variable access) but to keep it close to our goal and simple we will define or “point cut” as the join points of execution of any public method call with in our app and we will call this point cut “publicMethods”. The point cut expression is as follows:

pointcut publicMethods() : execution(public * com.ozkey.aop..*(..));

Now we can inset additional code “before” and “after” every joint point defined in our point cut. This additional code is called “advice”. The combination of the pointcut and the advice is termed an aspect. Below is what our aspect looks like (Download source code):

package com.ozkey.aop;

public aspect LogitAspect {

	pointcut publicMethods() : execution(public * com.ozkey.aop..*(..));

	before() : publicMethods(){
		/* before advice (additional code) */
	}
	after() : publicMethods(){
		/* after advice (additional code) */
	}
}

Since our goal is to log the two random numbers generated we will log value being returned but we might also want to log the arguments being passed to the methods calls to find if the correct arguments are being passed. The before advice will log the arguments being passed and the “after” advice will log the object being returned (Download source code).

package com.ozkey.aop;

public aspect LogitAspect {

	pointcut publicMethods() : execution(public * com.ozkey.aop..*(..));

	before() : publicMethods(){
		/*before advice (additional code)*/
		System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
		System.out.println(">	Class:" + thisJoinPointStaticPart.getSignature().getDeclaringType().getName());
		System.out.println(">	Method:" + thisJoinPointStaticPart.getSignature().getName());

		Object[] args = thisJoinPoint.getArgs();
		for(int i = 0; i<args.length;i++){
			System.out.println(">	Arg" +i + ":" + args[i].toString() );
		}
		System.out.println(">	");
	}
	after() returning (Object obj):  publicMethods(){
		/* after advice (additional code) */
		if(obj!=null)
			System.out.println("<	Returned:" + obj.toString());
		System.out.println("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
	}
}

The application’s output should look like the lines below:

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
>	Class:com.ozkey.aop.App
>	Method:main
>	Arg0:[Ljava.lang.String;@6ca1c
>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
>	Class:com.ozkey.aop.App
>	Method:getRandomNumber
>
<	Returned:2
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
>	Class:com.ozkey.aop.App
>	Method:getRandomNumber
>
<	Returned:3
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
>	Class:com.ozkey.aop.App
>	Method:add
>	Arg0:2
>	Arg1:3
>
<	Returned:5
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Result:5
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

Another possible way of writing the same advice would have been to use the “around” advice. Around advice can perform custom behavior before and after the method invocation but it is also responsible for choosing if and when to proceed to the join point advised and what object to return. the around advice looks like this (Download source code):

	Object around(): publicMethods(){
		System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
		System.out.println(">	Class:" + thisJoinPointStaticPart.getSignature().getDeclaringType().getName());
		System.out.println(">	Method:" + thisJoinPointStaticPart.getSignature().getName());

		Object[] args = thisJoinPoint.getArgs();
		for(int i = 0; i<args.length;i++){
			System.out.println(">	Arg" +i + ":" + args[i].toString() );
		}
		System.out.println(">	");

		Object obj = proceed();

		if(obj!= null)
			System.out.println("<	Returned:" + obj.toString());
		System.out.println("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
		return obj;
	}

The around advice is very powerful as it allows you to modify behavior by either changing the original arguments,  not proceeding to the joint point and/or returning a different Object

(Download source code)

Continue to AOP102

See also

http://www.eclipse.org/aspectj/doc/next/progguide/semantics-advice.html

1 – http://www.javaworld.com/javaworld/jw-01-2002/jw-0118-aspect.html?page=2

Javascript – play time

There is some amazing things you can do with JavaScript and this is a great example of what can be done. I could play with this app for hours. http://10k.aneventapart.com/Uploads/25/

Graphene

Graphene is such an interesting material. I think it will change a lot of what we know about electromagnetism.

Article:

Strained graphene creates pseudo-magnetic fields stronger than any before seen:
http://www.popsci.com.au/2010/08/strained-graphene-creates-pseudo-magnetic-fields-stronger-than-any-before-seen/

What is graphene:

http://en.wikipedia.org/wiki/Graphene

Networking PDF – A Peer-to-Peer Architecture for Massive Multiplayer Online Games

I thought making a game was going to be easy but the network part is starting to be a little nightmare and a challenge.

here is PDF that might give me some answers (2006) network and this website (2010) http://vast.sourceforge.net/

Jmonkey Networking

Jmonkey has a networking built in so i will have to look into it a little more. here is a tutorial

Simple Example: http://code.google.com/p/jgn/wiki/SimpleSynchronization

One More: http://code.google.com/p/jgn/wiki/FlagRushTest

Network game cheats and p2p solutions

This is a good document on MMOG Survey on Network Game Cheats and P2P Solutions1

Jmonkey – Java 3D engine

Jmonkey is an open source 3D engine. Normally java is not considered for games but Jmonkey has already being used in commercial applications.