Showing posts with label Useful Tools. Show all posts
Showing posts with label Useful Tools. Show all posts

Thursday, September 3, 2009

Screencast of my iPhone App

Thursday, June 11, 2009

A simple example with StringTemplate

I have always wanted to write this article but often find myself preoccupied with many other things. Please spend 20 minutes of your day to read this article. It is a food for thought in my opinion and the main audience are Java developers developing web applications using Eclipse together with Apache Tomcat.

I would like to introduce a very powerful and convenient tool to generate HTML pages using StringTemplate. This tutorial assumes that the readers are well versed with writing servlets, configuring web server and Java programming. The main intention and focus of this article is to expose ourselves to the power of this template engine using Apache Tomcat web server; not Jetty, not Resin, nor JBOSS. I hope you find this blog entry useful although I will not go in depth with the nitty gritty of the details.

A short history of StringTemplate: this tool is written by Terence Parr, my former Computer Science professor at University of San Francisco. It is a useful tool to generate HTML pages dynamically and enforces a distinct and clear separation between view and model in the MVC model.

Tools that I use: Eclipse 3.4.0, Apache Tomcat 6.0 and of course the two important jar files that you need to download from the StrngTemplate official website. They are antlr-2.7.7.jar and stringtemplate.jar. Unpack the compressed file and copy the two jar files into WebContent/WEB-INF/lib folder of your project in the Eclipse IDE.

DISCLAIMER: the codes shown below are adapted from Terence Parr's sample implementation at his website.

Now let us get into the meaty part of this article by introducing the servlet dispatcher. Imagine the job of a postman sending letters to different destinations. However in our context, my servlet dispatcher is actually dispatching the users' requests to the appropriate servlets. I will name this class FrontendServletDispatcher and a sample of implementation is as below:As you may notice in the implementation of FrontendServletDispatcher, there is a class called InvalidPage that subclasses Page. I wrote that class as a way to prevent users from going into illegal servlet paths. At least the users are informed that the path they are trying to go is not available. Details of other classes that subclass Page are followed after the demonstration of web.xml. This is a file you cannot ignore when you are developing web application with Tomcat Apache.After that, I create a folder called "templates" in the com.pages package. This is where all the st files are located. The next thing to focus is the Page class and the subclasses (LandingPage, LoginPage and InvalidPage). The code shown below demonstrates to you the implementation of the super class Page and the introduction of StringTemplate and StringTemplateGroup.Page class gets an instance of "templateLayout" from the folder "template". "templateLayout" serves as a skeletal or a building block of dynamic content in a web page. I include all four necessary st files for our reference in this discussion. The first st file is called "templateLayout.st", followed by "landingPage.st", "loginPage.st" and "invalidPage.st"Last but not least, here are the implementations of LandingPage, LoginPage and InvalidPage classes.For a start, you may try changing the string of the titles. You do not actually need to restart the server as the changes will take effect immediately, somewhat similar to what we know as hot-deploy. I hope you have fun trying this out and please feel free to drop any comments that further improves this article :)

Thursday, May 28, 2009

Translating XML with XSL in Java

I do not consider the codes in this blog entry as intensive as other entries. This is just merely an example to show you how to translate a XML document with a XSL stylesheet in a Java class. It could be a very handy tool for some Java developers out there that want to translate a given XML content into another completely different XML content on the fly.
Do not forget to set the encoding of your Java codes to UTF-8 if you are manipulating non-English XML content - for example, Traditional Chinese, Simplified Chinese, Russian, Korean or Japanese - if you would want to see the output in your Eclipse IDE, which is my current IDE to write Java codes.

The usefulness of this approach is that you do not need to include a reference of a XSL file in the XML, say for example,

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="myXMLstylesheet.xsl"?>
<catalog/>

Hope you have fun trying this out! :)

Sunday, May 24, 2009

Indexes of indexOf

Have you ever come across a situation in which you want to gather a list of indexes of the one particular substring in a string but you are limited to using only indexOf() method? I did and I wrote this method to ease my work in the future in the event that I need to get the list of indexes of the given substring. The code is as follow.

public static ArrayList indices(String inputString, String sampleString){
int length = inputString.length();
int inputStringIndex = -1;
StringBuffer newString = new StringBuffer();
int index = 0;
int check = 0;
ArrayList compile = new ArrayList();
while (index < length) {
try {
if (inputString.charAt(index) == sampleString.charAt(check)) {
newString.append(inputString.charAt(index));
check++;
if (newString.toString().equals(sampleString)) {
inputStringIndex = (index - check) + 1 ;
compile.add(inputStringIndex);
newString.setLength(0);
}
}
if (check == (sampleString.length())) {
check = 0;
}
} catch (Exception ex){}
index++;
}
if (compile.size() == 0) {
compile.add(inputStringIndex);
}
return compile;
}
The usage of this static method is very simple and trivial. Given a string "Nicholas Key Key Key Nicholas Key" and a sample substring "Key", you will get the result of [9, 13, 17, 30].

Thursday, May 21, 2009

Converting decimals into different base numbers

I have this function that might be useful and interesting for you. Probably some of us are thinking how to convert a decimal number into hexadecimal, octal and binary. To those readers that never heard of these four words, decimal is a base 10 number, hexadecimal is a base 16 number, octal is a base 8 number and binary is a base 2 number. I wrote this function simply because I wanted to learn what happens behind the API methods in the Java SDK that help you to convert a given decimal into the three different base numbers.

The methods that are available for us the developers in the Java 1.5 SDK are:
Integer.toBinaryString(input);
Integer.toOctalString(input);
Integer.toHexString(input);


public static class DecimalConverter{
static StringBuffer result = new StringBuffer();
static int divisorBIN = 2;
static int divisorOCT = 8;
static int divisorHEX = 16;
static char[] code = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};

public static String converterHelper(int number, int divisor) {
if (number == 0) {
return "";
}
else {
converterHelper(number/divisor, divisor);
result.append(code[number%divisor]);
}
return result.toString();
}

public static String toHex(int number) {
//reset StringBuffer result
result.setLength(0);
return converterHelper(number, divisorHEX);
}

public static String toOct(int number) {
//reset StringBuffer result
result.setLength(0);
return converterHelper(number, divisorOCT);
}

public static String toBin(int number){
//reset StringBuffer result
result.setLength(0);
return converterHelper(number, divisorBIN);
}
}
From the method as shown, we have 16 characters in the array "code". This is because we want to accommodate all the valid the characters in base 16 numbers (hexadecimals). This method is quite a recursive method to convert the base 10 numbers (decimals) into 3 different bases of numbers. I hope you find these method useful. :) We can make use of this method by calling these static methods in the DecimalConverter class. Static methods are especially easy and useful when we want to call or make use of them from other classes. This is how the method is demonstrated.

public static void main(String[] args) {
System.out.println(DecimalConverter.toOct(207));
System.out.println(DecimalConverter.toBin(207));
System.out.println(DecimalConverter.toHex(207));
}
The recursion takes place in this statement converterHelper(number/divisor, divisor);. converterHelper method calls itself as long as the number is not 0 and then it looks into the array and find the matching character according to the index from the modulo operation. You may try out this method and use the numbers in the conversion table to determine if this helper class is useful for you. Click here to view the conversion table.

Monday, May 11, 2009

CoffeeCup HTML Editor

This is a HTML Editor that you may want to give it a try. I love to use this application because, first of all, it is absolutely free. You can get it right here for free without any cost! Here is a screenshot of how their website looks like.

Most of the time, free stuffs are not actually free. Some companies will insist to get at least your email address in order to download their "free" software. For those of you that might be wondering why some companies tempt you to give them your email address or phone number, the reason being that your contact information will be harvested by spammers or so called business affiliates. Do not fall into that trap. Privacy is becoming more and more invaded these days. CoffeeCup does not ask for your email address nor telephone number. You will just need to download this HTML Editor from their website and the application is up and running. No strings attached!

I have tested this application and it is loaded with many interesting features including syntax highlighting. It also allows you to preview your HTML design in the same window. Since I have started to tinker with PHP at my playground, the editor is able to highlight the PHP statements nicely. The most important feature, for me personally, to use this application, is the FTP which is used to perform file uploads and downloads. No more paying a hefty sum of money to buy FrontPage or Dreamweaver - IDEs that helps you most of the frontend but leave you clueless about the underlying HTML codes.

Other than that, the interface is very intuitive. Everything that I wanted to do is within my estimation, which means that I know intuitively what buttons to point and click or which drop down menu to look at, the first time I was using this application. This is true when I configured the FTP settings.

But hey, since CoffeeCup HTML Editor is free, you should not expect that it is very feature-packed just like those off-the-shelf HTML editors. I have mentioned the pros earlier so here are some of the disadvantages. I have only came across one - CoffeeCup HTML Editor is only available for Windows and that is sad.

Anyway, this is the link again to download CoffeeCup HTML Editor. Have fun trying it!

DISCLAIMER: I am recommending CoffeeCup HTML Editor as a software developer that has tried its features and I think it is useful for other web developer and I do not receive any endorsement fee from CoffeeCup to write this article :)

Friday, May 8, 2009

The syntax highlighter

I believe some of my readers might be thinking to themselves how does Nicholas wraps around the codes that he demonstrates in his blog entries in a text area filled with interleaving colors. It also comes with the copying feature and viewing the codes in plain texts. Many thanks to Alex Gorbatchev for this wonderful Javascript library that allows us to read codes more easily in blogs or online journals. This is his website if you would want to take a look at his work. Or you can actually go to Google Code website to download the package. There are several steps for you to follow if you want to get your codes display nicely in the encapsulated and decorated text area.

[1] Go to the syntaxhighlighter website at Google Code to download the latest version of the Javascript library.


[2] Download the compressed file and unzip it in your remote hosting. I may suggest Google Apps to host the uncompressed files. You will have to use WinRAR to unzip the contents. I rename the folder called "dp.SyntaxHighlighter" to "SyntaxHighlighter". There are 2 folders that I make use in the uncompressed file namely "Styles" and "Scripts".

[3] Edit your blog template to insert these lines of codes, preferably at the footer part of the template that reads "<!-- end outer-wrapper --> ".

[4] The next step is to try inserting your code snippets into this textarea
<textarea name="code" class="javascript" cols="60" rows="10">
  code...
  code...
  code...
</textarea>

Hope you have fun trying this out! :)