Archive for May 2012

Camtasia Studio – Free license give-away

Camtasia Studio

I have used Camtasia Studio by TechSmith on a number of occasions and I thoroughly enjoy their desktop recording software. Since I like Camtasia Studio so much, I thought I would write a couple of articles on using their software. Since I wanted to write a quick article about them, I contacted them and asked if they would let me host a give away for a free copy of Camtasia Studio right here on my blog. I was totally happy when they said yes.

For details on entering the give-away, see The Give-Away below.

So my blog is not so much about promoting a product as providing instructions for how to do something, so of course, this is going to be a “how to” article. So here is how easy it is to record a video.

Sometimes you want to record something on your desktop. For a blogger like myself, I want to record how something hard is done on a computer. I have int the past used VMWare’s recording feature but it doesn’t record sound. I want both sound and video.

Even though I am geek and a developer and I don’t mind compiling some open source tool from scratch, I am also a fan of quality technology that just works. For recording my desktop or any application with video and sound, Camtasia Studio studio just works. While it is not open source, Camtasia Studio is well worth the license fee for me.

About Camtasia Studio

Let’s talk about Camtasia Studio. Camtasia Studio has a single installer, but like many products it is more of a suite or “studio” of feature.

There are five features installed:

  • Camtasia Studio
  • Camtasia MenuMaker
  • Camtasia Player
  • Camtasia Recorder
  • Camtasia Theater

I have mostly used the Recorder and Camtasia Studio.

Easy posting to YouTube or ScreenCast

Camtasia Studio makes uploading a video to YouTube or ScreenCast easy. All you need is your username and password and Camtasia Studio does the work for you.

It automatically opens your browser and takes you to the link to your online video.

The Give-Away

So Camtasia Studio is giving away a free License.

  • Mac or Windows? They have a version for Windows and Mac and so the winner can choose which license they want.
  • Version: Yes, we will be giving away the new version of Camtasia Studio.
  • Start date: Friday, June 1, 2012.
  • End date: Monday, July 2, 2012.

Here is how you can enter to win it.

Step 1

Like Camtasia Studio on Facebook. Just click the image as it is a link.

 FaceBook

Step 2

Enter your email address. Yes, I will need your email address to contact you if you win!

Your done!

That is it. You are now entered into the give-away.

10 Reasons why Linux as a Desktop is rarely found in an Enterprise

Application and Development

  1. Commercial apps. Like it or not the best apps, from MS Office, Adobe Creative Suite, and thousands more, exist only for Windows and most cross-platform apps just mean Windows and Mac.
  2. Internal custom apps are almost all written for Windows only. And when they are web apps they often use SharePoint with IE only features.
  3. Lack of enterprise product support for any operating system but Windows.
  4. Rapid desktop application development on Windows with Visual Studio is orders of magnitude faster than on Linux with its best IDE, which is arguably Eclipse.

Infrastructure

  1. Most existing desktop operating systems are already Windows.
  2. Desktop Management solutions that Enterprise IT departments use to manage their workstations only manage Windows or if they manage multiple operating systems, they manage Windows the best.
  3. Existing infrastructure (such as phone systems, etc…) integrate with Windows but not with Linux.

Employees

  1. Existing Full-time employees (FTE) in IT are skilled in Windows and employee replacement or training costs are high.
  2. The cost of Linux FTE in IT is higher than Windows FTE in IT.

Advertising

  1. Most companies start small and grow to be an enterprise. When most companies are started, they are started by people who have never heard of or seen Linux.

Will this change in the future?

Maybe. Change is possible but it takes a lot of time and I don’t mean just years, I mean decades. And during these decades every OS vendor is going to fight to gain a monopoly in the enterprise desktop world.

If it does happen, the changes are for the following reasons.

  1. To better support  mobile devices such as iOS and Android (which is sort of Linux)
    1. As more applications become browser apps or cloud apps that work in any browser.
  2. Cross platform development tools, such as Mono and Java and AIR are really improving.

For those who are pro-Linux because it is open source and you believe knowledge belongs to the world, the enterprise doesn’t care. This argument is completely irrelevant from an enterprise perspective. I care, though, if that makes you feel any better (though I am a person not an Enterprise).

What if a Startup uses an Open Source Operating System

Well, look at the 10 items above and you will see you can eliminate 2, 5, 7, 8, and 10. Half the reasons are eliminated by starting with an Open Source OS.  However, on the other hand, half the reasons still exist.

AOP – Implementing Role Based Security

You may want to implement role-based security, where you only allow users assigned a certain role to perform certain actions in an application. Many different classes in your code will need role-based security added to them. As it turns out, role-based security is a cross-cutting concern. Well, Aspect Oriented Programming (AOP) can help you modular such a role-based security structure.

Lets start with an example. Maybe you have a database filled with people (people being a list of user or person objects). You want to control the list of people. Now think of the Create, Read, Update, Delete (CRUD) pattern. Now turn those into four permissions.  Any role could potentially have or not have rights to create a person, read a person’s info, update a person’s info, or delete a person.  An admin user would likely have all of the four CRUD rights. A user would likely have CRUD rights for their own user, but just read rights for other users. Your design might have multiple levels of rights as well. You may want to provide multiple levels of read permissions. Think of any social network where you have more read rights if you are a friend of another Person.

If it was just for a Person object, you probably would implement an AOP-based solution. However, a large application will have dozens of classes around the Person class. It will have many entities besides Person and those entities have many surrounding data classes as well. What if you had to add code to over 100 class objects? Now you can really benefit from an AOP-based design.

Well, I am going to show you example to help get you started.
Lets say you want to encrypt a field of a class. You might think that this is not a crosscutting concern, but it is. What if throughout and entire solution you need to encrypt random fields in many of your classes. Adding encryption to each of the classes can be a significant burden and breaks the “single responsibility principle” by having many classes implementing encryption. Of course, a static method or a single might be used to help, but even with that, code is must be added to each class. With Aspect Oriented Programming, this encryption could happen in one Aspect file, and be nice and modular.

Prereqs

This example assumes you have a development environment installed with at least the following:

  • JDK
  • AspectJ
  • Eclipse (Netbeans would work too)

Step 1 – Create an AspectJ project

  1. In Eclipse, choose File | New | Project.
  2. Select AspectJ | AspectJ Project.
  3. Click Next.
  4. Name your project.
    Note: I named my project AOPRolePermissions
  5. Click Finish.
The project is now created.

Step 2 – Create a class containing main()

  1. Right-click on the project in Package Explorer and choose New | Class.
  2. Provide a package name.
    Note: I named my package the same as the project name.
  3. Give the class a name.
    Note: I often name my class Main.
  4. Check the box to include a public static void main(String[] args) method.
  5. Click Finish.
package AOPRolePermissions;

public class Main
{
	public static void main(String[] args)
	{
		// TODO Auto-generated method stub
	}
}

Step 3 – Create an object that needs Role-based security

For this example, I am going to use a simple Person object.

  1. Right-click on the package in Package Explorer and choose New | Class.
    Note: The package should already be filled out for you.
  2. Give the class a name.
    Note: I named mine Person.
  3. Click Finish.
  4. Add String fields for FirstName and LastName.
  5. Add a getter and setter for each.
package AOPRolePermissions;

public class Person
{
	// First Name
	private String FirstName = "";

	public String getFirstName()
	{
		return FirstName;
	}

	public void setFirstName(String inFirstName)
	{
		FirstName = inFirstName;
	}

	// Last Name
	private String LastName = "";

	public String getLastName()
	{
		return LastName;
	}

	public void setLastName(String inLastName)
	{
		LastName = inLastName;
	}
}

a

Step 4 – Implement example role-based code

For this I created the following objects:

  • Role
  • Permission
  • Permissions
  • FakeSession

The implementation of these is not important to this article, so I am not posting their code. However, you will see these classes if you download the project.

Step 5 – Implement an Annotation for  Role-based Security

Lets add an annotation to mark methods that should use role-based security.

  1. Right-click on the package in Package Explorer and choose New | Annotation.
    Note: The package should already be filled out for you.
  2. Give the annotation a name.
    Note: I named mine RoleBasedSecurity.
  3. Click Finish.
  4. Add a value for the permission type.
  5. Add a value for the Field name (in case the method is named completely different from the field).
  6. Set the Retention to RetentionPolicy.RUNTIME.
  7. Maybe add a comment that this annotation is for use by the Aspect (which we will create shortly).
package AOPRolePermissions;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface RoleBasedSecurity
{
	Permission.Type value() default Permission.Type.All;
	String FieldName() default "";
}

Step 6 – Add the @RoleBasedSecurity annotation to methods

  1. In the Person class, add @RoleBasedSecurity(Type.Read) tag above the gettersof Person.
  2. In the Person class, add @RoleBasedSecurity(Type.Update) tag above the setters of Person.
package AOPRolePermissions;

import AOPRolePermissions.Permission.Type;

public class Person
{
	// First Name
	private String FirstName = "";

	@RoleBasedSecurity(value = Type.Read)
	public String getFirstName()
	{
		return FirstName;
	}

	@RoleBasedSecurity(Type.Update)
	public void setFirstName(String inFirstName)
	{
		FirstName = inFirstName;
	}

	// Last Name
	private String LastName = "";

	@RoleBasedSecurity(value = Type.Read)
	public String getLastName()
	{
		return LastName;
	}

	@RoleBasedSecurity(Type.Update)
	public void setLastName(String inLastName)
	{
		LastName = inLastName;
	}
}

Step 7 – Create an Aspect to check Role-based permissions

  1. Right-click on the package in Package Explorer and choose New | Other.
  2. Choose AspectJ | Aspect.
  3. Click Next.
    Note: The package should already be filled out for you.
  4. Give the Aspect a name.
    Note: I named mine SecureByRoleAspect.
  5. Click Finish.
package AOPRolePermissions;

public aspect SecureByRoleAspect
{

}

Step 7 – Add the pointcut and advice

  1. Add a pointcut called RoleBasedSecurityMethod.
  2. Implement it to work for any method called that is annotated with @RoleBasedSecurity: call(@RoleBasedSecurity * *(..)).
  3. Add a !within(SecureByRoleAspect) (to prevent an infinite loop).
package AOPEncryptionExample;

public aspect EncryptFieldAspect
{
	pointcut RoleBasedSecurityMethod() : call(@RoleBasedSecurity * *(..)) && !within(SecureByRoleAspect);
}

You now have your pointcut.

Step 8 – Implement around advice to check for permissions

  1. Add around advice that returns an Object.
  2. Implement it to be for the RoleBasedSecurityMethod pointcut.
  3. Add code to check for permissions.
  4. Add a return statement.
package AOPRolePermissions;

import java.lang.reflect.Method;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;

public aspect SecureByRoleAspect
{
	pointcut RoleBasedSecurityMethod() : call(@RoleBasedSecurity * *(..))	
									&& !within(SecureByRoleAspect);
	
	
	Object around() : RoleBasedSecurityMethod()
	{
		System.out.println("Checking permissions...");
		
		RoleBasedSecurity rbs = getRBSAnnotation(thisJoinPointStaticPart);

		// Use the FieldName if specified, otherwise guess it from the method name
		String field = (rbs.FieldName().equals("")) ? removeLowerCasePrefix(thisJoinPointStaticPart
				.getSignature().getName()) : rbs.FieldName();

		if (FakeSession.Instance.getCurrentRole().GetPermissions()
				.can(rbs.value(), field))
		{
			System.out.println(String.format(
					"Success: Role has permissions to %s field named %s.%s.",
					rbs.value(), thisJoinPointStaticPart.getSignature()
							.getDeclaringType().getName(), field));
			return proceed();
		}
		else
		{
			System.out
					.println(String
							.format("Failure: Role has insufficient permissions to %s field named %s.%s.",
									rbs.value(), thisJoinPointStaticPart
											.getSignature().getDeclaringType()
											.getName(), field));
		}

		return null;
	}

	private String removeLowerCasePrefix(String inString)
	{
		int startPoint = 0;
		for (int i = 0; i < inString.length(); i++)
		{
			if (Character.isUpperCase(inString.charAt(i)))
			{
				startPoint = i;
				break;
			}
		}
		return inString.substring(startPoint);
	}

	private RoleBasedSecurity getRBSAnnotation(JoinPoint.StaticPart inStaticPart)
	{
		RoleBasedSecurity rbs = null;
		Signature sig = inStaticPart.getSignature();
		if (sig instanceof MethodSignature)
		{
			// this must be a call or execution join point
			Method method = ((MethodSignature) sig).getMethod();
			rbs = method.getAnnotation(RoleBasedSecurity.class);
		}
		return rbs;
	}
}

You are done. Go ahead and run the program. You should get the following output.

Checking permissions...
Success: Role has permissions to Update field named AOPRolePermissions.Person.FirstName.
Checking permissions...
Success: Role has permissions to Update field named AOPRolePermissions.Person.LastName.
Checking permissions...
Success: Role has permissions to Read field named AOPRolePermissions.Person.FirstName.
John
Checking permissions...
Success: Role has permissions to Read field named AOPRolePermissions.Person.LastName.
Johnson
Checking permissions...
Failure: Role has insufficient permissions to Update field named AOPRolePermissions.Person.FirstName.
Checking permissions...
Failure: Role has insufficient permissions to Update field named AOPRolePermissions.Person.LastName.
Checking permissions...
Success: Role has permissions to Read field named AOPRolePermissions.Person.FirstName.
John
Checking permissions...
Success: Role has permissions to Read field named AOPRolePermissions.Person.LastName.
Johnson

Role Based Security with AOP Project Download

AOPRolePermissions.zip

Return to Aspected Oriented Programming – Examples

AOP – Logging method execution time  in Java with AspectJ

This is not a walk-thru. This is just an example AspectJ class.

Note: For logging, the log singleton which I previously posted is used, but of course you can hook this up to your own logging methods or just print to the console.

This class is intended to log when a method executes and when a method ends and include the time it took for a method to execute in nanoseconds. Methods inside methods are tabbed. This is an enhancement to this post: AOP – Logging all method calls and executions

package mainExample;

import java.util.Stack;
import org.aspectj.lang.JoinPoint;

public aspect AspectLogMethodExecution
{
	private int tabCount = 0;
	private Stack _StartTimeStack = new Stack();

	pointcut AnyMethod() : (call(* *.*(..)) || execution(* *.*(..)))
						&& !within(AspectLogMethodExecution)
						&& !within(Log);

	before() : AnyMethod()
	{
		PrintMethod(thisJoinPointStaticPart);
		tabCount++;
		_StartTimeStack.add(System.nanoTime());
	}

	after() : AnyMethod()
	{
		Long methodExecutionTime = EvaluateExecutionTime();
		tabCount--;
		PrintMethod(thisJoinPointStaticPart, methodExecutionTime);
	}

	private Long EvaluateExecutionTime()
	{
		Long methodExecutionTime = System.nanoTime() - _StartTimeStack.pop();
		return methodExecutionTime;
	}

	private void PrintMethod(JoinPoint.StaticPart inPart)
	{
		Log.WriteLine(GetTabs() + inPart);
	}

	private void PrintMethod(JoinPoint.StaticPart inPart, long inExecutionTime)
	{
		Log.WriteLine(GetTabs() + inPart + " Execution Time: "
				+ inExecutionTime + " nanoseconds");
	}

	private String GetTabs()
	{
		String tabs = "";
		for (int i = 0; i < tabCount; i++)
		{
			tabs += "\t";
		}
		return tabs;
	}
}

So if you have a simple Hello, World app, this is the log output.

execution(void mainExample.Main.main(String[]))
	call(void java.io.PrintStream.println(String))
	call(void java.io.PrintStream.println(String)) Execution Time: 112063 nanoseconds
execution(void mainExample.Main.main(String[])) Execution Time: 904636 nanoseconds

I ran it multiple times and the executions times were sporadic. I remember reading somewhere that System.nanoTime() in java was not extremely accurate, but it is accurate enough for this example.

 
Return to Aspected Oriented Programming – Examples

AOP – Logging all method calls and executions in Java with AspectJ

This is not a walk-thru. This is just an example AspectJ class.

Note: For logging, the log singleton which I previously posted is used, but of course you can hook this up to your own logging methods or just print to the console.

This class is intended to log when a method executes and when a method ends. Methods inside are tabbed.

package mainExample;

import org.aspectj.lang.JoinPoint;

public aspect AspectLogMethodExecution
{
	private int tabCount = 0;

	pointcut AnyMethod() : (call(* *.*(..)) || execution(* *.*(..)))
						&& !within(AspectLogMethodExecution)
						&& !within(Log);

	before() : AnyMethod()
	{
		PrintMethod(thisJoinPointStaticPart);
		tabCount++;
	}

	after() : AnyMethod()
	{
		tabCount--;
		PrintMethod(thisJoinPointStaticPart);
	}

	private void PrintMethod(JoinPoint.StaticPart inPart)
	{
		Log.WriteLine(GetTabs() + inPart);
	}

	private String GetTabs()
	{
		String tabs = "";
		for (int i = 0; i < tabCount; i++)
		{
			tabs += "\t";
		}
		return tabs;
	}
}

So if you have a simple Hello, World app, this is the log output.

execution(void mainExample.Main.main(String[]))
	call(void java.io.PrintStream.println(String))
	call(void java.io.PrintStream.println(String))
execution(void mainExample.Main.main(String[]))

Return to Aspected Oriented Programming – Examples

AOP – Encrypting with AspectJ using an Annotation

This is a continuation of AOP – Encrypting with AspectJ. It is expected you have read (or skimmed) that article first. This article uses the same project. The files in the project so far are these:

  • Encrypt.java
  • EncryptFieldAspect.aj
  • FakeEncrypt.java
  • Main.java
  • Person.java

The final version of EncryptFieldAspect.aj in the previous article is not exactly a “good” Aspect. The problem with it is that it isn’t very reusable. There is a one to one relationship between this Aspect and the field it encrypts. We want a one to many relationship where one Aspect works for encrypting many fields.

Another problem is there is nothing in the objects that would inform a developer that any Aspect Oriented Programming is occurring.

Step 9 – Making the Aspect reusable

Lets make the aspect reusable. Lets make one aspect with a single pointcut and a single around advice work for multiple setters in a class.

  1. In the Person class, add a forth field, DriversLicense. This field should also be encrypted.
  2. Add a getter and setter for the DriversLicense field.
  3. In the Main class, add sample code to set and later print out the DriversLicense field.
  4. In the EncryptFieldAspect, change it to work for all setters by using a * after the word set and making it work for any method that takes a string, not just the SSN setter.
package AOPEncryptionExample;

public aspect EncryptFieldAspect
{
	pointcut encryptStringMethod(Person p, String inString):
	    call(void Person.set*(String))
	    && target(p)
	    && args(inString)
	    && !within(EncryptFieldAspect);

	void around(Person p, String inString) : encryptStringMethod(p, inString) {
		proceed(p, FakeEncrypt.Encrypt(inString));
		return;
	}
}

Ok, now it is reusable but we now have another problem. It is encrypting all the fields, including FirstName and LastName. It is definitely reusable, but now we need something to differentiate what is to be encrypted from what isn’t.

Step 10 – Create an Encrypt annotation

Lets add and use an annotation to mark setters that should use encryption.

  1. Right-click on the package in Package Explorer and choose New | Annotation.
    Note: The package should already be filled out for you.
  2. Give the annotation a name.
    Note: I named mine Encrypt.
  3. Click Finish.
  4. Maybe add a comment that this annotation is for use by the Encrypt Aspect.
public @interface Encrypt
{
	// Handled by EncryptFieldAspect
}

Step 11 – Add the @Encrypt annotation to setters

  1. In the Person class, add @Encrypt above the setSSN setter.
  2. Also add @Encrypt above the setDriversLicense setter.
	@Encrypt
	public void setSSN(String inSSN)
	{
		SSN = inSSN;
	}

 

	@Encrypt
	public void setDriversLicense(String inDriversLicense)
	{
		DriversLicense = inDriversLicense;
	}
}

Step 12 – Alter the EncryptFieldAspect to work for multiple objects

Well, now that it works for any setter in the Person object that is marked with @Encrypt, the next step is to make it work for any setter marked with @Encrypt no matter what object it is in.

  1. Remove any reference to Person. We don’t even need it or the parameter ‘p’.
package AOPEncryptionExample;

public aspect EncryptFieldAspect
{
	pointcut encryptStringMethod(String inString):
		call(@Encrypt * *(String))
		&& args(inString)
		&& !within(EncryptFieldAspect);

	void around(String inString) : encryptStringMethod(inString) {
		proceed(FakeEncrypt.Encrypt(inString));
		return;
	}
}

Great, now let’s test it.

Step 11 – Test Using @Encrypt on multiple objects

Ok, let’s create a second object that has an ecrypted field to test this. Lets create a Credentials.java file with a UserName and Password fields, getters and setters. Of course the Password should be encrypted.

  1. Right-click on the package in Package Explorer and choose New | Class.
    Note: The package should already be filled out for you.
  2. Give the class a name.
    Note: I named mine Credentials.
  3. Click Finish.
  4. Add both a UserName and Password field.
  5. Add a getter and setter for both.
  6. Add the @Encrypt annotation above the setPassword setter.
package AOPEncryptionExample;

public class Credentials
{
	// UserName
	private String UserName;

	public String getUserName()
	{
		return UserName;
	}

	public void setUserName(String userName)
	{
		UserName = userName;
	}

	// Password
	private String Password;

	public String getPassword()
	{
		return Password;
	}

	@Encrypt
	public void setPassword(String password)
	{
		Password = password;
	}
}

Now lets create a Credentials object in the main() method and print out the values.

package AOPEncryptionExample;

public class Main
{
	public static void main(String[] args)
	{
		Person p = new Person();
		p.setFirstName("Billy");
		p.setLastName("Bob");
		p.setSSN("123456789");
		p.setDriversLicense("987654321");

		System.out.println("Person:");
		System.out.println("         FirstName: " + p.getFirstName());
		System.out.println("          LastName: " + p.getLastName());
		System.out.println("               SSN: " + p.getSSN());
		System.out.println("  Driver's License: " + p.getDriversLicense());
		System.out.println();

		Credentials c = new Credentials();
		c.setUserName("billybob");
		c.setPassword("P@sswd!");

		System.out.println("Person:");
		System.out.println("       UserName: " + c.getUserName());
		System.out.println("       Password: " + c.getPassword());
	}
}

Ok, test it. The output should be as follows:

Person:
         FirstName: Billy
          LastName: Bob
               SSN: #encrypted#123456789#encrypted#
  Driver's License: #encrypted#987654321#encrypted#

Person:
       UserName: billybob
       Password: #encrypted#P@sswd!#encrypted#

Well, now you have learned how to encrypt using Aspect Oriented Programming.

Here are a couple of benefits of encrypting with AOP.

  1. The crosscutting concern of security is now modular.
  2. If you wanted to change/replace the encryption mechanism, including the encryption method names, you can do that in a single place, the EncryptFieldAspect object.
  3. The code to encrypt any field in your entire solution is nothing more than an annotation, @Encrypt.
  4. The @Encrypt annotation can provide documentation in the class and in API documentation so the fact that encryption is occurring is known.
  5. You don’t have to worry about developers implementing encryption differently as it is all done in a single file in the same predictable manner.

Congratulations on learning to encrypt using AOP, specifically with AspectJ and Annotations.

What about decryption?

By the way, I didn’t show you how to decrypt. Hopefully I don’t have to and after reading you know how. Maybe in your project the design is that the getters return the encrypted values and you don’t need to decrypt. However, maybe in your design you need your getters to decrypt. Well, you should be able to impement a DecryptFieldAspect and a @Decrypt annotation for that.

If you use decrypt on the getter, the output is the same as if there were no encrypt/decrypt occuring. However, it is still enhanced security because the value is stored encrypted in memory and not as plain text in memory.

However, I have a version of the project that decrypts that you can download.

AOP Encryption example project Download

Download the desired version of the project here:

Return to Aspected Oriented Programming – Examples

AOP – Encrypting with AspectJ

Lets say you want to encrypt a field of a class. You might think that this is not a crosscutting concern, but it is. What if throughout and entire solution you need to encrypt random fields in many of your classes. Adding encryption to each of the classes can be a significant burden and breaks the “single responsibility principle” by having many classes implementing encryption. Of course, a static method or a single might be used to help, but even with that, code is must be added to each class. With Aspect Oriented Programming, this encryption could happen in one Aspect file, and be nice and modular.

Prereqs

This example assumes you have a development environment installed with at least the following:

  • JDK
  • AspectJ
  • Eclipse (Netbeans would work too)

Step 1 – Create an AspectJ project

  1. In Eclipse, choose File | New | Project.
  2. Select AspectJ | AspectJ Project.
  3. Click Next.
  4. Name your project.
    Note: I named my project AOPEncryptionExample
  5. Click Finish.
The project is now created.

Step 2 – Create a class containing main()

  1. Right-click on the project in Package Explorer and choose New | Class.
  2. Provide a package name.
    Note: I named my package the same as the project name.
  3. Give the class a name.
    Note: I often name my class Main.
  4. Check the box to include a public static void main(String[] args) method.
  5. Click Finish.
package AOPEncryptionExample;

public class Main
{
	public static void main(String[] args)
	{
		// TODO Auto-generated method stub
	}
}

Step 3 – Create an object with an encrypted value

For this example, I am going to use a Person object, and we are going to encrypt the SSN on that object.

  1. Right-click on the package in Package Explorer and choose New | Class.
    Note: The package should already be filled out for you.
  2. Give the class a name.
    Note: I named mine Person.
  3. Click Finish.
  4. Add String fields for FirstName, LastName, and SSN.
  5. Add getters and setters for each.
package AOPEncryptionExample;

public class Person
{
	// First Name
	private String FirstName = "";

	public String getFirstName()
	{
		return FirstName;
	}

	public void setFirstName(String inFirstName)
	{
		FirstName = inFirstName;
	}

	// Last Name
	private String LastName = "";

	public String getLastName()
	{
		return LastName;
	}

	public void setLastName(String inLastName)
	{
		LastName = inLastName;
	}

	// Social Security Number
	private String SSN = "";

	public String getSSN()
	{
		return SSN;
	}

	public void setSSN(String inSSN)
	{
		SSN = inSSN;
	}
}

Right now, SSN has no encryption. We don’t want to clutter our Person class with encryption code. So we are going to put that in an aspect.

Step 4 – Add sample code to main()

  1. Create in instance of Person.
  2. Set a FirstName, LastName, and SSN.
  3. Ouput each value.
public static void main(String[] args)
{
	Person p = new Person();
	p.setFirstName("Billy");
	p.setLastName("Bob");
	p.setSSN("123456789");

	System.out.println("FirstName: " + p.getFirstName());
	System.out.println(" LastName: " + p.getLastName());
	System.out.println("      SSN: " + p.getSSN());

}

If you run your project, you will now have the following output.

FirstName: Billy
 LastName: Bob
      SSN: 123456789

Step 5 – Create and object to Simulate Encryption

You don’t have to do full encryption, or any encryption at all for that matter, to test this. The important thing to realize is that you can configure how the value is stored in an object without cluttering the object with the encryption code.

I created a FakeEncrypt static object and will use this object as an example.

package AOPEncryptionExample;

public class FakeEncrypt
{
	public static String Encrypt(String inString)
	{
		return "#encrypted#" + inString + "#encrypted#";
	}
}

The goal is to passing in an SSN, 123-456-789, and have it return an encrypted value (or in this case a fake encrypted value), #encrypted#123-456-789#encrypted#.

Step 6 – Create an Aspect object

  1. Right-click on the package in Package Explorer and choose New | Other.
  2. Choose AspectJ | Aspect.
  3. Click Next.
    Note: The package should already be filled out for you.
  4. Give the Aspect a name.
    Note: I named mine EncryptFieldAspect.
  5. Click Finish.
package AOPEncryptionExample;

public aspect EncryptFieldAspect
{

}

Step 7 – Add the pointcut

  1. Add a pointcut called SetSSN.
  2. Include two parameters, the Person object and the SSN string.
  3. Implement it with a call to void Person.setSSN(String).
  4. Add a target for the Person p.
  5. Add an args for the SSN string.
  6. Add a !within this class (to prevent an infinite loop).
package AOPEncryptionExample;

public aspect EncryptFieldAspect
{
	pointcut setSSN(Person p, String inSSN):
	    call(void Person.set*(String))
	    && target(p)
	    && args(inSSN)
	    && !within(EncryptFieldAspect);
}

You now have your pointcut.

Step 8 – Implement around advice to replace the setter

  1. Add void around advice that takes a Person and a String as arguments.
  2. Implement it to be for the setSSN pointcut.
  3. Add code to encrypt the SSN.
  4. Add a return statement.
package AOPEncryptionExample;

public aspect EncryptFieldAspect
{
	pointcut setSSN(Person p, String inSSN):
	    call(void Person.set*(String))
	    && target(p)
	    && args(inSSN)
	    && !within(EncryptFieldAspect);

	void around(Person p, String inSSN) : setSSN(p, inSSN) {
		p.setSSN(FakeEncrypt.Encrypt(inSSN));
		return;
}

You are done with this one method. Here is the output of running this program.

FirstName: Billy
 LastName: Bob
      SSN: #encrypted#123456789#encrypted#

So we aren’t exactly done because we have two issues that would be nice to resolve. First, the Aspect is not reusable and second, their is no way for a developer to know by looking at the Person object that the SSN should be encrypted. Both of these issue are resolved by using annotations and will be explained in the next article.

Continue reading at AOP – Encrypting with AspectJ using an Annotation

Return to Aspected Oriented Programming – Examples

AOP – Adding Advice before or after main() in Java with AspectJ

This is a very easy example of Aspect Oriented Programming. Lets add advice (code to run) before the main() executs and when main() finishes. You will see how without cluttering our Main class or our main() method, we can add modular code to run before or after main().

Prereqs

This example assumes you have a development environment installed with at least the following:

  • JDK
  • AspectJ
  • Eclipse (Netbeans would work too)

Step 1 – Create an AspectJ project

  1. In Eclipse, choose File | New | Project.
  2. Select AspectJ | AspectJ Project.
  3. Click Next.
  4. Name your project.
    Note: I named my project mainExample
  5. Click Finish.
The project is now created.

Step 2 – Create a class containing main()

  1. Right-click on the project in Package Explorer and choose New | Class.
  2. Provide a package name.
    Note: I named my package mainExample, the same as the project name.
  3. Give the class a name.
    Note: I often name my class Main.
  4. Check the box to include a public static void main(String[] args) method.
  5. Click Finish.
package mainExample;

public class MainExample
{
	static void main(String[] args)
	{
		// TODO Auto-generated method stub
	}
}

Step 3 – Create an Aspect object

  1. Right-click on the mainExample package in Package Explorer and choose New | Other.
  2. Choose AspectJ | Aspect.
  3. Click Next.
    Note: The package should already be filled out for you with “mainExample”.
  4. Give the Aspect a name.
    Note: I named mine StartEndAspect.
  5. Click Finish.
package mainExample;

public aspect StartEndAspect
{

}

Step 4 – Add a pointcut to the StartEndAspect

  1. Create a pointcut named mainMethod().
  2. Configure the pointcut to use “execution”.
  3. Configure the pointcut to be specifically for the “public static void main(String[] args)” method.
package mainExample;

public aspect StartEndAspect
{
    pointcut mainMethod() : execution(public static void main(String[]));
}

Note: Notice that to be specific for a method, you include everything but the parameter name.

Step 5 – Add before advice

  1. Add a before() statement for mainMethod().
  2. Have it simple write to the console a message such as “The application has started.”
package mainExample;

public aspect StartEndAspect
{
    pointcut mainMethod() : execution(public static void main(String[]));

    before() : mainMethod()
    {
        System.out.println("Application has started...");
    }
}

Step 6 – Add after advice

  1. Add an after() statement for mainMethod().
  2. Have it simple write to the console a message such as “The application has ended.”
package mainExample;

public aspect StartEndAspect
{
    pointcut mainMethod() : execution(public static void main(String[]));

    before() : mainMethod()
    {
        System.out.println("The application has ended...");
    }

    after() : mainMethod()
    {
        System.out.println("The application has ended...");
    }
}

So the advice is applied and even though there is not code in main(), the advice is applied and the console output is as follows:

The application has started…
The application has ended…

Congratulations you have learned one simple way to use Aspect Orient Programming for Java with AspectJ.
Return to Aspected Oriented Programming – Examples

Xml Serialization in Java using Simple – Inheritance

This is a continuation from this post: Xml Serialization in Java using Simple

Example 4 – Serializing a list of objects that inherit from Person

Lets create some objects that inherit from Person. I looked at some documentation to try to get it right the first time. And then I hoped that it would just work….

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

@Root
public class Person
{
	@Element(name="FirstName")
	private String _FirstName = "";

	@Element(name="LastName")
	private String _LastName = "";

	public String getFirstName()
	{
		return _FirstName;
	}

	public void setFirstName(String inFirstName)
	{
		_FirstName = inFirstName;
	}

	public String getLastName()
	{
		return _LastName;
	}

	public void setLastName(String inLastName)
	{
		_LastName = inLastName;
	}
}
import java.util.ArrayList;
import java.util.List;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;

@Root
public class People 
{
	@ElementList(inline=true)
	List<Person> List = new ArrayList<Person>();
}

I didn’t want to get too complex so I only added a single item to Patient, a list of Symptoms.

import java.util.ArrayList;
import java.util.List;
import org.simpleframework.xml.ElementList;

public class Patient extends Person
{
	@ElementList(entry = "Symptom", inline = true)
	public List<String> Symptoms = new ArrayList<String>();
}

For the Physician, again to keep it simple, I only added a list of Hospitals.

import java.util.ArrayList;
import java.util.List;
import org.simpleframework.xml.ElementList;

public class Physician extends Person
{
	@ElementList(entry = "Hospital", inline = true)
	public List<String> Hospitals = new ArrayList<String>();
}

And here is the main method where I create the instances and serialize them.

import java.io.File;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

public class Run
{
	public static void main(String[] args) throws Exception
	{
		People people = new People();
		
		Patient p1 = new Patient();
		p1.setFirstName("Jared");
		p1.setLastName("Barneck");
		p1.Symptoms.add("Runny nose");
		p1.Symptoms.add("Congestion");
		people.List.add(p1);

		Physician p2 = new Physician();
		p2.setFirstName("Mike");
		p2.setLastName("Michaels");
		p2.Hospitals.add("Intermount Health Care");
		p2.Hospitals.add("St. Marks");
		people.List.add(p2);
		
		Serializer serializer = new Persister();
		File file = new File("people.xml");

		serializer.write(people, file);
	}
}

And yeah! This worked. Here is the Xml.

<people>
   <person class="Patient">
      <FirstName>Jared</FirstName>
      <LastName>Barneck</LastName>
      <Symptom>Runny nose</Symptom>
      <Symptom>Congestion</Symptom>
   </person>
   <person class="Physician">
      <FirstName>Mike</FirstName>
      <LastName>Michaels</LastName>
      <Hospital>Intermount Health Care</Hospital>
      <Hospital>St. Marks</Hospital>
   </person>
</people>

There you go.

There are a lot more examples here:
Simple Xml Serialization Tutorial

Xml Serialization in Java using Simple

So, I have to serialize some code in Java and I have used Simple (a java Xml Serialization library) before for Xml serialization with Android in Java, so I thought I would use it again for a regular java project.

Here is what I have done. Some examples have failed, some have succeed. Here are my results.

Example 1 – Serializing a simple Person object

Attempt 1 – Failed with exception

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

@Root
public class Person
{
	@Element
	public String FirstName;

	@Element
	public String LastName;
}

And here is the Run.java with the main method.

import java.io.File;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

public class Run
{
	public static void main(String[] args) throws Exception
	{
		Person p = new Person();

		Serializer serializer = new Persister();
		File file = new File("person.xml");

		serializer.write(p, file);
	}
}

Result

An Exception was thrown because FirstName is null. So maybe it cannot handle null values?

Attempt 2 – Succeeded

Lets try be setting the default values to an empty string.

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

@Root
public class Person
{
	@Element
	public String FirstName = "";

	@Element
	public String LastName = "";
}

It worked. Here is the xml file.

<person>
   <FirstName>
   <LastName>
</person>

Attempt 3 – Succeeded

Of course if we set the values for FirstName and LastName…

    Person p = new Person();
    p.FirstName = "Jared";
    p.LastName = "Barneck";

…they show in the Xml as well.

<person>
   <FirstName>Jared</FirstName>
   <LastName>Barneck</LastName>
</person>

Example 2 – Serializing a Person object with getters and setters

Attempt 1 – Succeeded

I changed the member variables to be private and created public getters and setters.

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

@Root
public class Person
{
	@Element
	private String FirstName = "";

	@Element
	private String LastName = "";

	public String getFirstName()
	{
		return FirstName;
	}

	public void setFirstName(String inFirstName)
	{
		FirstName = inFirstName;
	}

	public String getLastName()
	{
		return LastName;
	}

	public void setLastName(String inLastName)
	{
		LastName = inLastName;
	}
}

I now use the setters to set the values in the main method.

import java.io.File;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

public class Run
{
	public static void main(String[] args) throws Exception
	{
		Person p = new Person();
		p.setFirstName("Jared");
		p.setLastName("Barneck");

		Serializer serializer = new Persister();
		File file = new File("person.xml");

		serializer.write(p, file);
	}

}

That worked and output the desired Xml.

<person>
   <FirstName>Jared</FirstName>
   <LastName>Barneck</LastName>
</person>

Example 3 – Using a custom name

What if the name of the member variables were _FirstName and _LastName. We wouldn’t want the underscore “_” to show up in the Xml.

So what do we do? The documentation says to use this line:

@Element(name=”FirstName”)

Attempt 1 – Success

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

@Root
public class Person
{
	@Element(name="FirstName")
	private String _FirstName = "";

	@Element(name="LastName")
	private String _LastName = "";

	public String getFirstName()
	{
		return _FirstName;
	}

	public void setFirstName(String inFirstName)
	{
		_FirstName = inFirstName;
	}

	public String getLastName()
	{
		return _LastName;
	}

	public void setLastName(String inLastName)
	{
		_LastName = inLastName;
	}
}

This worked, and the Xml output was unchanged.

Example 3 – Serializing a List

Ok, now we want to serialize a list of Person objects.

Attempt 1 – Failed with exception

I tried to use an ArrayList<Person> and it didn’t work. The person object is the same as in example 2, but I changed the main method as follows:

import java.io.File;
import java.util.ArrayList;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

public class Run
{
	public static void main(String[] args) throws Exception
	{
		ArrayList<Person> people = new ArrayList<Person>();

		Person p1 = new Person();
		p1.setFirstName("Jared");
		p1.setLastName("Barneck");
		people.add(p1);

		Person p2 = new Person();
		p2.setFirstName("Mike");
		p2.setLastName("Michaels");
		people.add(p2);

		Serializer serializer = new Persister();
		File file = new File("people.xml");

		serializer.write(people, file);
	}
}

So that didn’t work.

Attempt 2 – Failed, no exception, just bad Xml

I created a People class that extends ArrayList<Person>.

import java.util.ArrayList;
import org.simpleframework.xml.Root;

@Root
public class People extends ArrayList<Person>
{
}

I then used this class in the main method.

	public static void main(String[] args) throws Exception
	{
		People people = new People();

		Person p1 = new Person();
		p1.setFirstName("Jared");
		p1.setLastName("Barneck");
		people.add(p1);

		Person p2 = new Person();
		p2.setFirstName("Mike");
		p2.setLastName("Michaels");
		people.add(p2);

		Serializer serializer = new Persister();
		File file = new File("people.xml");

		serializer.write(people, file);
	}

It didn’t throw and exception but the Xml was basically empty.

<people/>

That isn’t what we want.

Attempt 3 – Succeeded but not quite right

Ok, so how about a container object instead of an extending object. The documentation has an @ElementList attribute that can be used if the class contains a list. So lets use that.

import java.util.ArrayList;
import java.util.List;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;

@Root
public class People
{
	@ElementList
	List<Person> List = new ArrayList<Person>();
}

The main method changed slightly to accommodate the People class.

	public static void main(String[] args) throws Exception
	{
		People people = new People();

		Person p1 = new Person();
		p1.setFirstName("Jared");
		p1.setLastName("Barneck");
		people.List.add(p1);

		Person p2 = new Person();
		p2.setFirstName("Mike");
		p2.setLastName("Michaels");
		people.List.add(p2);

		Serializer serializer = new Persister();
		File file = new File("people.xml");

		serializer.write(people, file);
	}

The Xml was created and looks as follows:

<people>
   <List class="java.util.ArrayList">
      <person>
         <FirstName>Jared</FirstName>
         <LastName>Barneck</LastName>
      </person>
      <person>
         <FirstName>Mike</FirstName>
         <LastName>Michaels</LastName>
      </person>
   </List>
</people>

That is almost correct. However, we don’t need to the List line between People and person.

Attempt 4 – Succeeded

Ok, so I read the documentation and it said to use this to remove the useless List Xml element.

@ElementList(inline=true)

So I tried and sure enough, it worked.

<people>
   <person>
      <FirstName>Jared</FirstName>
      <LastName>Barneck</LastName>
   </person>
   <person>
      <FirstName>Mike</FirstName>
      <LastName>Michaels</LastName>
   </person>
</people>

Ok…lets continue this a bit later in another post.

Xml Serialization in Java using Simple – Inheritance

A Log singleton in java

I needed a simple logger in java. I wrote a quick singleton. I sort of want to keep this around if I ever need to use it again, so I thought I would post it here.

Note: Feel free to complain about this singleton using my own code style and not the java code style. 🙂

package ClinicSoft.Singletons;

import java.io.File;
import java.io.FileWriter;

public class Log
{
	public static Log Instance = new Log();

	private String _FileName;
	private String _Extension = ".log";
	private int _LogId = -1;

	private Log()
	{
		SetFileName("ClinicSoft");
	}

	public String GetFileName()
	{
		if (_LogId > -1)
			return _FileName + "." + _LogId + _Extension;
		else
			return _FileName + _Extension;
	}

	// The root file name, without the extension
	public void SetFileName(String inFileName)
	{
		_FileName = inFileName;
		while (FileExists(GetFileName()))
			_LogId++;
	}

	private boolean FileExists(String inFile)
	{
		return new File(inFile).exists();
	}

	public static void WriteLine(String inLogMessage)
	{
		Log.Instance.WriteLog(inLogMessage
				+ System.getProperty("line.separator"));
	}

	public void WriteLog(String inLogMessage)
	{
		try
		{
			// Create file
			FileWriter file = new FileWriter(GetFileName(), true);
			file.write(inLogMessage);

			// Close the output stream
			file.close();
		}
		catch (Exception e)
		{
			// Catch exception if any
			System.err.println("Error: " + e.getMessage());
		}
	}
}

Building a FreeBSD kernel for debugging

You may want to actually debug the kernel or a kernel module, however, debugging is not enabled by default.

Prereqs

Before getting started it is assumed you have a FreeBSD Install and you have downloaded/installed FreeBSD Source.

The steps are identical to the steps contained in the How to build and install a custom kernel on FreeBSD? article, with the exception of the kernel configuration file.

Step 1 – Create a new kernel config

  1. Determine your architecture by running this command:
    # uname -a
    FreeBSD 9.0-RELEASE FreeBSD 9.0-RELEASE #0: Tue Jan 3 07:46:30 UTC 2012 root@farrell.cse.buffalo.edu:/usr/obj/usr/src/sys/GENERIC amd64
    
  2. Look at the last text item in the output string. I have amd64 so that is my architecture: amd64
  3. Change to the directory of the kernel configuration files for your architecture. Remember if you are on a different architecture to replace amd64 in the following command lien with your architecture.
    # cd /usr/src/sys/amd64/conf
    
  4. Copy GENERIC to a new file.
    # cp GENERIC KRNLDBG
    
  5. Edit KRNLDBG with your favorite text editor.
  6. First, change the ident value near the top from GENERIC to KRNLDBG.
    ident           KRNLDBG
    
  7. Add debugging settings to your KRNLDBG configuraiton file.
    options           KDB
    options           KDB_TRACE
    options           DDB
    options           GDB
    
  8. Save and close your new KRNLDBG configuration file.

For the remaining steps, follow the How to build and install a custom kernel on FreeBSD? article, only replace any references to KRNL1 kernel config file with the KRNLDBG config file created in the previous step.

Once you are done building and installing the kernel, you should have debugging enabled.

I happen to be working with a kernel module that is crashing and when it crashes, it automatically places me in a debugging session with the following prompt.

db>

Installing VMWare Tools on FreeBSD 9

Virtualizing a FreeBSD server is common place. Knowing how to install VMWare Tools on a FreeBSD server without X11 is going to be extremely important. This article will provide the steps.

Lets get started.

Step 1 – Install FreeBSD as VMWare Guest.

Instructions for installing FreeBSD 9 are found here: How do I install FreeBSD 9?

It shouldn’t be much of an effort to follow these steps inside a VMWare guest.

Note: You may consider taking a snapshot here to save your current state.

Step 2 – Update FreeBSD and Install ports

Instructions for updating FreeBSD and installing ports are found here:
Update FreeBSD and Install ports

Note: You may consider taking a snapshot here to save your current state.

Step 3 – Install Prerequisites

Step 3.1 – Install Perl

Installing Perl is easy. Use either of the following commands.

From ports

# cd /usr/ports/lang/perl5.12
# make install

From packages

# pgk_add -r perl

Step 3.2 – Install compat6x-amd64

The compat6x-amd64 port is also easily installed.

From ports

# cd /usr/ports/misc/compat6x/
# make install

From packages

# pkg_add -r compat6x-amd64

Step 4 – Take a VMWare Snapshot

Important! Take a snapshot here! Do not skip this step.

Step 5 – Mount the VMWare Tools ISO

I am using VMWare workstation. Some steps may be slightly different if you are using ESXi or other VMWare solution.

  1. In VMWare Workstation, choose VM | Install VMWare Tools.
  2. In FreeBSD as root, create a directory to mount the CD-Rom to.
    # mkdir /cdrom
    
  3. Mount the cd-rom.
    # mount -t cd9660 /dev/cd0 /cdrom
    

Note: You may consider taking a snapshot here to save your current state.

Step 6 – Extract the vmware-freebsd-tools.tar.gz

Now that the drive is mounted, it should be easy to get to the vwmare-tools file.

  1. Copy the vmware-freebsd-tools.tar.gz file to a local location.
    # cp /cdrom/vmware-freebsd-tools.tar.gz /root
    
  2. Extract the vmware-freebsd-tools.tar.gz file.
    # cd /root
    # tar -xzf vmware-freebsd-tools.tar.gz
    

VMWare tools should now be extracted.

Step 7 – Recompile VMWare Tools Modules

Before you install VMWare tools on FreeBSD 9, you need the modules to work with FreeBSD 9. VMWare is slow to update the vmware tools for the FreeBSD guest. So you are just going to have to update them yourself.

Note: We are now at the point where we are going to do more and install more than you want to for your nice new clean server, but that is ok, because we have a snapshot and once we get the files compiled you can revert to the clean snapshot. Alternately if you have another FreeBSD system, you can do these steps on that system.

If you install without recompiling as of May 10, 2012, you will get this result.

Starting VMware Tools services in the virtual machine:
   Switching to guest configuration:                                   done
   Guest memory manager:                                              failed
   Blocking file system:                                              failed
   Guest operating system daemon:                                      done
Unable to start services for VMware Tools

Execution aborted.

Compiling the modules first should prevent the above failures.

Step 7.1 – Get FreeBSD Source

Download the FreeBSD Source as described here.

How to download FreeBSD source using svn?

Step 7.2 – Configure the /etc/make.conf

Right now there is a move toward compiling with clang over gcc. Because of changes due to this, you need to add the following line to your /etc/make.conf to compile with gcc. I have not tried to compile with clang yet.

  1. As root open the /etc/make.conf file with you favorite editor and add the following line:
    MK_CLANG_IS_CC=no
    
  2. Save and close the /etc/make.conf file.

Your /etc/make.conf is now configured.

Note 1: You may want to compile a custom kernel while you are at this. If so, check out this article: How to build and install a custom kernel on FreeBSD? If you do this, remember that you have to copy the new kernel to your clean system too.

Step 7.3 – Compile the vmmemctl module

Recompile vmmemctl using these steps.

  1. Go to the lib/modules/source directory under where you extracted vmware-freebsd-tools.tar.gz.
    # cd /root/vmware-tools-distrib/lib/modules/source/
    
  2. Extract vmmemctl.tar
    # tar -xf vmmemctl.tar
    
  3. Change to the vmmemctl-only directory.
    # cd vmmemctl-only
    
  4. Run make.
    # make
    
  5. Run make install.
    # make install
    

You have now built and installed the vmmemctl module.

Step 7.4 – Compile the vmblock module

  1. Go to the lib/modules/source directory under where you extracted vmware-freebsd-tools.tar.gz.
    # cd /root/vmware-tools-distrib/lib/modules/source/
    
  2. Extract vmblock.tar
    # tar -xf vmblock.tar
    
  3. Change to the vmblock-only directory.
    # cd vmblock-only
    
  4. Run make.
    # make
    
  5. Run make install.
    # make install
    

You have now built and installed the vmblock module.

Step 8 – Install VMWare Tools

You are now ready to install the VMWare Tools.

Note: If you are trying to keep you server clean and pristine, then copy the /root/vmware-tools-distrib directory off the server somewhere. THen revert to the snapshot you took just before Step 4. Copy the directory back to your clean snapshot and continue.

  1. Move into the directory created by the extraction.
    # cd /root/vmware-tools-distrib/
    
  2. Run vmware-install.pl
    # ./vmware-install.pl
    
  3. Select all the defaults.

Your vmware tools installation should go smoothly.

How to build and install a custom kernel on FreeBSD?

Lets get started. The main reason I am writing this when so many articles on this already exist is because many articles do not have all the steps in one place. For example, the article in the FreeBSD Handbook doesn’t have steps for downloading the source using subversion or for making sure you have enough space on the root partition. See this article here: Building and Installing a Custom Kernell

Step 1 – Install FreeBSD as VMWare Guest.

Instructions for installing FreeBSD 9 are found here:

How do I install FreeBSD 9?

You may also want to install FreeBSD ports:

How to install FreeBSD ports

Step 2 – Download FreeBSD Source

Instructions for downloading FreeBSD Source can be found here:

How to download FreeBSD source using svn?

Step 3 – Build the GENERIC Kernel

Before you create a custom kernel it is always good to know that the default GENERIC kernel is compiling and working. Also, if you are practiced at this and are certain this will work, feel free to skip this step.

Note: I call it the GENERIC kernel because the GENERIC is the file name of the default kernel configuration.

  1. Go to the /usr/src directory:
    # cd /usr/src
    
  2. As root, run this command:
    # make buildkernel
    
  3.  Wait for the compile to complete

Step 4 – Create a new kernel config

  1. Determine your architecture by running this command:
    # uname -a
    FreeBSD 9.0-RELEASE FreeBSD 9.0-RELEASE #0: Tue Jan 3 07:46:30 UTC 2012 root@farrell.cse.buffalo.edu:/usr/obj/usr/src/sys/GENERIC amd64
    
  2. Look at the last text item in the output string. I have amd64 so that is my architecture: amd64
  3. Change to the directory of the kernel configuration files for your architecture. Remember if you are on a different architecture to replace amd64 in the following command lien with your architecture.
    # cd /usr/src/sys/amd64/conf
    
  4. Copy GENERIC to a new file.
    # cp GENERIC KRNL1
    
  5. Edit KRNL1 with your favorite text editor.
  6. First, change the ident value near the top from GENERIC to KRNL1.
    ident           KRNL1
    
  7. Make any other changes you would like to make.It is hard to know why you are building a custom kernel and hopefully you know what you need in your custom kernel. This is where you modify the kernel to provide what you need.
  8. Save and close your new KRNL1 configuration file.

Step 5 – Build the custom kernel

Now that you have a new configuration file, build a kernel using that configuration file.

  1. Compile the kernel.
    # cd /usr/src
    # make buildkernel KERNCONF=KRNL1
    
  2. Wait for you kernel to build.

Step 6 – Verify you have enough space for the new kernel

  1. Make sure you have enough free space to install your kernel.Note: Your output may be quite different than mine.
    # df -ah
    Filesystem    Size    Used   Avail Capacity  Mounted on
    /dev/da0p2     74G    4.3G     64G     6%    /
    devfs         1.0k    1.0k      0B   100%    /dev
    
  2. If your root partion, /, has a capacity greater than 55%, you probably OK. Otherwise, your backup or kernel installation may fail.

Step 7 – Install the custom kernel

  1. Install the Kernel.
    # make installkernel KERNCONF=KRNL1
    
  2. Reboot the system.
    # reboot
    

You now have a custom kernel installed.

Unit Testing with Parameter Value Coverage (PVC)

Parameter Value Coverage (PVC) is the ability to track coverage of a method based on the common possible values for the parameters accepted by the method.

Current code coverage tools fail to take into consideration the possibility that a value for a parameter is not handled resulting in a bug. However, there may not be any code addressing this value in any way, introducing the possibility of obtaining 100% code coverage or line coverage (LC) without detecting the bug.

If the common values for types, especially primitive types and known types, are documented and methods that use them are required to have a test for each possible parameter value, bugs can be avoided.

The following is a table of parameter value requirements for an int or System.Int32 and string or System.String. A unit test should exist for each of the possible values in order to have 100% PVC.

System.Int32 System.String
  1. A positive integer
  2. A negative integer
  3. Zero
  4. int.MaxValue or 2,147,483,647
  5. int.MinValue or -2,147,483,648
  1. A null string
  2. An empty string, String.Empty, or “”
  3. One or more spaces ” “
  4. One or more tabs ” “
  5. A new line or Environment.NewLine
  6. A valid string.
  7. An invalid or junk string
  8. Unicode characters such as Chinese

See Parameter Value Coverage by Type for more complete list of common Parameter Values per type.

Were code coverage tools enhanced to take into account Parameter Value Coverage (PVC), better tests would be written and more bugs would be found.

Such PVC lists should be created for each primitive type and a list of required parameter values to test against for each of primitive type should be standard for each language. You could also create a list of parameter values for you own types though you may find that your own type is actually a collection of primitive types and methods, and if they are tested with PVC, your class is automatically tested with PVC as well.

Finding bugs beyond 100% Code Coverage with PVC

100% code coverage or line coverage (LC) can fail to find many bugs. Developers often write a unit test with only the goal to get as close to 100% LC as they can. Unfortunately, they are only covering the written code, but bugs may exist due to code not written.

Here is a quick example. The method below is a very common example of a piece of code that looks so simple, most assume there is no way there is a bug, but after a brief analysis, the bug becomes obvious.

public class Adder()
{
    private int Add(int val1, int val2)
   {
        return val1 + val2;
   }
}

To get 100% LC, the following test could be used.

private void Add_Test()
{
    Adder adder = new Adder();
    var actual = adder.Add(1,2);
    var expected = 3;
    Assert.AreEqual(expected, actual)
}

You now have 100% LC, but have you found all the bugs? No you haven’t. Here are two problems:

  1. An int or System.Int32 is a 32-bit integer with a max value of 2,147,483,647. What happens if you add one or more to the max value?
  2. The minimum value is -2,147,483,648. What happens if you subtract one or more from the minimum value?

How should this problem be fixed?

  • Should you enabled “checked” to disallow overflows?
  • Should you return a long so two 32-bit integers can always be added together?
  • Or should you ignore the issue as it isn’t going to matter in your project?

Your answer may be different depending on your project. I am not going to tell you how to fix this bug in this article, that is not the point. The point is to show that 100% LC failed to find this bug, proving that some level of coverage is missing; some value is not being tracked and reported on.

What is the missing value? Parameter Value Coverage (PVC).

If PVC were taken into account, the test above only provides 20% coverage as only one of the five integer value types were tested. Reaching 80% to 100% PVC would have found this bug.

Every bug that is found internally will cost your business far less money overall than if a customer finds the bug.

Return to C# Unit Test Tutorial