Monday, February 18, 2013

Brainfuck plugin for Eclipse IDE

Features:
  • Brainfuck interpreter
    • launch configurations
    • launch configuration shortcut
  • Brainfuck editor
    • associates with *.b & *.bf files
    • syntax highlighting
    • code hover tool tips
    • loop select on double click
Repository: hg clone https://code.google.com/p/brainfuck-eclipse-plugin/

Enjoy!

Tuesday, November 13, 2012

Local functions prototyping

A trivial piece of C++ source code:
#include <iostream>

class Foo {
    public:
        Foo(int=5);
};

Foo::Foo(int) {
    std::cout << "[Foo]";
}

int main() {
    Foo Foo0();
    Foo Foo1(1);
    return 0; //SUCCESS?
}
And a trivial question: how many times will the Foo constructor execute?

Explanation:
in the above code, line:
    Foo Foo0();

is not a declaration of a variable named Foo0 of class Foo initialized with default constructor. Instead, it is, what can be called local function prototyping. More precisely, it is a declaration of a new function, named Foo0, which returns result of type Foo.

It seems to be legacy code after nested functions, supported by GCC C Compiler. See the example:
#include <stdio.h>

int main() {
 auto int m_nested();
 int m_nested() {
  return 666;
 }

 printf("%d", m_nested());
 return 0;
}
Function m_nested() is nested within another function (main()), and its scope is limited to that surrounding function.

Getting back to the original code, any attempt to access Foo0 will result in error:
int main() {
    Foo Foo0();
    Foo Foo() { //error: a function-definition is not allowed here before '{' token
        //...
    };
    Foo0(); // error: undefined reference to 'Foo0()'
    Foo0 = *new Foo(); // error: cannot convert 'Foo' to 'Foo()' in assignment
}
The only thing, that would make sense and would actually compile is defining this function somewhere else:
//...
int main() {
    // no access to Foo0() here
    Foo Foo0();
    Foo f = Foo0();
    //.. do some stuff with 'f'
    delete &f;
    return 0;
}

Foo Foo0() {
    std::cout << "Foo0()";
    return *new Foo();
}
Such code will narrow access to Foo0() to the place where it was declared for the first time, and will end as soon as the program leaves the execution block.

Monday, February 6, 2012

java.net.URL, content handlers and HTML/XML parsing

Below is an example of using java.net.ContentHandler class while retrieving resources from URL.

The objective is to get traffic stats from a network device. The device may present its status in two ways: as an XML data or human readable HTML page. In this example will use both the sources to get the information.

My network device collects data from different interfaces. The interface may be described as follows:

public class InterfaceStatus {
    private String name;
    private long txPackets;
    private long txBytes;
    private long rxPackets;
    private long rxBytes;
    
    // getters and setters...
}

To override default behaviour of the URL.getContent() method, a custom content handler factory must be created, i.e. class that implements ContentHandlerFactory interface. There's only one method to implement in this interface: public ContentHandler createContentHandler(String mimetype).

import java.io.*;
import java.net.*;

import javax.swing.text.html.parser.ParserDelegator;

import org.xml.sax.*;
import org.xml.sax.helpers.XMLReaderFactory;

public class UrlContentHandlerFactory implements ContentHandlerFactory {

    @Override
    public ContentHandler createContentHandler(String mimetype) {
        if("application/xml".equals(mimetype)) {
            return new XmlContentHandler();
        } else
        if("text/html".equals(mimetype)) {
            return new HtmlContentHandler();
        }
        // default content handler will be selected by JVM
        return null;
    }
    // ... inner *ContentHandler classes below...
}

The mimetype value is taken from the [JAVA_HOME]\lib\content-types.properties file. Now, it's time for the concrete implementation of the ContentHandler abstract class.

HtmlContentHandler
public class UrlContentHandlerFactory implements ContentHandlerFactory {
    // ...
    protected class HtmlContentHandler extends ContentHandler {

        @Override
        public Object getContent(URLConnection urlc) throws IOException {
            HttpURLConnection conn = (HttpURLConnection) urlc;
            if(conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                // using HTML Editor Kit API
                HtmlTrafficExtractor hte = new HtmlTrafficExtractor();
                new ParserDelegator().parse(new InputStreamReader(conn.getInputStream()), hte, true);

                return hte.getExtractedList();
            }
            return null;
        }
    } // HtmlContentHandler
}

To parse HTML pages, I've used HTMLEditorKit and ParserDelegator from javax.swing.text.html package. Why not to use XML parser? Here's the answer:

<html>
    <!-- head -->
    <body bgcolor=#00cccc>                <!-- no quotation marks around attribute value -->
        <img src="logo.gif" alt="Logo">   <!-- no closing "img" tag -->
    </body>
</html>

Although HTML pages consist of tags, tag attributes, text, etc., just as XML documents do, they don't have to conform to XML specification as illustrated in the above snippet. This would cause unnecessary exceptions being thrown.

XmlContentHandler
public class UrlContentHandlerFactory implements ContentHandlerFactory {
    // ...
    protected class XmlContentHandler extends ContentHandler {

        @Override
        public Object getContent(URLConnection urlc) throws IOException {
            HttpURLConnection conn = (HttpURLConnection) urlc;
            if(conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                // this is where the SAX2 API kicks in
                try {
                    XMLReader xmlReader = XMLReaderFactory.createXMLReader();
                    XmlTrafficExtractor te = new XmlTrafficExtractor();
                    xmlReader.setContentHandler(te);
                    xmlReader.setErrorHandler(te);
                    xmlReader.parse(new InputSource(conn.getInputStream()));

                    return te.getExtractedList();
                } catch(SAXException saxe) {
                    System.err.println("Parsing failed due to the following error: " + saxe.getMessage());
                }
            } // if
            return null;
        }
    } // XmlContentHandler
}

The content handler for XML documents is very similar. In contrast to the previous code, it uses SAX2 parser, which is a part of Java environment.

Both APIs use callback objects to parse documents. In HTML Editor Kit, the object must extend static HTMLEditorKit.ParserCallback class, and in SAX2 it is org.xml.sax.helpers.DefaultHandler.

HtmlTrafficExtractor
import javax.swing.text.html.HTMLEditorKit;

public class HtmlTrafficExtractor extends HTMLEditorKit.ParserCallback {
    private List<InterfaceStatus> statusList;

    // overriding essential callback methods here

    public List<InterfaceStatus> getExtractedList() {
        return statusList;
    }
}

XmlTrafficExtractor
import org.xml.sax.helpers.DefaultHandler;

public class XmlTrafficExtractor extends DefaultHandler {
    private List<InterfaceStatus> statusList;
    
    // overriding essential handler's methods here
    
    public List<InterfaceStatus> getExtractedList() {
        return statusList;
    }
}

Both the callback classes provide a method to return a list of available/found interfaces.

And here's how to use the code:

public class TransferStatus {
    private static final String URL_ADDRESS_XML = "http://router/stats/traffic.xml";
    private static final String URL_ADDRESS_HTM = "http://router/stats/netstat.html";

    public static final void main(String[] args) {
        URLConnection.setContentHandlerFactory(new UrlContentHandlerFactory());

        try {
//          Object content = new URL(URL_ADDRESS_XML).getContent();
            Object content = new URL(URL_ADDRESS_HTM).getContent();
            if(content != null && content instanceof List<?>) {
                @SuppressWarnings("unchecked")
                List<InterfaceStatus> statusList = (List<InterfaceStatus>) content;
                for(InterfaceStatus status : statusList) {
                    // doing things with the data
                }
            }
        } catch(IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

First, URLConnection.setContentHandlerFactory() static method is called to set the content handler factory. From now on, every call to URL.getContent() will ask the factory for a proper content handler (if none is found, i.e. the factory returns null, JVM will try to load default handler).
The next step is to check if the content returned is of correct type and further processing of the data.
Now, the only thing that changes in the above code is the resource URL address passed as an argument to the URL() constructor.

Friday, December 16, 2011

Initialization block as a constructor for anonymous class

Although not broadly used, [static] initialization blocks are quite interesting features in Java. They may be used to initialize static and instance fields with own default values, before a constructor kicks in. In byte-code, such blocks are represented by two special methods: void <clinit>() for static initialization block and void <init>() for instance initialization block. There may be multiple declarations of initialization blocks in one class. In such case the code from each block is combined into one of the above methods. All instructions are invoked in the same order as they were declared in source code. Example:

package net.progsign.java6;

public class InitializationBlockTest {
 
 private static char charValue;
 private boolean boolValue;
 private int intValue;
 private String stringValue;
 
 static {
  charValue = '$';
  System.out.println("[clinit] " + charValue);
 }
 
 {
  System.out.println("[init-0] " + boolValue);
  System.out.println("[init-0] " + intValue);
  System.out.println("[init-0] " + stringValue);
  System.out.println();
 }
 
 {
  boolValue = true;
  intValue = 1024;
  stringValue = "default";
 }

 public InitializationBlockTest() {
  System.out.println("[constr] " + boolValue);
  System.out.println("[constr] " + intValue);
  System.out.println("[constr] " + stringValue);
 }
 
 public static final void main(String[] args) {
  new InitializationBlockTest();
 }
}

The output of the above code will be:
[clinit] $
[init-0] false
[init-0] 0
[init-0] null

[constr] true
[constr] 1024
[constr] default

Good code design expects from us to initialize class fields in a constructor. Also, because of the characteristics of initialization blocks, it may cause some confusion when trying to understand the order in which the object is created.
However, there is a case where initialization block may be successfuly used. Examine the following code:

package net.progsign.java6;

interface IFace {
 int method();
}

public class AnonymousConstructor {
 public static void main(String[] args) {
  // anonymous class implementing IFace interface
  IFace foo = new IFace() {
   private int value;
   
   {
    value = 1024;
    init();
   }
   
   public int method() {
    return value;
   }
   
   private void init() {
    System.out.println("<init> called init()");
   }
  };
  System.out.println("[main] foo.method() = " + foo.method());
 }
}

In the above code, I declared an interface IFace and, in the main() method, I created anonymous class that implements this interface. My anonymous class has one private attribute value of type int. Because anonymous classes have no name, thus it's not possible to define own constructor (default non-argument constructor will still be created for the class by the compiler). Without initialization blocks, we would be unable to init the class field with our own values.

When compiled and run, the code will produce the following output:

<init> called init()
[main] foo.method() = 1024

Things to know about [static] initialization blocks:
  • there may be multiple initialization blocks in one class (they run in the order they occur in code)
  • they are invoked before any constructor
  • you can't call constructors (neither super() nor this()) from inside initialization block
  • same as constructors, initialization blocks may throw runtime exceptions (in such case the object will not be created)
  • you can assign default value to fields declared as final, but only if they haven't been initialized at declaration time



PS: noticed quite an interesting behaviour of initialization blocks. See the following code:

package net.progsign.java6;

public class InitializationTest {

 static {
  sfield = 1;
  //System.out.println("<clinit> " + sfield);
  //System.out.println("<clinit> sfield=" + InitializationTest.sfield);
 }
 
 {
  ifield = 2;
  //System.out.println("<init> " + ifield);
  //System.out.println("<init>   ifield=" + this.ifield);
 }
 
 static int sfield = 10;
 int ifield = 20;
 
 public static void main(String[] args) {
  InitializationTest it = new InitializationTest();
  System.out.println("[main]   sfield=" + it.sfield);
  System.out.println("[main]   ifield=" + it.ifield);
 }
}

Will the code compile? What will be the output? What will happen if you uncomment the "System.out.println(...)" lines?

Tuesday, October 11, 2011

OT: Chatting with Windows shell (VBScript)

Just a short memo on how to use WMI (Windows Management Instrumentation) and VBScript to simplify some administration tasks.

Rebooting remote machine (have to have privileges to WMI on the remote host):
Sub Reboot(host)
On Error Resume Next
    Set wmi = GetObject("winmgmts:{(Shutdown)}\\" & host & "\root\cimv2")
    If Err.Number <> 0 Then
        Exit Sub
    End If
    Set osList = wmi.ExecQuery("SELECT * FROM Win32_OperatingSystem")
 
    For Each os In osList
        os.Reboot()
    Next
End Sub

Checking host availability:
Sub Ping(host)
    Set pingStatus = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery("SELECT * FROM Win32_PingStatus WHERE address = '" & host & "'")
    For Each pingReplay In pingStatus
       If pingReplay.StatusCode = 0 Then
            WScript.Echo "Response: OK [Time (ms)=" & pingReplay.ResponseTime & "/TTL (ms)=" & pingReplay.ResponseTimeToLive & "]"
       Else
            WScript.Echo "No response from host '" & host & "'"
       End If
    Next
End Sub

Mounting network resources:
Sub Mount(folder)
On Error Resume Next
    Set NetworkObj = CreateObject("WScript.Network")
    Set ShellObj   = CreateObject("WScript.Shell")
    NetworkObj.MapNetworkDrive "X:", folder, true', "user", "pass"
    If Err.Number = 0 Then
        ShellObj.LogEvent 0, "Network resource '" & folder & "' mounted"
    Else
        WScript.Echo "Failed (Status code: " & Err.Number & ")"
    End If
End Sub

Thursday, September 29, 2011

Getting power source info from OS X (Objective-C)

I trust any introduction is unnecessary here, so will go straight to the code.
First approach is to use power source support methods from the IOKit/ps package. Here's how to do it:
#import <Cocoa/Cocoa.h>
#import <IOKit/ps/IOPowerSources.h>
#import <IOKit/ps/IOPSKeys.h>
#import "PowerSourceInfo.h"

@interface IOKitPowerSourceInfo : NSObject {

}

- (PowerSourceInfo*) getPowerSourceInfoFor: (int) index;

@end
... and the implementation:
#import "IOKitPowerSourceInfo.h"


@implementation IOKitPowerSourceInfo

- (PowerSourceInfo*) getPowerSourceInfoFor: (int) index {
 CFTypeRef info = IOPSCopyPowerSourcesInfo();
 CFArrayRef sources = IOPSCopyPowerSourcesList(info);
 PowerSourceInfo* psi = nil;

 int numOfSources = CFArrayGetCount(sources);
 if(numOfSources == 0) {
  return nil;
 }
 CFDictionaryRef source = IOPSGetPowerSourceDescription(info, CFArrayGetValueAtIndex(sources, index));
 psi = [[PowerSourceInfo alloc] initWithDictionary:(NSDictionary*)source];

 CFRelease(sources);
 CFRelease(info);

 return psi;
}

@end

Two functions, IOPSCopyPowerSourcesInfo() and IOPSCopyPowerSourcesList() are used to get information from the system and create list of available power sources. Then, by invoking IOPSGetPowerSourceDescription() function with references to our info object and particular source passed as arguments, we get a reference to a dictionary with all information about selected power source provided by vendor.
The key values for the dictionary are stored in IOKit/ps/IOPSKeys.h file. Unfortunately the dictionary does not have to contain values for all the keys as some of them, according to documentation, are optional.

Another apprach is to read system IO registry related to particular power source. The code is as follows:

#import <Cocoa/Cocoa.h>
#import <IOKit/IOKitLib.h>
#import "PowerSourceInfo.h"

@interface IORegPowerSourceInfo : NSObject {

}

- (PowerSourceInfo*) getPowerSourceInfo;

@end
and...
#import "IORegPowerSourceInfo.h"


@implementation IORegPowerSourceInfo

- (PowerSourceInfo*) getPowerSourceInfo {
 io_object_t deviceHandle;
 kern_return_t kernReturn;
 CFMutableDictionaryRef serviceMatch, properties;
 PowerSourceInfo* psi = nil;

 serviceMatch = IOServiceMatching("IOPMPowerSource");
 deviceHandle = IOServiceGetMatchingService(kIOMasterPortDefault, serviceMatch);
 kernReturn = IORegistryEntryCreateCFProperties(deviceHandle, &properties, NULL, 0);
 if(kernReturn == kIOReturnSuccess) {
  psi = [[PowerSourceInfo alloc] initWithDictionary:(NSDictionary*)properties];
 }
 CFRelease(properties);
 IOObjectRelease(deviceHandle);
 return psi;
}

@end

First, we get a dictionary matching IOService class called "IOPMPowerSource". Then we ask the system to return first IOService related to this class. Next step is to invoke IORegistryEntryCreateCFProperties, passing the device handle we just got, address of a pointer which will refer to a dictionary with all registry values of a particular power source. The function returns status code of type kern_return_t to inform whether it succeeded or failed. Finally, we have to release the memory.

In both examples, the PowerSourceInfo class is just a custom wrapper for the returned dictionary that exposes all keys as class methods.

OS X allows us to be notified about any changes that occur in different parts of the system (including power source chanage). To listen for those changes we have to create a RunLoopSource and attach it to current RunLoop. See the code below:

#import <Cocoa/Cocoa.h>
#import <WebKit/WebKit.h>
#import <IOKit/ps/IOPowerSources.h>

@interface PowerSourceInfoWorker : NSObject {
 WebView* webView;
 CFRunLoopSourceRef runLoopSource;
}

@property (readonly, nonatomic) WebView* webView;

-(void) startThread;
-(void) stopThread;

void powerSourceChange(void* context);

@end

PowerSourceInfoWorker is just a simple Cocoa class that exposes two messages: "startThread" and "stopThread" which will be used to add and remove our "listener" from system loop. The most important is the void powerSourceChange(void* context). It's a regular C function, which will be the callback from the loop.

NOTE: The WebView* webView attribute in the above code will be used later on to call JavaScript functions from the callback function.

Implementation of the PowerSourceInfoWorker:

#import "PowerSourceInfoWorker.h"


@implementation PowerSourceInfoWorker
@synthesize webView;

-(id) initWithWebView:(WebView*) aWebView {
 self = [super init];
 
 if(self) {
  webView = [aWebView retain];
 }
 return self;
}

-(void) dealloc {
 [self stopThread];
 [webView release];
 [super dealloc];
}

-(void) startThread {
 runLoopSource = (CFRunLoopSourceRef)IOPSNotificationCreateRunLoopSource(powerSourceChange, self);
 if(runLoopSource) {
  CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopDefaultMode);
 }
}

-(void) stopThread {
 if(runLoopSource) {
  CFRunLoopSourceInvalidate(runLoopSource);
  CFRelease(runLoopSource);
 } 
}

void powerSourceChange(void* context) {
 NSArray* args = [NSArray arrayWithObjects: @"Power Source has changed!", nil];
 id win = [[(PowerSourceInfoWorker*)context webView] windowScriptObject];
 [win callWebScriptMethod:@"jsCallback" withArguments:args];
}

@end

In startThread new IOPS RunLoopSource is being created. The two params are our callback function and context (which in this case is "self"). Then, this newly created source is attached to currenct RunLoop in default mode (see documentation for details about available RunLoop modes).
stopThread is responsible for removing our RunLoopSource from the system loop, by invoking CFRunLoopSourceInvalidate function, and releasing resources.
The callback function simply gets WebView* from the context, which in my case is the PowerSourceInfoWorker class itself (see: startThread), and calls some WebScript method with arguments passed as an array.

And here comes the JavaScript callback function (with one argument):

function jsCallback(msg) {
    document.getElementById('status').innerHTML = msg + ' (' + new Date().toUTCString() + ')';
    //refresh view
}

The code is quite obvious, and I believe does not need any explanation.

There's one big advantage of the latter method. It returns much more information about power sources available in system than the IOPSCopyPowerSourcesInfo. I wrote a simple Cocoa application to present the differences between those two methods. For source code see the following Mercurial repository:
hg clone https://code.google.com/p/osx-battery-info-app/

Saturday, July 9, 2011

The longest class name in Java

The first thing, that I noticed while working with Spring framework (right after its simplicity, purity, good performance, etc.) is that the designers of the framework didn't bother of creating short and simple names which resulted in a set of VeryLongSelfDescriptiveClassNames.

Curious enough, went throught the core Spring API and found two candidates for the title of "the longest class name in Java", and by the longes class name I mean a class name with no package prefix.

Those two candidates are:

AbstractInterruptibleBatchPreparedStatementSetter
AbstractTransactionalDataSourceSpringContextTests
both containing impressing 50 characters.

However, with Google's help found they're not the winners. The longes class name tends to be:
PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails
from Spring Security package, which is amazing 59 characters long.

Well self-described code or just a good sense of humor? Both, I guess.