Keep Walking!

Parsing Typescript in Go using QuickJS

This post is in series where I talk on how to parse Typescript code in Java and Go using v8go. Instead of using v8go, this time we will use QuickJS-Go to parse and obtain the abstract syntax tree.

As before, there are many use-cases on why this may be required:

  • you want to build a new documentation tool for Javascript/Typescript
  • you are building a new version of Hacker Rank
  • you want to enable scripting in your own code

Back to getting the job done, here are the broader steps:

  • Initialize and load QuickJS
  • Load Typescript JS library
  • Load the Typescript code that you would like to parse
  • And, finally call the TS parser code to obtain the AST

Let’s dig into the details. The first step is to initialize a new QuickJS instance. You would notice the use of runtime.LockOSThread() - this is to ensure that QuickJS always operates in the exact same thread.

// this is a must-step as per QuickJS documentation
stdruntime.LockOSThread()

// create new runtime
runtime := quickjs.NewRuntime()
defer runtime.Free()

// obtain a new context that we will work with
context := runtime.NewContext()
defer context.Free()

Once V8 is up, we need to load the Typescript JS code. We make use of a locally saved typescript.js file for the same. Read it in memory and then use the EvalFile method to load the script.

tsSource, err := ioutil.ReadFile("/path/to/ts/on/disk/typescript.js")
if err != nil {
    panic(err) // panic if load failed
}

// load TS source code
result, err := context.EvalFile(string(typeScript), 0, "typescript.js")
check(err)
defer result.Free()

Notice the use of check(err) function call above. It is a convenience function borrowed from the documentation that allows us to visit the stack/cause in case something fails inside the QuickJS runtime. The function is as under.

func check(err error) {
	if err != nil {
		var evalErr *quickjs.Error
		if errors.As(err, &evalErr) {
			fmt.Println(evalErr.Cause)
			fmt.Println(evalErr.Stack)
		}
		panic(err)
	}
}

Once Typescript is loaded, we need to build the compiler options to let TS know that we would like to use the latest syntax version for parsing.

// never free this - throws cgo error at app termination
globals := context.Globals()

ts := globals.Get("ts")
defer ts.Free()

scriptTarget := ts.Get("ScriptTarget")
defer scriptTarget.Free()

system := scriptTarget.Get("Latest")
defer system.Free()

args := make([]quickjs.Value, 4)
args[0] = context.String("index.ts")
args[1] = context.String(string(sourceCode))
args[2] = context.String("")
args[3] = context.Bool(true)

Next, obtain the function createSourceFile from the loaded ts object. This allows us to invoke the function directly from Go.

parseCode := ts.Get("createSourceFile")
defer parseCode.Free()

Load the typescript code that you would like to parse, and then simply use context.Call to execute the parser.

sourceCode, err := ioutil.ReadFile("/path/on/disk/typescript/code/index.ts")
if err != nil {
    panic(err)
}

result, err = context.Call(globals, parseCode, args)
check(err)
defer result.Free()

If there was no error, result contains the AST as an object. However, you will need to iterate over it to convert to a pure Go object or a strongly-typed object. It is left as an exercise for the reader.

if result.IsObject() {
    // print the property names available
    names, err := result.PropertyNames()
    check(err)

    fmt.Println("Object:")
    for _, name := range names {
        val := result.GetByAtom(name.Atom)
        defer val.Free()

        fmt.Printf("'%s': %s\n", name, val)
    }
} else {
    fmt.Println(result.String())
}

Complete code is available in this gist

This concludes the series on different ways to parse Typescript code in Java using J2V8, Go with v8go and [Go with QuickJS][post3].

Happy Hacking.


Read the full post here.

Parsing Typescript in Go using V8Go

In my earlier post we saw how we can parse Typescript into an Abstract Syntax Tree using Eclipse J2V8. In this post, we will explore the same in Go using v8go.

Using Go has advantages if you are building a tool as you can ship a single native binary without any depdendency. Though Java has the convenience of write once, run many but it still requires the presence of JVM on the user’s machine.

Back to the task at hand, the code requires the following steps:

  • Initialize and load V8
  • Load Typescript JS library
  • Load the Typescript code that you would like to parse
  • And, finally call the TS parser code to obtain the AST

Let’s get started. The first step is to initialize a new V8 context.

ctx := v8.NewContext()

Once V8 is up, we need to load the Typescript JS code. We make use of a locally saved typescript.js file for the same. Read it in memory and then use the RunScript method to load the script.

tsSource, err := ioutil.ReadFile("/path/to/ts/on/disk/typescript.js")
if err != nil {
    panic(err) // panic if load failed
}

// load typescript by converting []byte to string
ctx.RunScript(string(tsSource), "typescript.js")

As Typescript is now loaded, we need to build the compiler options to let TS know that we would like to use the latest syntax version for parsing

// read global object
obj := ctx.Global()
typescript, _ := obj.Get("ts")
ts, _ := typescript.AsObject()

// fmt.Println(typescript.IsObject())
moduleKindJs, _ := ts.Get("ScriptTarget")
moduleKind, _ := moduleKindJs.AsObject()

systemJs, _ := moduleKind.Get("Latest")
system := systemJs.String()

Next, obtain the function createSourceFile from the loaded ts object. This allows us to invoke the function directly from Go.

fnJs, _ := ts.Get("createSourceFile")
fn, _ := fnJs.AsFunction()

Load the typescript code that you would like to parse:

// read the source code file
jsFile, err := ioutil.ReadFile("/ts/source/code/on/disk/index.tsx")
if err != nil {
    panic(err)
}

We are now all set to invoke the parser. Though this requires setting up a new isolate and creating a few wrapper objects to be passed into the function obtained above.

isolate := ctx.Isolate()
ctx.RunScript("const compilerOptions = { module: "+system+"};", "source-tree.js")

sourceFileName, err := v8.NewValue(isolate, "index.ts")
sourceCode, err := v8.NewValue(isolate, string(jsFile))
compilerOptions, _ := ctx.RunScript("compilerOptions", "source-tree.js")
booleanTrue, err := v8.NewValue(isolate, true)

// invoke the parser function
fnValue, err := fn.Call(ctx.Global(), sourceFileName, sourceCode, compilerOptions, booleanTrue)

Check if there was an error while parsing, and if yes, you may want to obtain relevant error message as well as stack trace on the Javascript side.

if err != nil {
    e := err.(*v8.JSError)    // JavaScript errors will be returned as the JSError struct
    fmt.Println(e.Message)    // the message of the exception thrown
    fmt.Println(e.Location)   // the filename, line number and the column where the error occured
    fmt.Println(e.StackTrace) // the full stack trace of the error, if available

    fmt.Printf("javascript error: %v", e)        // will format the standard error message
    fmt.Printf("javascript stack trace: %+v", e) // will format the full error stack trace
    return
}

If there was no error, fnValue contains the AST as an object. However, you will need to iterate over it to convert to a pure Go object or a strongly-typed object. It is left as an exercise for the reader.

// following shall return true to indicate it is an object
fmt.Println(fnValue.IsObject()) // returns true

Complete code is available in this gist.

In my next post we will see how we can achieve the same using QuickJS and its wrapper for Go, QuickJS-Go.

Happy Hacking.


Read the full post here.

Parsing Typescript in Java

This post talks on how you can parse Typescript code in Java using Eclipse V8 wrapper. Why would one do that? I used it to prepare Javascript documentation for Bedrock, my React component library. I tried using both React Styleguidist and Storybook but haven’t liked both (will discuss those reasons in a later post).

Parsing means generating an Abstract Syntax Tree from the TS source code. Once you have the AST you can crawl it, to run any transform or aggregation as you like.

Let’s start by creating a new V8 instance that also understands the NodeJS runtime

NodeJS nodeJS = NodeJS.createNodeJS();

Next step is to load the Typescript parser in V8 using require. I am using the entire folder from a previously existing node_modules folder.

V8Object typescript = nodeJS.require(new File("path_to/node_modules/typescript"));

Now we need to obtain the Typescript.ScriptTarget.Latest value. This value allows us to instruct TS compiler to use latest TS syntax guidelines during the parsing phase.

V8Object moduleKind = typescript.getObject("ScriptTarget");
Integer system = moduleKind.getInteger("Latest");

Next, we need to setup compiler options. These shall be needed in the next step.

V8Object compilerOptions = new V8Object(nodeJS.getRuntime());
compilerOptions.add("module", system);

Before we invoke the parser, let’s load the TS source code in memory from the file on disk.

String code = org.apache.io.FileUtils.readFiletoString("my-ts-file.ts");

Finally time to invoke the TS compiler:

V8Object result = (V8Object) typescript.executeJSFunction("createSourceFile", fileName, code, compilerOptions, true);

Iterating over the V8Object is difficult, so we will use a utility method to convert it to normal java.util.Map

Map<String, ? super Object> astAsMap = V8ObjectUtils.toMap(result);

And that is all what we need. You may now use astAsMap to crawl/iterate over the AST as your use-case desire. But before, we wrap it up here, we need to clean up the resources that V8 allocated:

while (nodeJS.isRunning()) {
    nodeJS.handleMessage();
}

// release all resources
result.release();
compilerOptions.release();
moduleKind.release();
typescript.release();
nodeJS.release();

You can find all the code together in this Github repository including conversion to strongly typed Java objects.


Read the full post here.

Experiments with Hugo!

In continuation of my last post, revisiting this blog, I spent time over weekend experiment and convert my site to Hugo. And I was amazed at the very first run. Hugo is not just fast, it is super fast. While Jekyll takes up 3-4 seconds to start, Hugo was done in less than a second. To top it all, it automatically detects changes to the configuration file as well and rebuilds. And to add cherries on top of the cake, Hugo was emitting content in both HTML and JSON formats to be consumed.

I also love the way Hugo allows you to configure your site either using YAML, or TOML or JSON. This allows a lot of flexibility for people who may be more familiar and comfortable using one format than other. I loved the way that at the flip of a configuration flag, all content (HTML/JS/CSS) was mininfied instantly. I use MermaidJS a lot for my sequence diagrams, and loved that Hugo has support for the same too.

Hugo has some level of customization in the form of shortcodes. It has a decent amount of built-in functions that you may leverage. However, I was disappointed to see no support for date format customization. I was born to read dates in dd/MM/yyyy format and now reading mm/dd/yyyy or yyyy-mm-dd format just doesn’t feel natural. Adding functionality requires writing a Go plugin which again may not be for everyeone.

But what makes Hugo stand apart is this one word: SPEED. Speed in setting it up - just download the binary and you are ready to go. Whether you are serving locally to test, or publishing your site for production, completing everything in less than a second is what I will call GOD SPEED.

However, if I were to move all my work, then I will need to change the date format again to something Hugo can undertand. Wish there was a simple way to define that in the configuration.


Read the full post here.

Revisiting the blog

It has been many years I wrote something worthy. A lot has changed since then. In these years front-end development has become more advanced with technologies like ReactJS, Vue, Svelte etc. Static sites need no longer confined to generate-time data and basic text processing. They should be able to make use of web components to better the user experience.

Today, as I look at this space it feels out-dated, pale and buggy. The headers and left-hand pane are not truly responsive. The typography does not properly align. Colors need more work. But these are least of my concerns. As a developer, I still have no true control over the way I write (seldom) and it gets published. For example, why should all posts be in a single folder, or in sub-folders based on date/time, or based on tag names?

With Jekyll setting up the site/blog or adding a new section within the existing one is difficult. Posts can only be recognized and paginated from under the _posts folder. There is no way to filter the posts. The software required to generate locally (ruby, bundler) etc itself takes time to install. And then you run into version issues. It took me 30+ minutes today get Jekyll running again. I believe we developers should do better here.

As I go over the latest documentation (version 4.2.2), I can’t find an easy way:

  • to customize functionality using Javascript
  • no way to optimize/thumbnail images directly
  • pull HTTP data to merge into posts
  • creating automatic post excerpt
  • inline/donwload external images
  • support for Velocity templates (yes, I come from Java world)
  • customizing date format to be used
  • and more…

I am sure there would be 3rd party plugins to support some of the above. However, I think this is something that should be supported out of the box. Over the next couple of days, I will evaluate the latest in static site generators. Have heard a lot about Hugo, Gatsby and Next. Time to find a worthy replacement for Jekyll.


Read the full post here.

Javascript classes with `prototype`

BabelJS has made it quite easy to write stateful ReactJS components by helping transpile the class based components into function’s. Classes are still second class citizens in the Javascript world, as they are part of ECMA Script 6 which hasn’t yet gained wide adoption.

Though, this post is not about ReactJS but about classes in general. In this post let’s revisit how classes can be created in Javascript using functions. As a bonus we will also see how to create a singleton using a function.

// this function serves as the constructor
function Fruit(color) {
    this.color = color;
}

// let's add a weight parameter to the class
// and a pair of getter and setter
Fruit.prototype.setWeight = function(weight) {
    this.weight = weight;
}

Fruit.prototype.getWeight = function() {
    return this.weight;
}

This seems very simple as we first use a simple function as a constructor and then its prototype to add new methods to it. However, if you would like to use inheritance it becomes a little tricky syntax. Suppose, we want to create another class called Orange that inherits from Fruit. This Orange has a constructor that takes another attribute called variety along with color. Let’s see how this is accomplished.

// create another function that serves as a constructor
function Orange(color, variety) {
    // as in classes, call the super with color
    Fruit.call(this, color);

    // assign remaining attributes
    this.variety = variety;
}

So far, so good. However, we still need to set the prorotype chain to ensure that when an Orange is created, the methods from Fruit are inherited as well. For the same, we need to set the following on Orange:

Orange.prototype = new Fruit;
Orange.prototype.constructor = Orange;

And we are all set. Now if we create an Orange and call setWeight() method, it shall work flawlessly.

// create a new instance
const or = new Orange('reddish-orange', 'grapefruit');

// call any method from Fruit or Orange
or.setWeight(100); // works like a charm
or.getWeight(); // returns 100

Now, let’s look at how to create a singleton.

const Apple = new function() {
    this.type = "green apple";
    this.color = "red";
    
    this.printAsString = function() {
        return this.color + ' ' + this.type + ' apple';
    };
}

Instead of just declaring a normal function, we define and invoke an anonymous function using the new keyword. This way the constructor to the object is no longer available to other code, and hence, they cannot initialize the same.

Happy hacking!


Read the full post here.

Announcing AM library 1.0.0

I am happy to announce the launch of a new library called AM or Assert-Mocks for unit-testing Java servlet API code. The library aims to make it a lot easier and faster to test the servlet API code, including and not limited to testing of servlets, servlet filters and tag libraries. It helps remove the need of using Mockito framework for setting up expectations.


Read the full post here.

Releasing jerry-core 3.0.0

I am happy to announce that exactly after an year of the last release, I have a new major release for jerry-core library: version 3.0.0. You may get hold of the library from Maven Central with the following coordinates:

<dependency>
    <groupId>com.sangupta</groupId>
    <artifactId>jerry-core</artifactId>
    <version>3.0.0</version>
</dependency>

Read the full post here.

Fastest way to merge multiple integer sets

Problem

You are given multiple integer sets and you need to merge them into a single set in the fastest possible way.

Solution

The always updated article is always available on Github:sangupta/ps repo

Suppose we have 3 arrays of integer sets and we need to merge them. The fastest solution would be possible in time of O(n1 + n2 + n3) where n1, n2, n3 are the lengths of the three sets respectively. The solution lies in using a bit-vector (also called as bit-set or a bit-array) to represent elements using the index and then iterating over them.

  • Construct a bit-array
  • Iterate over the first array and for each integer set the corresponding bit to true
  • Repeat the above process for remaining arrays
  • Any duplicate element will result in setting true an already set bit
  • The resultant bit-array is the merge of all the arrays

Read the full post here.

Fastest sorting of integers

Problem

We are given a huge array of bounded, non-duplicate, positive integers that need to be sorted. What’s the fastest way to do it.

Solution

The always updated article is always available on Github:sangupta/ps repo

Most of the interview candidates that I have talked to about this problem come up with the quick answer as MergeSort or divide-and-conquer. The cost of sorting being O(N * Log(N)) - which in this case is not the fastest sorting time.

The fastest time to sort an integer array is O(N). Let me explain how.

  • Construct a boolean array of length N
  • For every integer n in array, mark the boolean at index n in array as true
  • Once the array iteration is complete, just iterate over the boolean array again to print all the indices that have the value set as true

Read the full post here.

Finding degrees of separation in a social graph

Problem

Assume two users on a Social network start with zero 0 connections. And add connections at a rate of 100 per minute. Explain how you would design a solution to find out the degrees of separation between two network profiles, given a known function getConnections(profile.id) that returns data from over the network. What differences would you make for realtime less consistent/optimal result vs a slower more accurate result?

Solution

The always updated article is always available on Github:sangupta/ps repo

I can think of many different ways to compute this. I will put them out below.

Approach 2 seems the best considering the storage cost and traversal costs. Approach 3 can be near real-time if we can take care of the storage, and add optimal number of workers for fan-out.


Read the full post here.

Introducing CodeFix

Am happy to release the very first version of a command-line development tool that I had been using for years for my own consumption: CodeFix - the tool helps perform some minor code refactoring tasks via a command line interface such as adding/updating copyright headers, removing trailing spaces in files, fixing file encoding, adding an empty line-ending to text files and more…

Some quick and dirty examples on what could be achieved are:

# add/update copyright
$ java -jar codefix.jar addcopy -r -f COPYRIGHT.txt -p *.java c:\code

# update line endings
$ java -jar codefix.jar ending -r -p *.txt c:\docs

# remove trailing white spaces
$ java -jar codefix.jar rtrim -r -p *.java c:\code

# change file encodings
$ java -jar codefix.jar encoding -r -p *.txt -s ISO-8969 -t UTF-8 c:\textdocs

You may download the binary or may take a dive into the source code.

Hope this helps.


Read the full post here.

Tabular data in a Java Console application

Displaying tabular data is a very common use-case, but working a console application and displaying the same becomes a tedious task. Why? First, you have to take care of formatting the entire data. Second, you need to make sure that the data does not spill-over the boundary of the cell. Third, it takes time and precision for such a code, and spending time on this boiler-plate code is total-waste.

Thus, I created ConsoleTable, a new helper class in Jerry-Core framework. This class is pretty useful to create such console outputs.

Features

  • Supports automatic sizing of columns in full-width layout
  • Supports multi-line layout where column text is broken at word boundaries to spill over multi-line
  • Support export to CSV, XML and JSON formats

Examples

For example, to create a layout like:

 | ------------ | --------- | --------------- | 
 | Stock Ticker | Company   | Any one product | 
 | ------------ | --------- | --------------- | 
 | APPL         | Apple     | iPhone          | 
 | GOOG         | Google    | GMail           | 
 | MSFT         | Microsoft | Windows         | 
 | ------------ | --------- | --------------- | 

you just need to code something like:

ConsoleTable table = new ConsoleTable();

table.addHeaderRow("Stock Ticker", "Company", "Any one product");

table.addRow("APPL", "Apple", "iPhone");
table.addRow("GOOG", "Google", "GMail");
table.addRow("MSFT", "Microsoft", "Windows");

table.write(System.out);

The code itself takes care of proper alignment and spacing of each element. This is not the end.

The ConsoleTable also supports multi-line output by breaking the sentence at word boundaries to make sure that the text fits in the cell.

For example:

ConsoleTable table = new ConsoleTable(ConsoleTableLayout.MULTI_LINE);
		
table.addHeaderRow("Stock Ticker", "Company", "Products");
table.addRow("APPL", "Apple", "iPhone, iPad, iPod, Mac, OSX, Mac Pro");
table.addRow("GOOG", "Google", "GMail, Blogger, AdSense, Analytics, Search");
table.addRow("MSFT", "Microsoft", "Windows, Office, Remote Desktop");

table.setColumnSize(2, 20);

table.write(System.out);

produces output as:

 | ------------ | --------- | -------------------- | 
 | Stock Ticker | Company   | Products             | 
 | ------------ | --------- | -------------------- | 
 | APPL         | Apple     | iPhone, iPad, iPod,  | 
 |              |           | Mac, OSX, Mac Pro    | 
 | GOOG         | Google    | GMail, Blogger,      | 
 |              |           | AdSense,             | 
 |              |           | Analytics, Search    | 
 | MSFT         | Microsoft | Windows, Office,     | 
 |              |           | Remote Desktop       | 
 | ------------ | --------- | -------------------- | 

The table also supports export to various formats:

Console table = getMyTable(); // some table data

// create a CSV
ConsoleTableWriter.writeCsv(table, System.out);

// create JSON output
ConsoleTableWriter.writeJson(table, System.out);

// create an XML
// wrap everthing inside a <data> ... </data> tag
// each row be wrappped inside a <row> ... </row> tag
ConsoleTableWriter.writeXml(table, System.out, "data", "row"); 

Hope this helps.


Read the full post here.

Various Bit-Array Implementation in Java

Bit-Arrays are much-useful and quite-fast data-structure that have a variety of uses. One of the most important ones in context of Big-Data is the use in Bloom filters. To store the bloom we need a very fast bit-array and the ones that can be persisted as well. Java has only an in-memory bit-array implementation. I needed a file-persisted one to be used in conjunction with the bloomfilter filter project. Thus, I added the following implementations to the jerry-core project.

  • FastBitArray - an implementation that is much faster than the standard Java implementation
  • FileBackedBitArray - backed by file persistence, and all operations are flushed back automatically
  • MMapFileBackedBitArray - one that is file-persisted, but uses memory-mapped files for nuch faster performance
  • JavaBitSetArray - one that uses internal Java implementation underneath

Usage is pretty simple as,

final int maxElements = 1000 * 1000; // 1 million
BitArray ba = new FileBackedBitArray(new File("my-bit-array.ba"), maxElements);

boolean updated = ba.setBit(13); // returns true
updated = ba.setBit(13); // returns false
ba.clearBit(13);
udpated = ba.setBit(13); // returns true

boolean isSet = ba.getBit(13); // returns true


// using the memory-mapped version is similar
ba = new MMapFileBackedBitArray(new File("my-bit-array"), maxElements);

// all other operations are the same

I have used MMapFileBackedBitArray in production for the last few years and has been quite useful and fast.

Hope this helps.


Read the full post here.

Iterating over Strings inside a String object

When reading file contents, or working with REST requests, many a times we want to read a String object line-by-line, that is, read lines within a single String object. Java does not offer a simple solution to the same - either you convert the String object to a byte[] and then use ByteArrayInputStream or use a StringReader and then push this into another line-by-line reader.

For the same, I wrote a simple utility class, StringLineIterator (available in jerry-core project) simplifying reading of lines to the following code snippet:

String contents = "..."; // some contents that contains new-lines, and form-feed characters

StringLineIterator iterator = new StringLineIterator(contents);
while(iterator.hasNext()) {
  String line = iterator.next();

  // do something with this extracted line
}

This helps us reading sub-string lines from contents and reduces boiler-plate code. Note that this implementation would use extra memory to the extent of each line, as it creates a new String object for each line that is read via the iterator.

Hope this helps.


Read the full post here.

Jetty + Spring 4 + Jersey 2 Integration

Today most of the enterprise systems are built over MicroServices. The advantages of the same are well-explained as 12factor principles. In Java, this translates to using Jetty as the embedded HTTP server, running Jersey or RestEasy or alike as the Jax-RS based REST framework.

Integration between Spring 3 and Jersey 2 is well documented and works great. With the coming of Spring 4, the integration still works if you are building a web application using Tomcat or JBoss or any other application server. However, for standalone Java applications this is broken.

Last night, I went poking my nose inside the jersey-spring3 module to dig the reason for the same. And finally found the reason, and a fix for the same.

Quick Fix

For the impatient, a very simple fix to this is to create a new WebApplicationContext, with the parent set to the ApplicationContext you created manually, and then set it in the Jettys ServletContext as:

ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
context.setContextPath("/");

AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext();
webContext.setParent(rootContext);
webContext.refresh();
webContext.start();

context.setAttribute(WebApplicationContext.class.getName() + ".ROOT", webContext);

This will ensure that all your dependencies get wired in your web-services.

For why it happens, continue reading.

Why is it broken?

The class org.glassfish.jersey.server.spring.SpringComponentProvider is responsible for detecting existence of Spring context and wiring the same withint the Jersey code so that all your dependencies can be @Autowired or @Injected. Let’s take a look at the initialize method of the class:

@Override
public void initialize(ServiceLocator locator) {
	this.locator = locator;

	if (LOGGER.isLoggable(Level.FINE)) {
		LOGGER.fine(LocalizationMessages.CTX_LOOKUP_STARTED());
	}

	ServletContext sc = locator.getService(ServletContext.class);

	if (sc != null) {
		// servlet container
		ctx = WebApplicationContextUtils.getWebApplicationContext(sc);
	} else {
		// non-servlet container
		ctx = createSpringContext();
	}
	if (ctx == null) {
		LOGGER.severe(LocalizationMessages.CTX_LOOKUP_FAILED());
		return;
	}

	// more code omitted for brevity
}

If you look above, if Jersey figures out that there is a ServletContext already present, which would be as you are running a Jetty server, it will then only read the ApplicationContext/ctx via the code line:

ctx = WebApplicationContextUtils.getWebApplicationContext(sc);

If it detects that no ServletContext is present, only then it creates a new ApplicationContext instance via the call to,

ctx = createSpringContext();

Now the call to WebApplicationContextUtils.getWebApplicationContext(sc) translates to the following code (some constant references have been modified to make the code more understandable):

public static WebApplicationContext getWebApplicationContext(ServletContext sc, String attrName) {
	Assert.notNull(sc, "ServletContext must not be null");
	Object attr = sc.getAttribute(WebApplicationContext.class.getName() + ".ROOT");
	if (attr == null) {
		return null;
	}
	if (attr instanceof RuntimeException) {
		throw (RuntimeException) attr;
	}
	if (attr instanceof Error) {
		throw (Error) attr;
	}
	if (attr instanceof Exception) {
		throw new IllegalStateException((Exception) attr);
	}
	if (!(attr instanceof WebApplicationContext)) {
		throw new IllegalStateException("Context attribute is not of type WebApplicationContext: " + attr);
	}
	return (WebApplicationContext) attr;
}

As there is not WebApplicationContext.class.getName() + ".ROOT" attribute present in the ServletContext - Jersey fails to wire the dependencies.

Now, let’s take a look at the createSpringContext() method (again, some constants have been inlined):

private ApplicationContext createSpringContext() {
  ApplicationHandler applicationHandler = locator.getService(ApplicationHandler.class);
  ApplicationContext springContext = (ApplicationContext) applicationHandler.getConfiguration().getProperty("contextConfig");
  if (springContext == null) {
    String contextConfigLocation = (String) applicationHandler.getConfiguration().getProperty("contextConfigLocation");
    springContext = createXmlSpringConfiguration(contextConfigLocation);
  }

  return springContext;
}

One another way to fix this, would be be to add an ApplicationHandler class that sets the contextConfig property in its configuration, but with annotation support and classpath scanning, I don’t see why someone would want to do that.

I would raise a pull-request for the same in Jersey code sometime soon.

Hope this helps.


Read the full post here.

JOpenSurf now available in Maven Central

Sometime back I happened to work with JOpenSurf project for some prototyping work. The project is also a dependency of the LIRE project, the popular Lucene based Image Retrieval library. The only drawback if the JOpenSurf project was its non-availability in Maven Central.

I took time and am pleased to announce that the library is now available in Maven Central. Feel free to include it in your code as:

<dependency>
    <groupId>com.sangupta</groupId>
    <artifactId>jopensurf</artifactId>
    <version>1.0.0</version>
</dependency>
  • JOpenSurf Home Page: https://code.google.com/p/jopensurf/
  • LIRE Home Page: https://code.google.com/p/lire/

Hope this helps.


Read the full post here.

Windows Shell and Wildcard Command-line argument resolution

Problem: Windows Shell parses any wildcard path arguments that you supply over the command line, before passing the arguments to the actual program that has been invoked.


Read the full post here.

Introducting Java based HTTP server

Introducing a new HTTP server that can be used by Java developers for simple development needs.
Read the full post here.

Building a REST Server using Jetty

Today, most of the enterprise applications are distributed. And this also calls that the various components communicate with each other either using a Message Queue or via REST services. I have seen people still building Java web applications that are eventually deployed in a container like Tomcat. This is actually over engineering.


Read the full post here.