Archive for category java

A Java String permutations utility

On a recent project I need to find all the possible permutations of a given URL. Stripping off subdomains, paths, and query parameters. Here is the first part of the solution. A method which takes a string and strips it down based on a given divider in a given direction at a given interval.

Here’s the code:

private static String[] getPermutations(String whole, String divider, int lim, int dir) {
	   String[] chunks = whole.split((divider.matches("\\.") ? "\\" : "")+divider);
	   System.out.println("chunks.length: "+chunks.length);
	   	   
	   if(chunks.length <= lim) {
		   System.out.println("return whole: "+whole);
		   return new String[]{whole};
	   }
	   
	   String[] permutations = new String[chunks.length-lim];
	   
	   if(dir == 1) {
		   	permutations[0] = whole;
   		    System.out.println("permutations[0]: "+permutations[0]);
			for(int i = 1; i < chunks.length-lim; i++) {
			   String permutation = "";
			   for(int o = i; o < chunks.length; o++) {
				   permutation += (o == i ? "" : divider) + chunks[o];
			   }
			   permutations[i] = permutation;
			   System.out.println("permutations["+i+"]: "+permutations[i]);
			}
	   } else if(dir == -1) {
		   for(int i = 0; i < chunks.length-lim; i++) {
			   String permutation = "";
	 		   for(int o = 0; o < chunks.length-i; o++) {
				   permutation += (o == 0 ? "" : divider) + chunks[o];
			   }
			   permutations[i] = permutation;
			   System.out.println("permutations["+i+"]: "+permutations[i]);
			}
	   }
	   
	   return permutations;
   }

Here is an example of it being used.

Input:

      getPermutations("com",".",1, 1);
      getPermutations("google.com",".",1, 1);
      getPermutations("a.b.c.d.e.cool.google.com",".",1, 1);
      getPermutations("/path/asdf/a/b/c/d/e/f","/",0, -1);
      getPermutations("a=b&c=d&e=f","&",0, -1);

Output:

$ javac Runme.java && java Runme
chunks.length: 1
return whole: com
chunks.length: 2
permutations[0]: google.com
chunks.length: 8
permutations[0]: a.b.c.d.e.cool.google.com
permutations[1]: b.c.d.e.cool.google.com
permutations[2]: c.d.e.cool.google.com
permutations[3]: d.e.cool.google.com
permutations[4]: e.cool.google.com
permutations[5]: cool.google.com
permutations[6]: google.com
chunks.length: 9
permutations[0]: /path/asdf/a/b/c/d/e/f
permutations[1]: /path/asdf/a/b/c/d/e
permutations[2]: /path/asdf/a/b/c/d
permutations[3]: /path/asdf/a/b/c
permutations[4]: /path/asdf/a/b
permutations[5]: /path/asdf/a
permutations[6]: /path/asdf
permutations[7]: /path
permutations[8]: 
chunks.length: 3
permutations[0]: a=b&c=d&e=f
permutations[1]: a=b&c=d
permutations[2]: a=b

Next I'll need to combine the URL components to get a list of valid URLs..

Share/Save

Tags: ,

Introducing jpoxy, the simple json-rpc implementation for Java

werx-jsonrpc has been renamed to jpoxy (hosted on Google Code). But the project name isn’t the only thing that’s changed. Based on some excellent feedback I’ve made the following changes:

  • The project is now thread-safe. I’ve removed request and response as global objects and, instead, made sure they get passed along the request chain.
  • This means the events for request and response have been taken out (which, I’ve been informed, I didn’t make a big enough deal about last time). The only event that you will get now is the init complete event which will provide your application a copy of the servlet configuration.
  • You can still access the request object (and, subsequently, the session object) by accepting a single HashMap parameter in your method.
  • A new annotation has been added, @Jpoxy(enabled = false), which allows you to tell the framework not to expose a method if it is public. This means you can mark all your internal event listener code so they aren’t exposed to the public.
  • You can now expose methods which accept a complex Java object. This means you can expose a method which accepts, say, a User object and the framework will use Jackson to marshal the parameters you provide into that object.

We also now have a Google group! So if you have any questions or comments we would love to hear from you.

Tags: , , , ,

Fred Brooks on the promise of object oriented programming

One view of object-oriented programming is that it is a discipline that enforces modularity and clean interfaces. A second view emphasizes encapsulation, the fact that one cannot see, much less design, the inner structure of the pieces. Another view emphasizes inheritance, with its concomitant hierarchical structure of classes, with virtual functions. Yet another view emphasizes strong abstract data-typing, with its assurance that a particular data-type will be manipulated only by operations proper to it.

Now any of these disciplines can be had without taking the whole Smalltalk or C++ package—many of them predated object-oriented technology. The attractiveness of object-oriented approach is that of a multivitamin pill: in one fell swoop (that is, programmer retraining), one gets them all. It is a very promising concept.

Why has object-oriented technique grown slowly? In the nine years since “NSB,” the expectancy has steadily grown. Why has growth been slow? Theories abound. James Coggins, author for four years of the column, “The Best of comp.lang.c++ ” in The C++ Report, offers this explanation:

The problem is that programmers in O-O have been experimenting in incestuous applications and aiming low in abstraction, instead of high. For example, they have been building classes such as linked-list or set instead of classes such as user-interface or radiation beam or finite-element model. Unfortunately the self-same strong type checking in C++ that helps programmers to avoid errors also makes it hard to build big things out of little ones.

He goes back to the basic software problem, and argues that one way to address unmet software needs is to increase the size of the intelligent workforce by enabling and coopting our clients. This argues for top-down design:

we design large-grained classes that address concepts our clients are already working with, they can understand and question the design as it grows, and they can cooperate in the design of test cases. My ophthalmology collaborators don’t care about stacks; they do care about Legendre polynomial shape descriptions of corneas. Small encapsulations yield small benefits.

David Parnas, whose paper was one of the origins of object-oriented concepts, sees the matter differently. He writes me:

The answer is simple. It is because [O-O] has been tied to a variety of complex languages. Instead of teaching people that O-O is a type of design, and giving them design principles, people have taught that O-O is the use of a particular tool. We can write good or bad programs with any tool. Unless we teach people how to design, the languages matter very little. The result is that people do bad designs with these languages and get very little value from them. If the value is small, it won’t catch on.

-Fred Brooks, The Mythical Man-Month, pg. 220

Tags: , ,

Simple JSON-RPC updated to 1.0.0

Simple JSON-RPC has been updated to 1.0.0. This new version includes a brand new event messaging system making it possible for classes to react to events generated by the Simple JSON-RPC framework.

Through simple event messaging, your RPC classes are now able to react to and even interact with servlet configuration, context, request, and response objects. To use this facility your class needs to extend the new JSONRPCEventListener interface and implement the messageReceived method, accepting one argument of the JSONRPCMessageEvent type.

Here is an example of how a class could implement a Simple JSON-RPC event listener:

public void messageReceived(JSONRPCMessageEvent me) {
	switch(me.message().getCode()) {
		case JSONRPCMessage.INIT:
			config = me.message().getServletConfig();
		break;
		case JSONRPCMessage.BEFOREREQUEST:
			request = me.message().getRequest();
			session = request.getSession(true);
		break;
		case JSONRPCMessage.BEFORERESPONSE:
			response = me.message().getHttpResponse();
			response.setContentType("text/html");
		break;
		case JSONRPCMessage.AFTERRESPONSE:
			lastresponse = me.message().getRPCResponse();
		break;
	}
}

This new feature should also make it easier to implement solutions that use sessions. This should also make it possible for classes to react to the output of other classes, including errors.

Tags: , , , ,

HBase JSON-RPC Bridge updated, allows scanning

The HBase JSON-RPC bridge has been updated to allow scanning on non-key columns. Now, passing a filter parameter creates a scanner using a RegexStringComparator. Results are returned in 100 block chunks until null is returned, in which case the ResultScanner is closed

Here is an example query that is now possible:

http://localhost:8080/hbasebridge/rpc?debug=true&data={"method":"lookup","params":{"table":"hbasetable","filter":"searchstring"}}

Tags: , , , ,

Bible Flashcards for Android 2.0

It’s been a while since I released Bible Flashcards version 1.0. Long enough in fact that I started getting emails asking whether I intended on updating past the 1.1.4 release.

Well I am proud to announce version 2.0 which includes a lot of requested features and a lot of bug-fixes and improvements. For this release I decided to take my time and re-factor the way various screens interacted, making them more modular and self-contained which should translate into fewer force closes. I also unleased the monkey on my app which helped me improve my code even more.

So without further ado here are the major features included in this release:

  • Ability to mark cards learned/unlearned
  • Ability to choose a random card
  • Cards now cycle so that if you are on card 1 and you attempt to go backwards, you are taken to the last card. Likewise if you are on the last card and you attempt to go forwards you are taken to the first card.
  • Menus also cycle so that if you hit the back button you will go from the active card view to the lesson chooser to the lesson set chooser and back to the card view.
  • Preferences to control settings such as card text size, whether to display learned cards, and a button to remove all learned cards from the internal database.

Some interface items had to be chopped to make room for these improvements. So if you are wondering where the next/back buttons are, they have been removed in favor of the more intuitive gesture controls. Swipe right for next card and left for previous card. Tapping the card flips it over.

I also want to give a special thanks to everyone who contacted me with words of encouragement and everyone who brought to my attention things that were broken and things that could be improved upon.

This release also includes a new lesson set, RossWords, which is being put together by  Samuel Rogers as he takes Hebrew this year. If anyone else is feeling generous  and would like to help out, feel free to contact me about a lesson set that you could help me improve upon or create as Samuel is doing.

Here are some screen shots from the new version:

And as usual, you can find Bible Flashcards in the Android Marketplace by searching for “Bible Flashcards” or by scanning the barcode below:

Tags: , , ,

Simple JSON-RPC updated to 0.9.7

Simple JSON-RPC has been updated to 0.9.7. This new version includes the ability to enable using full class names rather than simple method names. This makes using multiple classes with the same public method names possible.

To enable this functionality simply add an init-param to your web.xml file like:

<init-param>
	<param-name>use_full_classname</param-name>
	<param-value>true</param-value>
</init-param>

With this feature enabled, you then call methods via their full classname + method name separated by a dot (this nomenclature is for both static as well as non-static methods, the framework handles the particulars in the back-end).

Special thanks to Stephan of Cross Pollinate for suggesting this improvement!

Tags: , , ,

Bible Flashcards for Android 1.0

Bible Flashcards is an Android application based on the data files provided by the Crosswire Bible Society‘s Flashcard application. It contains flashcards for both Greek and Hebrew along with appropriate fonts for proper display.

I’ve also included an additional lesson set titled “greekBasics” which includes flashcards for the Greek alphabet.

Here are some screenshots:

You can find Bible Flashcards in the Android app Market by entering “Bible Flashcards” or by scanning the barcode below:

Additionally, if you are interested in helping out with new lessons or if you would like to provide feedback, please feel free to email me.

Tags: , , , , , , ,

Learning Languages: Java

The first thing you’ll need to consider is the development environment you want to use primarily. This is important as it will have an impact on how you run through tutorials and examples later on.

Environments can be broken down into two broad categories; command-line or a visual IDE. Both have their merits and you’ll eventually need to be familiar with both (especially if you expect to be releasing production code or participating in any well-maintained development environment).

The most common command-line environments are Maven and Ivy. Both come with a somewhat steep learning curve (which, unfortunately is unavoidable) but both are well worth investigating as they are both very common in production environments.

Starting out, however, you’ll most likely find that using a visual IDE will help you get right down to learning and compiling example code fairly quickly.

There are several common IDEs; IntelliJ, NetBeans, and Eclipse are all great ones that I’ve seen used in production. My favorite hands-down is Eclipse, especially since it also has configurations to help you develop in other languages such as PHP (Aptana) and C/C++.

For general basics and a broad overview of Java; I would recommend you take a look at the Java Beginner site.

There’s also several handy video tutorials (mostly using Eclipse) on YouTube such as this one:

Once you get the basics down, I’ve found that working on a full project helps. A great place to start would be to help our with an existing open-source project like JSword.

Tags: , , , ,

Javascript implementation of Java’s String.hashCode() method

Here is a direct replacement for Java’s String.hashCode() method implemented in Javascript.

I wrote this function to fulfill a requirement at work. Apparently, the back-end engineers thought hashCode() was a standard function. One of the hurdles for this project was not only figuring out how to translate the mathematical formula used in Java to generate hashCode()’s but also how to force Javascript to use 32bit integer math (no small feat).

Fortunately, I discovered that Java supports bitwise operators which are constrained to 32bit integer math.

So here’s the resulting String prototype in Javascript. With this prototype you can simply call .hashCode() on any string, ie. “some string”.hashCode(), and receive a numerical hash code (more specifically, a Java equivalent) such as 1395333309.

String.prototype.hashCode = function(){
	var hash = 0;
	if (this.length == 0) return hash;
	for (i = 0; i < this.length; i++) {
		char = this.charCodeAt(i);
		hash = ((hash<<5)-hash)+char;
		hash = hash & hash; // Convert to 32bit integer
	}
	return hash;
}

Tags: , ,