Showing posts with label JSE7. Show all posts
Showing posts with label JSE7. Show all posts

Thursday, October 09, 2014

How do I check if a Class is an instanceof another Class without initializing it?

Illustration: Cathy Wilcox
We had a recent security audit and a question was posed about how to check a Class without doing an instanceof. This turned out to be a great learning experience. There were a couple of issues that needed to be resolved, first we were loading a Class by passing in its name using something similar to the line below: This will load the Class, but from here how do we check that it is an instanceof without instantiating it?
This can be solved by using isAssignableFrom(Class clazz) as shown below. In this case we are checking if SolientGreen is Green. Some of you will find the moral paradox of being "Green" with Soilent Green.
The second issue is a more potential security problem. How do we load the Class without initializing it. If the Class has a static initializer, the code is executed when the class is loaded. Alas, this is handled by using a variation of Class.forName(String name, boolean initialize, ClassLoader loader) which takes a boolean to determine if the class should be initialized, and a ClassLoader if you want to specify a specific loader.

Finally, we can check the Class like this: When this is run, you will not see the message. Very nice indeed!

So here is the remaining code for education and entertainment:
The code for the project can be downloaded from Bitbucket here: assignable

Wednesday, August 22, 2012

Computing Time in a Method Call

Background

I was trying to do some comparisons on how fast a particular algorithm was calculating Checksum values. In my case, I have Adler32, CRC32, and PureCrc32 (Apache Hadoop) to check. This is my particular case, but in general this question comes up for a number of cases; performance optimization being one of them. Since we are calculating the Checksum on files, the problem is complicated by I/O considerations. File caching, and operating system constraints (resources) being the big ones. So how do most people do it?


The Ugly Truth

The general methodology that most developers use is to wrap the method call of interest with start and end time variables, and calculate the difference. They may repeat the process a couple of times, and average it. If they are fancy, they may randomly execute the method to provide some variance. This pseudo randomness gives the feel of more objective results.

Does it work?

The truth is about precision. This will give you a rough time frame. Perhaps that is all you need. My college mathematics profession, Dr. Alden Monberg, always talked about scale and precision. A tolerance of ± 25mm may work on a ship section weighing a 50 MT., but the same value on a pacemaker, or heart value would be unacceptable. A precision of ± 10nm would work for the heart value, but would be impossible for the ship.

Getting nanometer precision (or nanosecond in our case)

The results from the calculations above will give "thumb in the air" results, but is too imprecise to be useful when you may be calculating 10,000 file, or 10,000,000 files. The overhead of the method call is lost in the I/O, but it still there. The greater the number of files, the more optimized the algorithm, the less time it consumes. We can't control the I/O per se, so lets control our algorithm.

Take a different approach

We still want to do the calculation, but we want to do it on the void update(byte[] b, int off, int len) method which is the root of our algorithm being called. I decided to try to use AOP, and try to wrap the method invocation. I know there are some folks who use Spring, but I do not. I wanted to use an AOP framework directly instead of using it wrapped in Spring. I tried a number of frameworks to see which one I thought would be the least invasive and easiest to use.
After trying all of them, I found that Guice was the easiest to use. I was not able to use it directly out of the box though. The "preferred" method for Guice is to annotate the classes you want to test. In my case, I can not annotate the JDK, nor Hadoop classes. So I had to use another methodology which I will detail.

How do you do it?

I had not originally considered Guice until I found this blog post: Guice Tutorial – part 2: method interception which details performing method interception. This was the jackpot find that got me on track. The example code on that tutorial has the methodology which I used. However, it falls a little short because Guice does not have method matcher which matches on the method name. A little more searching came up with an issue/enhancement posted in Issue tracker for Guice. Issue #164 method name matcher enhancement. The issue is closed as a WONTFIX, but the submitter (Aaron Whiteside) proposed some code to do it. I modified the code slightly, but it was a near perfect fit. Google Groups has an explanation why Bob Lee thinks it is a bad idea: Guice/AOP - intercepting a method thanks to its name. I disagree, but that is his choice. The code Aaron mostly works, and my code below does work. So be it. OK, so we now have most of the pieces in place. The cool thing about this method is that we can use it anywhere. I am going to use it on a JUnit test like the tutorial in my code, but it is very general. So here is what I needed:
  1. A MethodInterceptor implementation
  2. A Matcher implementation
  3. An AbstractModule implementation
  4. A JUnit test

Code

TimingInterceptor.java


MethodCalledMatcher.java


AbstractModuleImpl.java


ChecksumTest.java


Results

However one test does not tell the whole story. When I actually ran this as a more general performance calculation. The results were on curves. On small files like the 10MB one in my test, the Adler32 was fastest. The PureCrc32 code performed the best as the file sizes got larger. Please don't accept the output here as a performance test without considering other factors. It is cool though that we got more precise results rather than brute force attempting it.

Thursday, December 15, 2011

Java Tip of the Day: Using ProcessBuilder to Make System Calls

A few years ago I posted an article on how to execute OS level system calls using the Runtime class. When I wrote that article I was using a methodology which has been around since the 1.0 days of Java. In Java 5 Standard Edition, and subsequently improved in Java 6 and Java 7, is a class called ProcessBuilder. This class is a significant improvement over using the Runtime class. It provides complete flexibilty around the system call in terms of environment including directories, input and output streams, and execution.

Here is the NetBeans 7.1 Apache Maven project: process-builder-example.zip


When I execute it from NetBeans I get something like this:
[exec:exec]
total 24
drwxr-xr-x  12 jyeary  staff   408B Dec 15 08:19 .hg
-rw-r--r--   1 jyeary  staff    52B Dec 15 08:08 .hgignore
-rw-r--r--   1 jyeary  staff   1.7K Dec 15 07:59 nbactions.xml
-rw-r--r--   1 jyeary  staff   2.0K Dec 15 08:19 pom.xml
drwxr-xr-x   4 jyeary  staff   136B Dec 14 23:31 src
drwxr-xr-x   4 jyeary  staff   136B Dec 15 08:35 target
Exit Status : 0

Thursday, October 13, 2011

JDK7: String in Switch Example

switch in Java was always considered not particularly useful prior to Java 5. In Java 5, enum was added to the language. This made it more useful to use switch statements, but was still incomplete. A feature request that has been long in waiting is the ability to use a String in a switch.

Finally, in Java 7 SE we get the ability to use a String in a switch statement. This feature, I believe, will make the use of switch more prevalent in code which is post JDK 6.

The example below was developed using NetBeans 7.1 Beta on Oracle Solaris Express 11. The NetBeans Java project is located here: StringSwitch.zip.

This code was presented at the Greenville Java Users Group. The Unicode has a hidden message which is displayed when run.

StringSwitch.java


Sunday, August 28, 2011

Article: Java 7: Worth A Hard Look

I just finished reading a half-page article called "Java 7: Worth A Hard Look" by Andrew Binstock in InformationWeek. If you want to read the article you can download the pdf from InformationWeek. Their site has a broken link to the article.

In the article he briefly mentions a couple of the new items in Java 7 such as NIO.2, fork-join framework, and invokedynamic.

There is no significant meat to the article, but he misses a few of the really cool language improvements: diamond operator, try with resources, and multi-catch. These are changes from project coin which most developers can take advantage of immediately.

The diamond <> operator simplifies the use of generics by reducing code duplication.

Map<String,Map<String,String>> map = new HashMap<>();


Try with resources allows us to use critical system resources like I/O and not have to worry about closing them. The system will handle it for us. All of the Java I/O libraries have been retrofitted with the AutoClosable interface.

The multi-catch allows us to catch multiple exceptions and handle them in a common way.

try {
...
} catch (NullPointerException | ArithmeticException e) {
log(e);
}

This is a lot simpler, and makes the code cleaner and easier to read.

The other items like fork-join, and invokedynamic are much more specific (niche). If you are not using other JVM languages, invokedynamic is not of interest to you. Fork-Join is (in my opinion) more of an academic problem. I have not seen a real good use case example.

NIO.2 is really cool, but it will require a lot more work on the part of the developer to take advantage of. The FileSystem API is awesome for anyone who needs to take advantage of manipulating files on a system. However, it will take some re-work to bring into existing code.


Popular Posts