Tag Archives: java

Groovy is a language

A few years ago I wrote a few Groovy language scripts to help with some configuration and testing needs. I discussed these with my co-workers. But, lo and behold, for weeks they thought I was saying that the scripts were Groovy, as in cool, not Groovy as in the JVM based dynamic language. They never heard of Groovy. We had a big laugh.

This situation made me think again that developers have differing interests in their field. No offense, but a certain percentage just go to work and do what is required and punch out at the end of the day. It is Java today, but it may as well be COBOL, there is always opportunity to copy and paste and do the minimum to “solve” the current business stakeholder requirements.

I’m sure this is only true for some corporate IT environments which have a top down rigid structure and legacy applications. Introducing change into the software process and tools is difficult. Stability and safety is paramount. Thus, the worker who toes the line and is not disruptive is an asset. Sure, there is talk of change and new techniques, but at the end of the day: “no, we can’t use that, we have this.” The new web businesses and open-source projects are different, of course.

BTW, Groovy is now slowly being used in my company. But, not sure many have heard of it yet.

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

Java reflection on a message using MethodHandle

Some code I was looking at recently had an overloaded method and each method just accepted a different type argument. With Generics there are probably ways to reduce this clutter, or not.

Anyway, I started thinking about the original concept of OO; it was all about ‘messages’. But what is the difference between a ‘message’ as per Alan Kay and Smalltalk and a method’, née “subroutine” in Java? I guess it’s intent, design, and the other features of OOP?

Jump to example source code

Following this line of thought I wound up looking at how to invoke a public method on a class and that method in turn delegates to private methods that match the data within the message. BTW, this is not a new concept, it is an often used ‘idiom’, like in servlets and other backend service handlers.

The public method is the destination of a ‘message’. So I searched the web and found mention of the usual Reflection, Proxies, instanceof, and finally MethodHandles. The package java.lang.invoke contains the new approach to reflection introduced in Java 7. MethodHandle is the new class that makes all this possible.

Not much on MethodHandle on the web (search instead for: java “method handle”), but the API docs are very good and this blog post, “A glimpse at MethodHandle and its usage”, is all you need to get started. Below in Listing 1, a simple example is shown. Class Server has a single method that takes a String message and a parser.

The message contains the data that is used to determine the actual method to invoke. Simple, but the point is that this could be a JSON/XML string or some other data container. The parser is just me experimenting with callbacks, here the callback gets the data in the message. Yeah, I know, if the client can get the data, why not just send it? It’s just a ‘hello world’ example.

Example
In listing 1 the Service class exposes one method, send.

public class Service {	
    public Object send(String message, Parser parser) throws Throwable {
	Object pData = parser.parse(message);		

	MethodType methodType = 
          MethodType.methodType(
            Object.class,pData.getClass());		

	MethodHandle mh = MethodHandles.lookup()
         .findVirtual(
            Service.class, "call", methodType);		

	Object actual = mh.invoke(this,pData);		
	return actual;
    }

    @SuppressWarnings("unused")
    private Object call(String data) {
	System.out.println("in string method ...");
	return "string data";
    }

    @SuppressWarnings("unused")
    private Object call(Integer data) {
	System.out.println("in int method ...");
	return new Integer(42);
    }
	
    public interface Parser{
	public Object parse(String s); 
    }
}

Listing 1

In listing 2, the Main class sends the message to the Service class.

public class Main {    
    public static void main(String[] args) throws Throwable {
      Service app = new Service();
      Service.Parser parser = new Parser();   

      Object actual = app.send("some text", parser);
      assert actual == "string data" 
        : "Should have returned 'some data' string";
        
      actual = app.send("number: 42",parser);
      Integer expected = 42;
      assert (actual.equals(expected)) 
         : "Should have returned Integer with value 42";
  }
    
  static class Parser implements Service.Parser{                  
      @Override
      public Object parse(String s) {
          if(s.startsWith("number:")){                            
              Integer i = Integer.valueOf(  
                  (s.split(":")[1]).trim() );
              return i;
          }
          
          return s;
      }
  }
}

Listing 2

Not earthshaking of course. The output is:
in string method …
in int method …

The example is somewhat like the javax.servlet.Servlet class, only one method, service(ServletRequest req,ServletResponse res) is also used, and usually one invokes other methods based on the “message” params.

I can see the use of MethodHandles leading to some powerful mojo.

Links

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

Groovy Object Notation using ConfigSlurper

In an old post in 2010 I was exploring the idea of using Groovy syntax as a data interchange format, GrON, just as JSON is a “subset” of Javascript.

Just noticed that Groovy has, since version 1.5, the ConfigSlurper class. “ConfigSlurper is a utility class for reading configuration files defined in the form of Groovy scripts. Configuration settings can be defined using dot notation or scoped using closures.”

Example use of ConfigSlurper

We can store a configuration found on the ConfigSlurper API page into a section of an Inix file:

[>configuration/finance]
    grails.webflow.stateless = true
    smtp {
        mail.host = 'smtp.myisp.com'
        mail.auth.user = 'server'
    }
    resources.URL = "http://localhost:80/resources"
[<configuration/finance]

Then to read it we just load that section and parse with a ConfigSlurper. As shown below.

import static org.junit.Assert.*;
import org.junit.Test;
import com.octodecillion.util.inix.Inix

class ExampleSlurpInix {
  @Test
  public final void test() {		
  	def scriptString = new Inix('resources\\test-data.inix')
              .load("configuration/finance")

  	def config = new ConfigSlurper().parse(scriptString)
		
  	assert config.toString() == 
  	'[grails:[webflow:[stateless:true]], smtp:[mail:[host:smtp.myisp.com, auth:[user:server]]], resources:[URL:http://localhost:80/resources]]'
  }
}

That’s one of the application types I was envisioning GrON to be used for: An easier format to store and transfer configuration, test, and other types of data. The issue is that as noted in the original post, this is insecure for use as data interchange unless a GrON parser that does not execute Groovy is used.

Links

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

Groovy implementation of INIX file format, part 2

Continued experimentation with the INIX “ini” file format. I take the original post code and add an alias feature.

Background
In three prior posts I presented a very simple metadata file storage approach. Pretty much using the INI file format with the sections as “heredocs.” In original INI format, afaik, the data within the sections were properties only, x=y.

Updates

  • Dec 25, 2015: Just saw a mention of Tom’s Obvious, Minimal Language (TOML) This is not directly related to what I’m after with Inix, but interesting as an example of a simple markup language.
  • Alias
    Now I am working on adding the ability for a section of data to load data from another section. The sections to load are indicated by the ‘@’ symbol and then the section path. Multiple sections can be indicated. Though I’m using the term ‘alias’ for this, perhaps a better term is ‘importing’. So far, I can parse the alias from the tag string.

    I have not implemented the actual import. One complexity left to solve is recursion. If this section imports another section, what if that section imports others sections?

    Alias use case
    Since currently the Inix file format is being used for test data, aliasing allows reuse of data without duplication, i.e., DRY. This is problematic with hierarchical data like JSON or XML, but much easier with lists or maps. Further features like overriding and interpolation would be useful for Java Properties data. The goal would be to eventually support use of the Cascading Configuration Pattern.

    Example 1

    [>First]
    Data in first    
    [<]
    
    [>Second@First]
    Data in second
    [<]
    

    Now when the data in section “Second” is loaded, the data from the aliased section is prepended to the current section data:

    Data in first    
    Data in second
    

    Tag format
    The section tag format is now: [>path#fragment@aliases?querystring]. Note that unlike a URI, the fragment does not appear at the end of the string.

    The section ID is really the path#fragment. Thus, the end tag could be [<] or can use the section ID: [<path#fragment]. Example 2

    [>demo1/deploy#two@account897@policy253?enabled=true&owner=false]
    stuff here
    [<demo1/deploy#two]
    

    Grammar
    The start of a grammar follows, but has not been ‘checked’ by attempted use of a parser generator like Antlr.

    grammar Inix;
    section: start CRLF data end;
    start: '[>' path (fragment)?(alias)*('?' args)? ']';
    end: '[<' path? ']';
    path: NAME ('/' NAME)*;
    fragment: '#' NAME;
    alias: '@' NAME
    args: (NAME=NAME ('&' NAME=NAME)*)?;
    data: (ANYTHING CRLF)*;
    NAME: ('a'..'z' | 'A'..'Z')('a' .. 'z' | 'A'..'Z'|'0'..'9'|'_');
    
    TODO:

    1. Do the actual import of aliased section data.
    2. Allow multiple params per param key: ?measure=21,measure=34,measure=90. Or better yet, just allow array in arg string: measure=[21,34,90],color=red

     

    Implementation
    Source code available at Github: https://gist.github.com/josefbetancourt/7701645

    Listing 2, Implementation

    Test class
    Note that there are not enough tests and the implementation code has not been reviewed.

    Listing 3, Test class

    The test data is:

    Listing 4, data file

    Environment
    Groovy Version: 2.2.2 JVM: 1.7.0_25 Vendor: Oracle Corporation OS: Windows 7

    Further Reading

    1. The Evolution of Config Files from INI to TOML
    2. Groovy Object Notation using ConfigSlurper
    3. Configuration Files Are Just Another Form of Message Passing (or Maybe Vice Versa)
    4. INI file
    5. Data File Metaformats
    6. Here document
    7. JSON configuration file format
    8. Creating External DSLs using ANTLR and Java
    9. Groovy Object Notation (GrON) for Data
      Interchange
    10. Cloanto Implementation of INI File Format
    11. http://groovy.codehaus.org/Tutorial+5+-+Capturing+regex+groups
    12. URI
    13. Designing a simple file format
    14. The Universal Design Pattern
    Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

    Regex group capture with optional delimeter

    Ever had one of those days where the simplest thing seems complex? A simple regex is doing that to me now.

    This is the example, simplified. You have a string “BEFOREAFTER”. If this string has a ‘x’ in it, you want to capture everything before the ‘x’, else you want to capture the whole string. So,
      “BEFOREAFTER” gives “BEFOREAFTER”
      “BEFORExAFTER” gives “BEFORE”

    jump to solution

    Yes, I know this can be done programmatically or just using String.split(….). Don’t you hate on Stackoverflow and other places where they say don’t do it that way, but you still want to know: yes, but if I do choose this way, how would it be done? This is a learning incident.

    This should be easy, regex 101, right? I thought so too. I thought /^(.*)x?.*/ would work, nope. I tried captures with non-greedy quantifiers, zero-width this or that, etc. I even went back to reading Mastering Regular Expresssions by Jeffrey E. F. Friedl, O’Reilly Media, Inc. Great book by the way.

    My solution just has to be wrong. Here it is written using the Groovy language.

    def re = /^(.*)x|^(.*)/
    
    getCaptureGroup(re,"BEFORExAFTER")
    getCaptureGroup(re,"BEFOREAFTER")
    getCaptureGroup(re,"")
    getCaptureGroup(re,null)
    getCaptureGroup(null,"x")
    
    def getCaptureGroup(regex, inString){
      def found = ""	
    
      def m = (inString =~ regex)
      if(m){
        List matches = (List)m[0]		
        found =  matches[1] ? matches[1] : 
          (matches[2] ? matches[2] : "")
       }	
    	
       println "Using pattern $regex in String '$inString', 
        found group: '($found)' of type: ${found.getClass().getSimpleName()}"
    }
    

    The output of this script is:

    Using pattern ^(.*)x|^(.*) in String 'BEFORExAFTER', found group: '(BEFORE)' of type: String
    Using pattern ^(.*)x|^(.*) in String 'BEFOREAFTER', found group: '(BEFOREAFTER)' of type: String
    Using pattern ^(.*)x|^(.*) in String '', found group: '()' of type: String
    Using pattern ^(.*)x|^(.*) in String 'null', found group: '(null)' of type: String
    Using pattern null in String 'x', found group: '()' of type: String
    


    Any other way of designing the regex using the Java regex engine?

    Solved
    I found a Stackoverflow entry that solved a similar question here.

    So the solution is now:

    def re = /^(.*?)(?:x.*|$)/
    
    getCaptureGroup(re,"BEFOREAFTER")
    getCaptureGroup(re,"BEFORExAFTER")
    getCaptureGroup(re,null)
    getCaptureGroup(null,"x")
    println ""
    
    def getCaptureGroup(regex, inString){
      def found = ""
    	
      def m = (inString =~ regex)
      if(m){
      	List matches = (List)m[0]		
      	found =  matches[1]
      }	
      
      println "Using pattern $regex in String '$inString', 
        found group: '($found)' of type: ${found.getClass().getSimpleName()}"
    }
    

    Or as one line:
    println ((“BEFORExAFTER” =~ /^(.*?)(?:x.*|$)/)[0][1])

    Further reading

    Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

    Don’t let Java varargs limit an API

    Was looking at Simple Logging Facade for Java (SLF4J), a Java logging library. One nice feature is that one can use message formats that don’t get evaluated until the log statement is executed, which in turn depends on the log level.

    It seems, maybe I missed it, that using this feature disallows you from logging exceptions. For example, you can log a complicated string and the exception like so:

    logger.error("Oh no, thing '" + 
         thing + "' took down the system!", ex);
    

    Alternatively, you can use SLF4J’s message formatting to avoid the costly String manipulations, and just pass in the ‘thing’ object and anything else needed in the message as varargs:

    logger.error("Oh no, thing '{}' 
         took down the system!", thing);
    

    But, where to you chain in the exception that caused this?

    Solution?

    Add to the API:

    void error(String format, Throwable t, Object... arguments)
      Log an exception and message at the ERROR level according to the 
      specified format and arguments.
    
      This form avoids superfluous string concatenation when the 
      logger is disabled for the ERROR level. However, this variant 
      incurs the hidden (and relatively small) cost of creating an 
      Object[] before invoking the method, even if this logger is 
      disabled for ERROR. The variants taking one and two arguments 
      exist solely in order to avoid this hidden cost.
    
       Parameters:
           format    - the message accompanying the exception
           t         - the exception (throwable) to log
           arguments - a list of 3 or more arguments
    

    Then the log could have been done as:

    logger.error("Oh no, thing '{}' 
        took down the system!", ex, thing);
    

    But…
    Of course, I’m sure the developers of SLF4j, and other libraries that change their API to take advantage of varargs, have very good reasons for the resulting changes and “limitations”.

    Varargs should be used sparingly?
    One advice given in Java docs is:
    “… you should not overload a varargs method, or it will be difficult for programmers to figure out which overloading gets called”.

    Resources

    Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

    Groovy template fails if language keywords used

    While using the SimpleTemplateEngine to process a template with a “$package” expression I got an error. Rename this expression to “$pack” and it works.

    Puzzling. Then I looked at the source code for the template engine. Oops, forgot that Groovy uses script parsing of text to implement many powerful features, like templates. Kind of like extreme EYODF*. Thus, a snippet of the source code for SimpleTemplateEngine shown in listing 1 below, the word “package” is interpreted as the Java language keyword “package“.

    try {
      template.script = groovyShell.parse(script, "SimpleTemplateScript" + counter++ + ".groovy");
    } catch (Exception e) {
      throw new GroovyRuntimeException("Failed to parse template script (your template may contain an error or be trying to use expressions not currently supported): " + e.getMessage());
    }
    
    Listing 1

    Below is an example of this.

    def templateText = '''package $package;'''
    
    def engine = new groovy.text.SimpleTemplateEngine(true)
    def template = engine.createTemplate(templateText)
    def binding = ['package':'a/b/c']
    
    def s = template.make(binding)
    println s
    
    Listing 2

    Results in:

    Caught: groovy.lang.GroovyRuntimeException: Failed to parse template script (your template may contain an error or be trying to use expressions not currently supported): startup failed:
    SimpleTemplateScript1.groovy: 1: unexpected token: package @ line 1, column 23.
       out.print("""package $package;""");
                             ^
    
    1 error
    

    Now change the expression to $pack:

    def templateText = '''package $pack;'''
    
    def engine = new groovy.text.SimpleTemplateEngine() // pass in true to see debug output
    def template = engine.createTemplate(templateText)
    def binding = ['pack':'a/b/c']
    
    def s = template.make(binding)
    println s
    
    Listing 3

    And, the result is:

    package a/b/c;
    

    Environment

    • Groovy Version: 2.2.2 JVM: 1.7.0_25 Vendor: Oracle Corporation OS: Windows 7
    • Eclipse 4.3
    • Groovy-Eclipse Feature: 2.9.0.xx-20140228-1800-e43-SNAPSHOT

    Some links

    EYODF*: “Eat Your Own Dog Food”

    Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

    Enum to Switch on Class types in Java and Groovy

    The Java Switch statement is usually considered a code smell since it’s use can be eliminated by better use of Object Oriented Programming (OOP) design. Nowhere is this more apparent than with a related technique: attempting to switch on Class types by using the instanceof operator.

    Real world
    Unfortunately, in the real world, OOP is sometimes lacking. The code may be using a minimal interface based design. Refactoring, redesigns, or sophisticated OO legerdemain cannot be used in such a project. What’s worse, these projects typically have no unit tests.

    In this situation, one must resort to use of ‘switch’ or nested “if else”. This is a situation I recently encountered with legacy code that used if-else conditionals and instanceof since the target classes had no commonality. I was curious at the alternatives, so wrote up this blog post.

    Important! The examples here do not reproduce the actual usage of the instanceof, wherein inheritance is taken account. See this Stackoverflow article for some info.

    Groovy approach
    In Groovy this is much easier since the switch statement supports much more types to switch on. In listing 1 below we simply use the classes directly. Note that this is not documented anywhere, afaik.

    Groovy Example source
    Listing 1

    package com.octodecillion.experiment
    
    class GroovySwithOnClass {
    
        static main(args) {
            
            switch(Class2.class){
                case Class1.class:
                    assert false
                    break
                case Class2.class:
                    assert true
                    break
                case Class2.class:
                    assert false
                    break
                default:
                    assert false
            }    
        }
        
        public static class Class1{}
    
        public static class Class2{}
    
        public static class Class3{}
    
    }
    

    Now that is sweet and to the point!

    Just to see if possible, one could explicitly switch on a Closure’s hashCode as follows:

    class SwithOnClosure {
    
        static main(args) {
            Closure cl1 = {}
            Closure cl2 = {}
            Closure cl3 = {}
            
            switch(cl2.hashCode()){
                case cl1.hashCode():
                    assert false
                    break
                case cl2.hashCode():
                    println "on cl2"
                    assert true
                    break
                case cl3.hashCode():
                    assert false
                    break
                default:
                    assert false
            }
        }
        
    }
    

    For some more Groovy Enum goodness, the reading list at end gives some more examples.

    Java Approach
    In contrast to the Groovy used above, in Java things get more wordy. Below in listing 2 a JUnit class illustrates two methods of using a switch that acts on Class types.

    Java 7
    The method “testOnJava7” shows that in Java 7 the switch can be on String values, so we just use the fully qualified class name (FQCN) as the case labels. This is not optimal, of course, any change to package or class names would break the switch.

    Unfortunately, you can’t use the class name found by, for example, Class1.class.getName(), to use for the case labels. The case labels must be “constant expressions“. Even creating String “constants” with private final String CLASS1 = …. would not work, afaik.

    Tip: In Java 7 the switch works with:
    • char
    • byte
    • short
    • int
    • Character
    • Byte
    • Short
    • Integer
    • String
    • Enum type
     

    Java 6
    In Java 6, the ‘switch’ is more limited. In method “testOnJava6” we create an Enum ‘Switcher’ that stores the FQCNs of the classes to switch on. To allow the conversion of class name to enum we have to implement the ‘fromString(String className)’ method (learned this in “Effective Java”).

    Java Example source
    Listing 2

    package com.octodecillion.experiment;
    
    import static org.junit.Assert.fail;
    import java.util.HashMap;
    import java.util.Map;
    import org.junit.Test;
    
    /**
     * @author josef betancourt
     */
    public class SwitchOnClass {    
        @Test
        public final void testOnJava7(){        
            switch(Class1.class.getName()){        
                case "com.octodecillion.experiment
                    .SwitchOnClass$Class1":
                    break;                
                case "com.octodecillion.experiment
                    .SwitchOnClass$Class2":
                    fail();
                    break;
                case "com.octodecillion.experiment
                    .SwitchOnClass$Class3":    
                    fail();
                    break;
                default:
                    fail();                    
            }        
        }
    
        @Test
        public final void testOnJava6() {
            switch(Switcher.fromString(Class1.class.getName())){            
                case CLASS1:
                    break;
                case CLASS2:
                    fail();                
                    break;
                case CLASS3:
                    fail();
                    break;                
                default:
                    fail();            
            }        
        }
    
        /** enum type that stores the class names as field */
        public static enum Switcher{        
            CLASS1(Class1.class),
            CLASS2(Class2.class),
            CLASS3(Class3.class);    
            
            private static final Map<String,Switcher>classNameToEnum = 
                 new HashMap<String, Switcher>();
            
            static{
               for(Switcher sw : values()){
                    classNameToEnum.put(sw.className, sw);
                }            
            }
            
            /** convert class name to the enum type */
            public static Switcher fromString(String className){
                return classNameToEnum.get(className);
            }
            
            private String className;
            
            // constructor
            Switcher(Class<?> klass){
                this.className = klass.getName();
            }
            
        } // end enum Switcher
        
        public static class Class1{}
    
        public static class Class2{}
    
        public static class Class3{}    
    }
    

    Alternatives
    1. Don’t do any of the above. Use instanceof to invoke a method specific to the target class. In this way future maintenance and possible OO refactoring can be done. This is possible with the Enum use too, but may be using the Enum for the wrong reason.

    2. An alternative is to change the classes in question to partake in the enum use as shown by Gaʀʀʏ in a Stackoverflow article. This, imho, is not a good approach since it mixes concerns.

    3. Still another approach was suggested by a colleague: switch on the hash code of a class, this would remove the maintenance of an Enum just for use of an instanceof replacement.

    4. An interesting approach is to forgo the use of a switch altogether and just use the enum to invoke type specific behavior. A state machine? See “Avoid switch! Use enum!

    5. Use the Visitor Pattern. However, this assumes you have or can modify the existing classes.

    Updates
    Feb 13, 2014: Changed the format of the post.
    Feb 15, 2014: added example with closures.
    Nov 7, 2015: Interesting discussion on the Guava project, Issue 562, IfElse and Switch Functions. The OP suggested something that would a Predicate and allow multiway conditionals. The commentators said it was not “Java”, so won’t fix.

    Environment

    • Windows 7
    • Eclipse 4.3
    • Java 7
    • JUnit 4
    • Groovy 2.2

    Further reading

    Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

    Unable to dock detached Eclipse Console window

    When the Eclipse IDE ‘breaks’ it seems to be unfixable. Like right now. I detached the Console view window via dragging onto another monitor. Done with it. Now I can’t dock the Console again inside the Java Perspective.

    The top left widget just shows a ‘close’ action. I tried closing projects, restarting Eclipse with “-clean”, and of course doing a search to see if this has been addressed by someone before. Sometimes it will go away and another docked Console will be used. But then it pops up again in float mode, and duplicating the output in the already docked Console, i.e., now two Consoles are showing the same thing.

    Reinstall Eclipse again????? Arrrrrrrrrrrrrr. Let me reboot Windoze first.

    I rebooted PC, rearranged Eclipse on the multi-monitor location, and the issue has not returned.

    Update

    1. The issue started again. I looked in the JUnit run configuration’s common tab for the test causing this. The “Launch in background” setting was checked. hmmm.
    2. Still not working. Second console window popup still appearing.
    3. Now trying the suggestion found here.
    4. Doh!!!!! I was dragging the window via the title bar. You have to drag via the tab title.

    I guess working in different environment made me lose my muscle memory gesture.
    Number 3 above fixed the popup reappearing.

    Environment

    • Eclipse 4.3 (Kepler)
    • Windows 7 Professional 64bit
    • Java 1.6 and 1.7
    • Dual monitor
    • UltraMon utility

    Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

    Set Java console output to “fine” logging level

    While coding a Java module I used java.util.logging output at the INFO level in the code to help development. This info is useful only during development. Are these output statements removed when development is done?

    The correct answer is that they should have been logged at the correct level, “debug“, or in java.util.logging’s NIH design, the FINE level. Thing is, the default configuration for console output blocks the FINE level. So, you have to configure the project’s logging appropriately.

    This task falls under the develotrivia (related to administrivia) category, the endless tasks that should be easy but draw attention from writing code.

    Fortunately I stumbled on a blog post by Michael R. Head that gives an easy way to configure the logger. Essentially it just creates a config string with text that normally would be put in a properties file. I took his example code and created a method that is invoked in the @Before method. Better yet, do this in the @BeforeClass method.

    /**
     * Based on code by MR Head
     * @author J. Betancourt
     */
    private void initLogging(){
        String config = "\n" + 
           "handlers = java.util.logging.ConsoleHandler" + "\n" + 
           ".level = ALL"+"\n"+
           "java.util.logging.ConsoleHandler.level = FINE" + "\n" +
           "com.sun.level = INFO" + "\n" +
           "javax.level = INFO" + "\n" +
           "sun.level = INFO" + "\n" +
           "";
    
    	InputStream ins = new ByteArrayInputStream(config.getBytes());
    
    	Logger logger = Logger.getLogger(this.class.getName());
    	try {
    	   LogManager.getLogManager().readConfiguration(ins);
    	} catch (IOException e) {
    	   logger.log(Level.WARNING, 
    	     "Log manager configuration failed: " + e.getMessage(),e);
    	}
    
    	logger.fine("Logger initialized");    
    	
    }
    

    Example Use

    @Before
    public void setUp() throws Exception {
    	initLogging();
    	graph = new Graph();
    }
    

    BTW, it is not difficult to configure the logger, just point to a configuration properties file using a JVM env variable setting, or point to a log manager class (I tried this, doesn’t work). I think Michael’s method is easier, especially for test driven development (TDD).

    Links

    Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.