Archive for the ‘Java’ Category.

10+ Reasons why Java needs C#’s property syntax

Written in response, to all the Java developers who claim that Java doesn’t need C#’s property syntax.

The truth is most C# developers can’t quantify all the benefits to C# properties because there are so many. Most arguments I have seen from C# developers have been weak at best. These arguments fail to provide the Java development team a good enough reason to implement C#-like properties.

A proper analogy would be the Pyramids. You can’t point to one brick and say, “That brick makes the pyramid,” because every brick is small (relative the size of the who pyramid), but together, each brick is important to making the pyramid and altogether, they are one of the seven wonders of the world. Similarly, C# Properties provide many little features that together improve the language far more significantly than most can’t quantify.

Properties are quite awesome and provide some great features that Java cannot do now.

1. Easy refactoring when moving from a simple member variable to a property.

Properties using the same syntax as a member variable enable more than one feature, but we are going to talk about only this feature here to start.

public class MyObj
{
   public int Id;
   public String Name;
}

The program starts off with this because for years simplicity is all that is needed.

Note: A getter and a setter provide little to no benefit for a model object. If you aren’t encapsulating code on get and set, using a getter and setter gets in the way. Also, a using a getter and a setter is only a convention anyway, and not forced by the language. As such, getters and setters can’t be relied upon.

A year later, you find that you need to add some feature on name set. You change your class. In Java, you have to create getters and setters.

public class MyObj
{
   public int id;
   private String _Name;
   public String getName(){return _Name;}
   public void setName(string value) {
      _Name = value; 
      // More work here
   }
}

Now every single line of code that calls MyObj.Name is broken. However, with properties, this wouldn’t the case.

public class MyObj
{
   public int id;
   private String Name {
      get { return _Name; } 
      set {
         _Name = value;
         // more work here
      }
   }
}

None of my existing code broke using the property example. This sounds trivial but what if you are an API that hundreds of other tools consume and use. Now this a breaking change that has a massive impact on a business. This feature is huge.

Can Java change a class today from a member variable to a method without breaking an API? No, it cannot. Does this happen often? No, but when it does, it is a breaking change without properties, while with properties, it works without a second thought.

Important: This feature is also why so many hacks that suggest that Java adds a language construct that creates getProperty and setProperty methods are still broken. I’ve seen recommendations such as this where the suggestion is for the compiler and IntelliSense to just convert these to getProperty and setProperty:

public class MyObj
{
   @get @set String Name;
   public MyObj()
   {
      setName("Rhyous");// Default value
   }
}

That syntax doesn’t solve the problem. In order to solve this problem, the syntax still has to be this:

public class MyObj
{
   @get @set String Name;
   public MyObj()
   {
      Name = "Rhyous";// Default value
   }
}

However, even with this, the suggested syntax is not the right suggestion. While the above syntax works for auto properties, how would code be added to the get or set method? The above syntactical sugar, while better than what java has now, is lacking compared to C#’s implementation and would result in fewer features.

2. Replacing an object that uses member variables with an interface

This is similar to #1. You have an object and need to create a layer of abstraction and use an interface for that object. But the object uses only member variables? How can you create an interface for the following syntax in Java?

MyObj.Name

You can’t. So to add a layer of abstraction, you now have to first refactor code. Again, as mentioned in #1, moving from MyObj.Name to MyObj.getName() and MyObj.setName() is a breaking change, especially in a API. It can have a massive impact.

Now, before you argue that you would never need to add a layer of abstraction for a simple object, let me remind you that all objects are not simple. I agree, on a simple model object, abstraction wouldn’t be necessary. However, the problem is certainly with a method on an object that also has public members. But you need the whole object, not just the method. And interface with only methods won’t be enough.

MyObj.Name
MyObj.CallServer();

Well, we can’t use the CallServer() method as is in a Unit Test. We need to use and interface and dependency injection and good language architecture. We have to refactor some. But we with properties we don’t need to make a breaking change. Without properties, we do. We have to change from MyObj.Name to MyObj.getName().

3. Properties are different than member variables and methods and reflection reflects that.

C# has reflection. You can loop through all members, properties, and methods separately. In Java, you have something similar. But no way to get properties separate from other methods.

When you only want to loop through getters and setters in Java, how do you do that? Unless every getter and setter is perfectly named getProperty setProperty and none of the methods that are not getters or setters have the format of getSomething setComething, you can’t.

Can you loop through only properties today in Java? Maybe. Java cannot guarantee this ability.

4. Sharing objects between Java and C#.

This feature goes beyond properties, but the lack of a Property syntax is the biggest barrier.

In order to do this today, the object has to be written in Java and C#. C# developers have to live with the more verbose getProperty() setPropert() syntax. For example: MyObj.Id++ is nice and clean but the equivalent in java is MyObj.setId(MyOjb.getId() + 1);

Some tools, such as Hibernate/NHibernate, would benefit greatly from this feature.

5. Properties let you write with cleaner and shorter syntax.

You save programming time. You save lines of code. Look below, as three lines become one.

private String _Name;
public String getName() { return _Name; };
private void setName(String name) { _Name = name; }

vs

public string Name { get; set; }

Java is not just a little more typing, it is a lot more typing. While you can argue that snippets or IDE code generator tools take care of this, I’d argue that C# has snippets and code generators, too. I can type prop tab in Visual Studio and have property pretty quickly so at best, snippets help Java almost catch up in development speed.

Also, let’s not forget that this is one single feature. I could write a whole article about all the ways that C#’s property syntax is cleaner and shorter than Java’s syntax.

How about adding one to an int?

MyObj.Id++;

vs in Java

MyObj.setId(MyObj.getId() + 1);

Again, a shorter and simpler syntax probably is a few dozen features as it will be used in so many different ways for so many different language benefits, not just one.

6. Most the property data is in one place.

This provides multiple features:

  • Easier to rename
  • Easier to copy and paste
  • Easier to identify as a property
public string Name { get; set; }


And in C#, a new syntax was added to make it so you no longer need to break this out to a backing field to set a default value.


public string Name { get; set; } = "Rhyous";

In java, there is no guarantee that properties are all together. I have seen code like this where the properties are not together in java.

public class MyObj 
{
  // Members
  private Integer _Id;
  private String _Name;

  // Getters
  public Integer getId() { return _Id; };
  public String getName() { return _Name; };

  // Setters
  public void setId(int id) { _Id = id; };
  public void setName(String name) { _Name = name; }
}

While this is fine, it makes renaming have to occur in 7 places in three lines that are separated and could be anywhere in the class file. (Count all the times Name or Id is used and it is 7 times.) In C#, it is once with an auto property and only four times with a property with a backing field. Of course, C# has the same problem once you use a backing field. The backing field isn’t always together with the property, that is only two items that can be separate, not three. In Java, keeping it together would have to be by convention. I use this convention in C# to keep backing fields together.

public string Name 
{ 
  get {return _Name; } 
  set {_Name = value;}
} private string _Name;

7. In Aspect-oriented programming (AOP), you can inject code into only Properties.

Using tools like AspectJ, can you do a pointcut only on properties in java? No, you cannot. You can do it on methods and filter it on methods that start with “get” or start with “set”, but we all know that get and set are only conventions and so any method that doesn’t follow convention won’t get the injected code (point cut in AspectJ), and worse, methods that aren’t getters or setters but start with get or set might get the pointcut, which is undesired.

8. Names of properties in a class match when doing Xml or Json serialization

Xml and Json serialization are very common. In C#, for newly developed code, there is no need to decorate the code with any C# Attributes as the names will serialize to JSON and Xml as is.

Imagine we want to get this following Xml from code.

<Person>
  <FirstName>Jared</FirstName>
  <LastName>Barneck</LastName>
</Person>

Or the following JSON.

{  
   "FirstName":"Jared",
   "LastName":"Barneck"
}

In C#, we create this poco class. Note: Poco = plain old class object.

public class Person
{
   public string FirstName { get; set; }
   public string LastName { get; set; }
}

In Java, the class is not so simple. There is not an easy or a guaranteed to work way to do this without a lot more code and without annotations. Here is the same object in Java and what you would have to do to have both getters and setters, private members and serialize using Simple. See my article on Java’s Simple Xml Serialization library.

public class Person
{
   @FirstName
   private String _FirstName {get;set;}
   public String getFirstName() { return _FirstName; }
   public void setFirstName(string value) { _FirstName = value; }

   @LastName
   private String _LastName {get;set;}
   public String getLastName() { return _LastName ; }
   public void setLastName(string value) { _LastName = value; }
}

So in Java, names don’t match, requiring the developer to add a fourth line, an annotation, just to make this work. And this is new code, not legacy code.

So when Java developers tell me that they don’t need properties, they are saying that they prefer four lines of code per property over one line per property when doing serialization. There is no argument. Of the two serializable class syntaxes above, C# is the winner by a long way.

Now some serializers other than Simple are made by using magic strings, where they hope that the get and set convention is used and if it is used, everything after the get or set is serialized. So getPerson() will serialize to Person. Still, this leaves the names not matching, and it requires magic strings of “get” and “set” and a hope (or requirement) that convention was followed.

C# also allows for taking of property of one name and serializing it to another name.

public class Person
{
   [XmlElement("fName")]
   public string FirstName { get; set; }
   [XmlElement("lName")]
   public string LastName { get; set; }
}

Yes, both C# and Java have this feature. The difference is, this is only needed to accommodate existing or legacy systems and not needed for brand new code and systems.

9. Names of properties in a class match when using a database ORM (or CSV or Excel headers)

Ok, this is almost an identical reason as #8, but serialization for JSON and Xml is vastly different than using a database ORM. But the same issue applies. And really Json and Xml are separate reasons and used often, so I could have broken those out into two features instead of one. But let’s not forget that this also benefits Excel output and CSV output as well as database table output. So, yes, this is a big, huge separate feature than serialization.

If you have a table:

CREATE TABLE [dbo].[User]
(
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Username] [nvarchar](255) NULL,
	[CreateDate] [datetime] NOT NULL,
	[LastUpdated] [datetime] NULL,
	[CreatedBy] [int] NOT NULL,
	[LastUpdatedBy] [int] NULL
)

With properties, the naming scheme matches exactly.

public class User
{
   public int Id { get; set; }
   public string Username { get; set; }
   public DateTime CreateDate { get; set; }
   public DateTime LastUpdated { get; set; }
   public int CreatedBy { get; set; }
   public int LastUpdatedBy { get; set; }
}

That is simple and pretty with the six members making up six lines. What do we do in Java?

public class Person
{   
   @Column(name = "Id")
   private String _Id {get;set;}
   public String getFirstName() { return _Id ; }
   public void setFirstName() { _Id = value; }

   @Column(name = "FirstName")
   private String _FirstName {get;set;}
   public String getFirstName() { return _FirstName; }
   public void setFirstName(string value) { _FirstName = value; }
   
   // Sorry, it is too tedious to even type out the rest of the java example, 
   // I would have to create 16 more lines of code for remaining four columns. Ugh!!!
}

10. Making convention a language construct and not just a convention

Multiple times, we have mentioned that trying to require the get and set convention and having tools key of magic strings (starts with “get” or starts with “set”) is not really a good practice. The convention cannot be enforced. I will say that Java has done a tremendous job of trying to enforce this convention. But in the end, it is still a questionable practice that keys off of magic strings that are not guaranteed to be there.

However, by implementing simpler properties, the convention goes away. Everyone who wants property features gets them. Tools no longer have to key off of magic strings.

One might argue that in C#, you can still write the Java way, by writing out getProperty() setProperty(Property value) methods, and that using Properties instead of methods is also only a convention. But that is not true and is shortsighted. Properties are properties. Whereas java only has two object members: member variables and methods; C# has three: member variables, properties, and methods. Properties are not just methods. As noted earlier, properties are separate in reflection, in a different list in the object type information. There is a clear and distinct difference between properties and methods and member variables and how they behave in C#. Because of this, magic strings are not needed to execute code.

Don’t just copy, improve too

Salesforce added C# like properties to Apex, their originally java-based language. Only they enhanced the properties by not requiring a separate backing field. In C#, if you call a property from the get, you create an infinite loop. In Apex, any calls to the variable inside the get don’t create an infinite loop. They copy and improved. Java should do the same.

From the Apex documentation on properties:

Apex properties are based on their counterparts in C#, with the following differences:

  • Properties provide storage for values directly. You do not need to create supporting members for storing values.
  • It is possible to create automatic properties in Apex. For more information, see Using Automatic Properties.

This is outdated information as C# has had the second item, auto properties, for many years now. However, C# doesn’t have the first improvement yet. Good job Salesforce and Apex. They didn’t just see a good thing and copy it, they saw it, copied it, and improved on it.

Properties Provide More Features

The benefits are many and far more valuable than Java developers or even most C# developer realize. The Pyramid analogy is really accurate. There are so many little features of C# properties that the sum of the feature set is, like sum of bricks in a pyramid, huge.

I surely missed many such features that properties provide.

What features do properties give you that would benefit the Java language?
What shorter syntaxes do properties give you over Java’s getter setter syntax?

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());
		}
	}
}

Android and Xml Serialization with Simple

Xml serialization is almost becoming a standard requirement for a language these days and so as I have been taking an Android class and I couldn’t find an Xml Serialization library as part of Android by default, I set out in search of one.

I came across a java XML Serialization project called Simple.

So here is a quick entry-level example of how to use Simple in an Android development project.

Note: This walk-thru assumes you are using Eclipse.

Step 1 – Create a new Android Project

  1. Go to File | New Project and select Android.
  2. Provide a Project Name.
  3. Select the minimum build target.
  4. Provide a Package name.
  5. Click Finish.

Step 2 – Download Simple

  1. Go to the Simple download page: http://simple.sourceforge.net/download.php
  2. Extract the zip file.

Step 3 – Add the Simple library to your project

  1. Create a folder called libs in your project.
  2. Copy the jar file called simple-xml-2.6.2.jar to the libs directory you just created.Note: Be aware your version may be newer than 2.6.2.
  3. In Eclipse, right-click on simple-xml-2.6.2.jar (if it doesn’t show up refresh) and choose Build Path | Add to Build Path.

Step 4 – Create an Serializeable object

  1. Right-click on your package and choose New | Class.
  2. Provide a class name and click ok.
  3. The following is an example Person class:Person.java
    package org.jaredbarneck.cs6890;
    
    import org.simpleframework.xml.Element;
    import org.simpleframework.xml.Root;
    
    @Root
    public class Person
    {
    
    	public Person()
    	{
    	}
    
    	public Person(String inFirstName, String inLastName)
    	{
    		SetFirstname(inFirstName);
    		SetLastname(inLastName);
    	}
    
    	@Element
    	private String FirstName;
    
    	public String GetFirstName()
    	{
    		return FirstName;
    	}
    
    	public void SetFirstname(String inFirstName)
    	{
    		FirstName = inFirstName;
    	}
    
    	@Element
    	private String LastName;
    
    	public String GetLastName()
    	{
    		return LastName;
    	}
    
    	public void SetLastname(String inLastName)
    	{
    		LastName = inLastName;
    	}
    
    	@Override
    	public boolean equals(Object inObject)
    	{
    		if (inObject instanceof Person)
    		{
    			Person inPerson = (Person)inObject;
    			return this.FirstName.equalsIgnoreCase(inPerson.FirstName)
    				&& this.LastName.equalsIgnoreCase(inPerson.LastName);
    		}
    		return false;
    	}
    }
    

Step 5 – Serialize and Deserialize in your main Activity

  1. Add the following code to your main Activity:Note: Code should be clear and is commented.PersonActivity.java
    package org.jaredbarneck.cs6890;
    
    import java.io.File;
    
    import org.simpleframework.xml.Serializer;
    import org.simpleframework.xml.core.Persister;
    
    import android.app.Activity;
    import android.os.Bundle;
    
    public class PersonActivity extends Activity
    {
    	public void onCreate(Bundle savedInstanceState)
    	{
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.main);
    
    		// Create a Person object
    		Person person1 = new Person("John", "Johnson");
    
    		// Create a file to save to and make sure to use the path provided from
    		// getFilesDir().getPath().
    		File xmlFile = new File(getFilesDir().getPath() + "/Person.xml");
    
    		// Serialize the Person
    
    		try
    		{
    			Serializer serializer = new Persister();
    			serializer.write(person1, xmlFile);
    		}
    		catch (Exception e)
    		{
    			e.printStackTrace();
    		}
    
    		// Create a second person object
    		Person person2 = null;
    
    		// Deserialize the Person
    		if (xmlFile.exists())
    		{
    			try
    			{
    				Serializer serializer = new Persister();
    				person2 = serializer.read(Person.class, xmlFile);
    			}
    			catch (Exception e)
    			{
    				e.printStackTrace();
    			}
    		}
    
    		boolean b = person1.equals(person2);
    	}
    }
    

Go ahead and try this in your Android emulator and step through it with a debugger.

You have now successfully implemented Xml Serialization in Java on Android using Simple.

How to create an Android menu?

Ok, so adding a menu that pops up from the bottom when the menu button is clicked is very common and quite easy to do.

Note: This assumes you have the Android SDK, Emulator, and Eclipse all working already.

Step 1 – Create your Android project

  1. In Eclipse, select File | New Project | Android | Android Project.
  2. Give your project a Name.
    I named this project “HelloAll”.
  3. Select the Build Target (the minimum version of Android).
    I selected Android 2.2.
  4. Enter a Package name.
    Package name is like a namespace, it can be anything you want, but you should actually choose a name as carefully as you choose and the name of an object.  I named the package this: org.rhyous.
  5. Click Finish.

Your project is now created.

Step 2 – Add an XML file for the menu

  1. Expand the res directory in your project.
  2. Right-click on the layout folder and choose New | Other.
  3. Choose XML | XML file and click Next.
  4. Name the file.
    I named my file menu.xml.
  5. Click Finish.
  6. Add the following text into your menu:
    <menu xmlns:android="http://schemas.android.com/apk/res/android">
        id="@+id/menu_item_1" android:title="@string/menu_1"/>
        id="@+id/menu_item_2" android:title="@string/menu_2"/>
        <item android:id="@+id/menu_item_3" android:title="@string/menu_3"/>
    </menu>
    

Step 3 – Add the strings for the menu items

  1. Expand the res\values directory in your project.
  2. Open the strings.xml.
  3. Add strings for each menu item.
    Make sure you use the same id strings you used in the menu.xml for the title of each menu item.
    Your strings.xml should now look like this:

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <string name="hello">Hello World, HelloAllActivity!</string>
        <string name="app_name">HelloAll</string>
        <string name="menu_1">Menu 1</string>
        <string name="menu_2">Menu 2</string>
        <string name="menu_3">Menu 3</string>
    </resources>
    

You now have a menu and strings for each menu item.

Step 4 – Overload onCreateOptionsMenu

  1. Open your Activity.
    Mine is src\org.rhyous\HelloAllActivity.java.
    It should look like this:

    package org.rhyous;
    
    import android.app.Activity;
    import android.os.Bundle;
    
    public class HelloAllActivity extends Activity {
    	/** Called when the activity is first created. */
    	@Override
    	public void onCreate(Bundle inSavedInstanceState) {
    		super.onCreate(inSavedInstanceState);
    		setContentView(R.layout.main);
    	}
    }
    
  2. Add code to override onCreateOptionsMenu and add code to inflate the menu.
    	@Override
    	public boolean onCreateOptionsMenu(Menu inMenu) {
    		super.onCreateOptionsMenu(inMenu);
    		getMenuInflater().inflate(R.layout.menu, inMenu);
    		return true;
    	}
    

You can now build your application and test that the menu pops up. However, the menu doesn’t do anything yet.

Step 5 – Overload onCreateOptionsMenu

  1. Add code to override onOptionsItemSelected and add code to inflate the menu.
  2. Use a switch statement with the inItem.getItemId() function to perform the appropriate action for each menu item.
    	@Override
    	public boolean onOptionsItemSelected(MenuItem inItem) {
    		switch (inItem.getItemId()) {
    		case R.id.menu_item_1:
    			// Do something here
    			return true;
    		case R.id.menu_item_2:
    			// Do something here
    			return true;
    		default:
    			// Should never get here
    			return false;
    		}
    

Based on the item clicked, the appropriate code will run.

Hope you enjoyed this simple Android development example.

Java version of the sequential sum algorithm or n(n+1)/2

My first Android homework was to write a little program that would add sequential numbers such as 1 to 100. I call it a Sequential Sum, but I couldn’t find the exact mathematical name.

You can read more about this mathematical task here: Techniques for adding the numbers 1 to 100

In code, you could of course loop through 1 through 100 and += them into a value but there is a more efficient way and most everyone in my class mentioned that is what they did, so I guess I was unique in choosing this solution.

Or you could use the following equation that provides you the answer to get the sum of all numbers between 1 and the end value, n.

n(n+1)/2

Now what if you aren’t starting at 1? What if you want to add the numbers between 50 and 150? Well, this is easy. The last number before the start value of 50 is 49 or 50 – 1 = 49. We can get the value of 1 to 49 and subtract it from the value of 1 to 150.

n(n+1)/2 – s(s+1)/2

While this is for Android, it is basically just java and there is nothing Android specific here. Here is my class.

package org.jaredbarneck.cs6890;

import java.security.InvalidParameterException;

/**
 * @author Jared
 *
 */
public class SequentialSum {

	// Member variables
	private int _LowValue = 0;
	private int _HighValue = 0;

	// Constructors
	public SequentialSum(int inLowValue, int inHighValue) {
		SetHighValue(inHighValue);
		SetLowValue(inLowValue);
	}

	// Getters and Setters
	public int GetLowValue() {
		return _LowValue;
	}

	public int GetHighValue() {
		return _HighValue;
	}

	public void SetLowValue(int inValue) {
		if (inValue < 0)
			throw new InvalidParameterException(
					"Value must be greater than zero!");
		if (inValue > _HighValue)
			throw new InvalidParameterException(
					"High value must be lower than the high value!");

		_LowValue = inValue;
	}

	public void SetHighValue(int inValue) {
		if (inValue < 0)
			throw new InvalidParameterException(
					"Value must be greater than zero!");
		if (inValue < _LowValue)
			throw new InvalidParameterException(
					"High value must be greater than the low value!");

		_HighValue = inValue;
	}

	// Methods
	public int Sum() {

		int sumToSubtract = 0;
		if (_LowValue > 1) {
			int tmpVal = _LowValue - 1;
			sumToSubtract = tmpVal * (tmpVal + 1) / 2;
		}

		return (_HighValue * (_HighValue + 1) / 2) - sumToSubtract;
	}
}

So if I ever need to get the sum of all values between a sequential list of numbers, I can come back and use this class again.

Note: No, I don’t follow java syntax rules and no, I don’t plan too either. I don’t start anything with lower case that is not a local variable. My member variables start with an underscore _ and then an uppercase letter. Everything else starts with upper case. I don’t conform my style to a specific language’s style, instead I try to use the same style in all languages.