Wednesday, August 13, 2014

Groovy Notes: Pretty print JSON from the command line

JSON pretty print it's common task while working with JSON from command line. There are many ways of doing this via Python, Ruby, node.js, but here I'd like to concentrate on Groovy one-liner:

$ echo '{"foo": "lorem", "bar": "ipsum"}' | groovy -e 'import groovy.json.*; println JsonOutput.prettyPrint(System.in.text)'

{
    "foo": "lorem",
    "bar": "ipsum"
}

We can slightly improve this one-liner via adding shell alias:
$ alias pp="groovy -e 'import groovy.json.*; println JsonOutput.prettyPrint(System.in.text)'"
$ echo '{"foo": "lorem", "bar": "ipsum"}' | pp

Also, we might use Groovy script which might be handy for simple JSON validation also:

$ cat prettyJson.groovy 
import groovy.json.*

try {
  println JsonOutput.prettyPrint(System.in.text)
} catch (JsonException e) {
  println "ERROR: Not valid JSON"
  System.exit(1)
}

$ echo '{"foo: "lorem", ' | groovy prettyJson.groovy
ERROR: Not valid JSON

Tuesday, August 12, 2014

How to disable Tomcat session serialization


Suppose you have the next error while restart/stop Tomcat (in my case Tomcat 7.x):
WARNING: Cannot serialize session attribute SPRING_SECURITY_CONTEXT for session 54DBA076EDC9B7A24C1AF76824DFD1EF
java.io.NotSerializableException: com.MyClass
 at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1180)
 at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1528)
 at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1493)
 at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1416)
 at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174)
 at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:346)
 at java.util.ArrayList.writeObject(ArrayList.java:710)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 at java.lang.reflect.Method.invoke(Method.java:601)
 at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:975)
...
It means that Tomcat is trying to persist non-serializable objects which were added into the session. Tomcat uses Manager component which is used to create and maintain HTTP sessions for web application.

By default manager implementation configured to perform session persistence across restarts and we want to disable this functionality.
To disable this persistence feature, create a Context configuration file (context.xml) for your web application and add the following element there:

<Manager pathname="" />

You can add this context.xml file to:
  • App.war:/META-INF/context.xml
  • TOMCAT_HOME/conf/Catalina/localhost/App.xml file
  • TOMCAT_HOME/cont/context.xml
References