Parsing JSON via ScriptEngine in the JDK

I’m writing some REST WebServices that return JSON and wanted to ensure that my JSON was correctly formatted and parsable. Since the JDK ships with a JavaScript engine built into it now, I figured it would be simplest to just use that and avoid any external dependencies. Here’s my code:

ScriptEngine se = new ScriptEngineManager().getEngineByExtension("js");
se.eval("var obj = " + json + ";");

Pretty simple overall. The only tricky part is that you need to add the “var obj = ” and the semicolon on the end so that the JavaScript engine can evaluate it correctly.

IntelliJ refresh

I’ve been using IntelliJ IDEA for the past 7 years and anyone who knows me will tell you that I’m an IDE snob. However, over the past 7 years I have been using the exact same configuration for IntelliJ IDEA and all of my project files have rarely changed. Over those 7 years I would merrily install the new version of IntelliJ IDEA and when it asked me to import the configuration from an old version, I would. Likewise, when new versions of IntelliJ IDEA tried to open an older project file it would often ask me if I wanted to upgrade the file format to the new version and I would.

Over the years my IDE configuration files and project files seemed to becoming less and less stable. I assumed that even though I was upgrading consistently, IntelliJ IDEA was managing all that complexity behind the scenes without any problems. This is not the case. But let me be clear, this is NOT an issue with the IDE, but the user.

In order to innovate things must change. Often that change is not backwards compatible or backwards compatibility is not always perfect. If you really want to innovate, you should just toss backwards compatibility out the door and charge forward (but that’s a topic for another post). The folks over at JetBrains have been innovating on the world’s best IDE for years. They have also tried and mostly succeeded at providing working upgrade paths between versions because often they break backwards compatibility. However, nothing is perfect and there comes a point when you must wipe the slate clean and start fresh.

I decided it was time to start fresh with IntelliJ IDEA. Here’s what I did:

  • Un-installed IntelliJ IDEA completely
  • Deleted all the preferences, caches and logs
  • Deleted all my IDE project files
  • Re-installed IntelliJ IDEA fresh
  • Re-configured IntelliJ from scratch
  • Re-created all my IDE projects files by hand

At first I was really annoyed at having to do this process. But now that I’m mostly finished, I’m glad I did. I noticed that a number of files I had been using (i.e. .eml files) were no longer needed and IntelliJ was probably just dealing with them since they were there, even though it really preferred to use a different structure. I’d much rather use the new methodology instead of an older one, which might not have the same level of support and integration, and could unexpectedly break at any time.

I think I’ll be doing this refresh again each time IntelliJ releases a new major version. Might as well keep things clean and charging forward.

Inversoft Partners with Metaverse Mod Squad

  

Inversoft announced last week a new partnership with Metaverse Mod Squad. The full press release can be viewed at http://www.prweb.com/releases/2010/03/prweb3702164.htm

We are very excited about this new partnership and know that it will help both companies serve our customers better. With the combination of Inversoft’s products and Metaverse Mod Squads services, our customers will be able to provide the best possible experience for their users.

Inversoft's new website and products

  

Last week Inversoft launched the Clean Speak family of products and our new website. Clean Speak is a complete rewrite of our old profanity products and our website is a complete rebrand of our company.

Clean Speak includes all of the same features of the older profanity products and many new ones. Here are some of the best features of Clean Speak:

  • Profanity Filter
  • Email Filter
  • URL Filter
  • Phone Number Filter
  • Management Interface
  • Integrated Testing Tools
  • Real-Time Database Updating
  • Real-Time Filtering
  • Content Moderation
  • Much More

Additionally, Clean Speak is much faster. We have the best performance available and that means our filter and moderation tools can be used in even the highest volume games and websites.

If you haven’t checked it out already, head over to http://www.inversoft.com and see what we’ve been working on.

Hibernate/JPA with missing tables

For some of the Inversoft products I’ve been adding new tables for new features into our standard schema. The tricky part with updating the database is also giving customers all the update scripts that they need to run and instructions on how to run them correctly.

I figured I’d see what happened if I added all the JPA Entity classes to the persistence.xml file and didn’t update the database. Since none of the existing JPA Entity classes was changed, the application appears to work fine without the tables in the database.

This is good news for me as it allows me to ship new versions of the application without any fear of breaking customers who don’t update their database. This is true only if that customer doesn’t use any of the new features that access the new tables.

Fixing Java tools on Snow Leopard

I was attempting to work with VisualVM and Tomcat over the past few days on Snow Leopard and it was constantly failing. I was getting errors like this:

    "attach: task_for_pid(59980) failed (5)"

I was also getting errors inside VisualVM and from the command like using jmap that went like this:

Attaching to process ID 61218, please wait...
sun.jvm.hotspot.debugger.NoSuchSymbolException: Could not find symbol "heapOopSize" in any of the known library names (-)
	at sun.jvm.hotspot.HotSpotTypeDataBase.lookupInProcess(HotSpotTypeDataBase.java:399)
	at sun.jvm.hotspot.HotSpotTypeDataBase.readVMIntConstants(HotSpotTypeDataBase.java:319)
	at sun.jvm.hotspot.HotSpotTypeDataBase.<init>(HotSpotTypeDataBase.java:88)
	at sun.jvm.hotspot.MacOSXTypeDataBase.<init>(MacOSXTypeDataBase.java:36)
	at sun.jvm.hotspot.bugspot.BugSpotAgent.setupVM(BugSpotAgent.java:578)
	at sun.jvm.hotspot.bugspot.BugSpotAgent.go(BugSpotAgent.java:499)
	at sun.jvm.hotspot.bugspot.BugSpotAgent.attach(BugSpotAgent.java:337)
	at sun.jvm.hotspot.tools.Tool.start(Tool.java:163)
	at sun.jvm.hotspot.tools.HeapDumper.main(HeapDumper.java:77)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:597)
	at sun.tools.jmap.JMap.runTool(JMap.java:179)
	at sun.tools.jmap.JMap.main(JMap.java:110)
Debugger attached successfully.
sun.jvm.hotspot.tools.HeapDumper requires a java VM process/core!

And I also got some other strange errors from jmap like this one:

61218: Unable to open socket file: target process not responding or HotSpot VM not loaded
The -F option can be used when the target process is not responding

I opened an issue with the VisualVM team and they tested things out on Snow Leopard and said it all worked fine. I figured they were smokin’ something and decided to try a Sun product and see if it worked. I fired up NetBeans and sure enough, VisualVM and jmap worked great. This indicated it was definitely a VM configuration issue.

Here’s the what you need to do to get your Java applications working with the VM tools on Snow Leopard. Add the following parameters to the java command and everything will start working fine:

java -Xverify:none -Xshare:off -Xcom.sun.management.jmxremote

The -Xverify:none is the setting that allows VisualVM and jmap to capture thread dumps. Without this setting, you’ll get strange errors like those above. The -Xshare:off gets VisualVM working without any startup errors or random failures. The last setting is really just for JConsole and other JMX tools.

Enjoy!

C++ references

Assigning reference return value to a variable

When assigning a reference return value to a variable, a copy is made. Here is an example:

class References {
private:
    std::string name;

public:
    References(const std::string& name) : name(name) {
    };

    virtual ~References() {
    };

    const std::string& getName() const {
        return name;
    };
};

References r("foo");
std::string n = r.getName();

This code makes a copy of the name member variable from the References class and puts the copy into the variable n.

Assigning reference return value to a reference variable

When assigning a reference return value to a reference variable, no copy is made. Here is an example:

class References {
private:
    std::string name;

public:
    References(const std::string& name) : name(name) {
    };

    virtual ~References() {
    };

    const std::string& getName() const {
        return name;
    };
};

References r("foo");
const std::string& n = r.getName();

This code does not make a copy of the name member variable. Instead, the reference variable is now a reference directly to the member variable inside the class.

Passing a reference return value to a method that takes a reference

When you pass the return value from a method that returns a reference directly into a method that takes a reference, no copy is made. Here is an example:

class References {
private:
    std::string name;

public:
    References(const std::string& name) : name(name) {
    };

    virtual ~References() {
    };

    const std::string& getName() const {
        return name;
    };
};

void print(const std::string& s) {
    ...;
}

References r("foo");
print(r.getName());

This passes the reference returned directly into the method as a reference. Therefore, no copy is made.

Using a reference method in a comparison operator

This is the same as the method invocation example above because all operators take references.

Fixing macbook wake up problems

One of the family Apple notebooks (a Macbook) was having some issues waking up from sleep periodically. It was also having issues when the lid was closed the fan would constantly spin as though the machine was overheating. I took the machine into the only Apple store I trust (the main tech there is pretty solid, although he still doesn’t use Terminal). The fix was pretty simple:

  1. Open up Terminal (Google it if you’ve never done it)
  2. Type in ‘cd /var/vm’
  3. Type in ‘rm sleepimage’

It looks like this:

$ cd /var/vm
$ rm sleepimage

This should fix any issues with sleeping and waking up. The root cause is that if you move the machine to fast, have any static electricity and shock the machine, or otherwise jostle it too much when it is going into sleep mode (just after you close the lid), the sleep image will become corrupt and you’ll start having issues.

Generic variable to the current type

I just noticed that I’ve been using the Builder pattern with method chaining a lot. Looks like this:

FooBuilder builder = new FooBuilder();
Foo foo = builder.add(...).divide(...).multiple(...).builder();

The issue that arises is that I want to store a bunch of methods in a base class that various builders can use. In order to do this correctly, I have to really hack up my classes with some strange generics and unchecked casts like this:

public class BaseBuilder<T extends BaseBuilder> {
  public T add(...) {
    ...
    return (T) this;
  }
  public T divide(...) {
    ...
    return (T) this;
  }
  public T multiply(...) {
    ...
    return (T) this;
  }
}

public class FooBuilder extends BaseBuilder<FooBuilder> {
  public Foo build() {
    ...
  }
}

This is really annoying. I think every class should have a generic type variable that references the current type and let the compiler figure it out. Just name the variable ME or something. It would make the code look like this instead:

public class BaseBuilder{
  public ME add(...) {
    ...
    return this;
  }
  public ME divide(...) {
    ...
    return this;
  }
  public ME multiply(...) {
    ...
    return this;
  }
}

public class FooBuilder extends BaseBuilder{
  public Foo build() {
    ...
  }
}

Now that’s much nicer looking.

Inferred typing

I know that .Net 4 is going to have some pretty cool features around dynamic typing and C++0x is also adding some auto typing features. I was thinking about all of this today and realized that what I really use most of the time is an inferred type. Essentially it would infer a new type based on the method’s contents.

Let’s say we have this:

public void callSomeMethod(Object obj) {
  obj.methodCall();
}

In static languages this fails because Object doesn’t contain the method methodCall. However, what if we told the compiler to create a new interface based on the content of the method? This code would then look like this:

public void callSomeMethod(autotype obj) {
  obj.methodCall();
}

The autotype keyword would cause the compiler to actually create this code:

public interface MethodCallInterface {
  void methodCall();
}

public void callSomeMethod(MethodCallInterface obj) {
  obj.methodCall();
}

This would now compile. Next, a caller to this method could pass in any object whose type the compiler could add this interface to. If you called it like this:

public class MyClass {
  public void methodCall() {
    System.out.println("Here I am");
  }
}

// Some other code somewhere
MyClass mc = new MyClass();
callSomeMethod(mc);

The compiler could take the interface it created for this method call and then see if the type passed in could implement that interface. If MyClass has already been compiled, it could do one of two things:

  • If MyClass is accesible as part of the current compilation unit, it could update the compiled Class to implement the interface
  • If it isn’t part of the current compilation unit and isn’t final, it could create a proxy for the call that implements the interface and delegates the call

Not sure yet how #2 really works or if it even makes sense to do it that way, but it seems to be the only way to make it work if the Class is in a JAR or DLL or something like that.

The only issue would be reflection. How could you reflection on the method and then pass an Object to it so that it would not completely blow chunks at runtime? Perhaps the reflective method invocation could determine if the object being passed could be proxied to the dynamic interface and then create a proxy on the fly.

Anyways, just pondering type systems in general today….