Skip to main content

Posts

Showing posts from 2009

Tips for Reading Source Code

Reading time is longer than the writing time and most programmers will lose focus along the way (some even fall asleep) especially if they are reading monstrous legacy code. There are several reasons why, in no particular order, 1. Procrastination Programmer: [Wandering mind… Facebook… Twitter…] “Oh man, I have a brilliant idea, I’m going to read more on that… I’ll set aside this crap first and try to come up something innovative.” 2. Impatient Programmer: “I hate this crap, ugly legacy code, it sucks! Can I just have the documents and rewrite everything from scratch?” Project Manager: “Unfortunately, the source code is the only document we have.” 3. Interruptions Team mate: “Hey! Can I have 5 seconds from you? I’m getting a NullPointerException, this is weird, I had everything initialized!” Programmer: “Are you sure? Hold on, let me check that, you might have some methods returning nul...

Installing Go in Ubuntu Jaunty

Processor: x86 Operating System: Ubuntu Linux 9.04 Jaunty Jackalope 1. CONFIGURE THE ENVIRONMENT Set the necessary variables in your .bashrc that is if you are using bash. Assuming you have a 386-descendant processor and you want to keep the installation clean in an external disk (/media/disk). # Google Go Programming Language Settings export GOROOT=/media/disk/go export GOARCH=386 export GOOS=linux export GOBIN=/media/disk/go/bin 2. INSTALL MERCURIAL. Easy. $ sudo easy_install mercurial Install process, Searching for mercurial Reading http://pypi.python.org/simple/mercurial/ Reading http://www.selenic.com/mercurial Best match: mercurial 1.3.1 Downloading http://mercurial.selenic.com/release/mercurial-1.3.1.tar.gz Processing mercurial-1.3.1.tar.gz Running mercurial-1.3.1/setup.py -q bdist_egg --dist-dir /tmp/easy_install-a3YaRd/mercurial-1.3.1/egg-dist-tmp-VyNqd2 zip_safe flag not set; analyzing archive contents... mercurial.lsprof: module references __file__ mercurial.temp...

The Go Programming Language

Good day! Try out [The Go Programming Language] . As quoted from its home page, Go is … … simple package main import "fmt" func main() { fmt.Printf("Hello, 世界\n") } … fast Go compilers produce fast code fast. Typical builds take a fraction of a second yet the resulting programs run nearly as quickly as comparable C or C++ code. … safe Go is type safe and memory safe. Go has pointers but no pointer arithmetic. For random access, use slices, which know their limits. … concurrent Go promotes writing systems and servers as sets of lightweight communicating processes, called goroutines, with strong support from the language. Run thousands of goroutines if you want—and say good-bye to stack overflows. … fun Go has fast builds, clean syntax, garbage collection, methods for any type, and run-time reflection. It feels like a dynamic language but has the speed and safety of a static language. It’s a joy to use. … open source Install Go! Click [h...

POSIX cksum algorithm in Java

Most Unix programs rely on cksum for checking duplicate files. If you happen to migrate programs doing that, you need to make sure that you’ll be using the same algorithm for the same functionality of course. Here is the [cksum algorithm] and here is the [cksum man] page. The class below is implementing the java.util.zip.Checksum interface for extensibility. /** * Compute the checksum of a data stream using the * POSIX cksum algorithm. */ public class Cksum implements Checksum { /** * The checksum value. */ private int value; /** * The length of the stream. */ private int length; /** * The cksum payload. */ private final int[] payload = { 0x00000000, 0x04C11DB7, 0x09823B6E, 0x0D4326D9, 0x130476DC, 0x17C56B6B, 0x1A864DB2, 0x1E475005, 0x2608EDB8, 0x22C9F00F, 0x2F8AD6D6, 0x2B4BCB61, 0x350C9B64, 0x31CD86D3, 0x3C8EA00A, 0x384FBDBD, 0x4C11DB70, 0x48D0C6C7, 0x4593E01E, 0x4152FD...

HTTP reader in Java

While there are numerous ways of accessing web services, here is a primitive way of doing it. This is a simple class for reading HTTP responses. You can take advantage of this, classic examples are, 1. Reading twitter feeds for executing commands in a target machine 2. Getting the latest articles in a particular website 3. Translating through Google Translate 4. Arithmetic operations through Google 5. Currency conversion through Google and more! Here is the class. /** * Hyper-Text Transfer Protocol Reader. * * @author joset */ public final class HttpReader { private Map<String, List<String>> responseHeader; private URL responseUrl; private String mimeType; private String charset; private Object content; private int responseCode = -1; /** * Constructor requiring the URL string. */ public HttpReader(final String urlString) throws MalformedURLException, IOException { // open a connection. fin...

Delete files and directories recursively in Java

This post will teach you how to delete files and directories in Java recursively. There is nothing special in this post but I’m sure this will be useful especially for those who are just starting out their programming career in Java. boolean deleteRecursively(final File file) { if (file.exists()) { final File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { deleteRecursively(files[i]); } else { files[i].delete(); } } } return (file.delete()); } This code was not tested. Please read the Java 6 File API documentation [here] for more information. "Confidence means non-paralysis, a willingness to act, and act decisively, to start new things and cut failing ventures off." - Tom Peters

Locking a file in Java

Locking a file in Java is platform dependent. Write once run anywhere? Thumbs down. Some platforms will not allow a file access without a lock while others will. This is very useful especially when writing your own database (I know some people will argue but this is still happening in corporations handling very sensitive data). It starts with a simple file access. try { final File file = new File("Tables.dat"); final FileChannel fileChannel = new RandomAccessFile(file, "rw").getChannel(); // this method will block until a lock is acquired final FileLock lock =fileChannel.lock(); // this method will not block, it will return null or throw an exception lock = fileChannel.tryLock(); // TODO: do something with the file // release the lock lock.release(); // cleanup / close file fileChannel.close(); } catch (Exception e) { // TODO: handle exception } Caution: You really need to verify how the target platform...

Earth planner - Architect Felino Palafox Jr. (Manila Bulletin)

Earth planner Architect Felino Palafox, Jr. October 17, 2009, 8:49am THE MMetroplan is to Felino Palafox Jr. as the ark is to Noah. Through the plan and the ark, respectively, both forewarned their people of destruction to come their way if they didn’t mend their ways. Unfortunately, both were not heeded - and we all know what happened thereafter. “It was not an act of God. The devastation caused by Typhoon Ondoy could have been averted if humans only listened,’’ firmly believes world-renowned Filipino architect Palafox. Palafox, of course, completely knows what he was talking about. More than 30 years ago, in 1977, he came out with the Metro Manila Transport, Land Use and Development Planning project, a World Bank-funded report that aimed to protect Metro Manila from further flooding. In this report, recommendations were made for transportation, land use, zoning, and flood control, particularly in the eastern part of the metropolis, specifically in – you guessed it – Marikin...

vrms - Virtual Richard M. Stallman

Though I am aware that there are non-free packages lurking in my box, I want to be precise, thanks to Virtual Richard M. Stallman . Non-free packages installed on linux-conqueror fglrx-modaliases Identifiers supported by the ATI graphics driver linux-generic Complete Generic Linux kernel linux-restricted-modules- Non-free Linux 2.6.28 modules helper script linux-restricted-modules- Restricted Linux modules for generic kernels nvidia-173-kernel-source NVIDIA binary kernel module source nvidia-173-modaliases Modaliases for the NVIDIA binary X.Org driver nvidia-180-modaliases Modaliases for the NVIDIA binary X.Org driver nvidia-71-modaliases Modaliases for the NVIDIA binary X.Org driver nvidia-96-modaliases Modaliases for the NVIDIA binary X.Org driver nvidia-glx-173 NVIDIA binary Xorg driver skype Skype - Take a deep breath tangerine-icon-theme Tangerine Icon theme virtualbox-3.0 Sun Virt...

Linus’ discussion about goto statements

As discussed by Linus Torvalds 6 years ago, From: Linus Torvalds Subject: Re: any chance of 2.6.0-test*? Date: Sun, 12 Jan 2003 12:22:26 -0800 (PST) On Sun, 12 Jan 2003, Rob Wilkens wrote: > > However, I have always been taught, and have always believed that > “goto”s are inherently evil. They are the creators of spaghetti code No, you’ve been brainwashed by CS people who thought that Niklaus Wirth actually knew what he was talking about. He didn’t. He doesn’t have a frigging clue. > (you start reading through the code to understand it (months or years > after its written), and suddenly you jump to somewhere totally > unrelated, and then jump somewhere else backwards, and it all gets ugly > quickly). This makes later debugging of code total hell. Any if-statement is a goto. As are all structured loops. And sometimes structure is good. When it’s good, you should use it. And sometimes structure is _bad_, and gets into the way, and usi...

What is going on?

Warning: Pure train of thought. My primary hard drive has crashed so I have to switch to Windows temporarily. There is nothing special happening lately except for the fact that I am enjoying life to the fullest. I can say that I am on the right track. I really thank God for that. Personal projects are keeping me busy these days. Next month I will be pursuing my MSCS degree. Hopefully this time, I am mature enough to handle school stuffs. Anyway here are stuffs for you to check, When Nature is Freakier than Sci-Fi Artificial Intelligence Blizzard Entertainment CitiSecOnline - Philippines Online Stockbroker

IBM Signed Numeric Table

If you are dealing with IBM mainframes, you will see signed numbers written this way. { = 0 } = -0 A = 1 J = -1 B = 2 K = -2 C = 3 L = -3 D = 4 M = -4 E = 5 N = -5 F = 6 O = -6 G = 7 P = -7 H = 8 Q = -8 I = 9 R = -9 Enjoy! “Stupidity is doing the same things repeatedly and expecting different results!”

Recovering from a checked exception in Java

If you are working on the back-end, this might be of use. Very trivial but rarely used. /** * This class demonstrates how to recover from checked exceptions * @author Joset */ public class CheckedExceptionRecovery { /** * @param args the command line arguments */ public static void main(String... args) { InputStreamReader inputStreamReader = new InputStreamReader(System.in); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); int input = 0; boolean done = false; do { try { System.out.println("Please enter an integer: "); input = Integer.parseInt(bufferedReader.readLine().trim()); done = true; } catch (NumberFormatException numberFormatException) { System.out.println("Invalid input. Please try again."); } catch (IOException ioException) { System.out.println("C...

Controller (MVC) Tips for Java Servlets / JSP

I was inspired by a face-to-face technical interview awhile ago that is why I am writing this down. To avoid having the Servlet’s doXXX() methods clogged, use reflection by breaking down your controller code into modules. Here’s how. You must have the following. 1. Reflection Interface (ServletHandler.java) - An interface for reflection. Nice definition! 2. Main Servlet (MainServlet.java) - A class extending HttpServlet. 3. Module Handler (CreditHandler.java) - A class containing the module’s controller code, for this example, the Credit Module. in file ServletHandler.java , import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public interface ServletHandler { public abstract void setServlet(HttpServlet servlet); public abstract void handle(HttpServletRequest request, HttpServletResponse response); } in file MainServlet.java , protected void doGet(HttpServletRequest r...

Method Piercing in Java

There’s nothing new here. I just want to reiterate though. class TargetClass { private static String DB_PASSWORD = "sw0rdfish"; private static String getDatabasePassword() { return DB_PASSWORD; } } And the attack? import java.lang.reflect.Method; public class ClassPiercing { public static void main(String... args) throws Exception { Class targetClass = Class.forName("TargetClass"); Method[] methods = targetClass.getDeclaredMethods(); methods[0].setAccessible(true); String databasePassword = (String)methods[0].invoke(null, null); System.out.println("Database Password: " + databasePassword); } } Output: Database Password: sw0rdfish Check out Val’s Blog by clicking [here] . He has more examples.

Sad reality about Wrapper Classes in Java

Consider the snippet. Integer firstInteger = 1000; // autoboxing Integer secondInteger = 1000; //autoboxing if (firstInteger != secondInteger) { System.out.println("Different objects!"); } if(firstInteger.equals(secondInteger)) { System.out.println("Meaningfully equivalent!"); } Output: Different objects! Meaningfully equivalent! How about this one. Integer firstInteger = 100; // autoboxing Integer secondInteger = 100; //autoboxing if (firstInteger == secondInteger) { System.out.println("Equal objects!"); } if(firstInteger.equals(secondInteger)) { System.out.println("Meaningfully equivalent!"); } And the output? Equal objects! Meaningfully equivalent! And the explanation? Two instances of the wrapper objects will always be == when their primitive values are the same. - Boolean - Byte - Character from \u0000 to \u007F (0 to 127) - Short from -128 to 127 - Integer from -128 to 127 Tsk.

MD5 Hashing in Java

This is useful for storing passwords in a database though still vulnerable to md5 dictionary attacks, anyway, here’s a static method. public static String hash(String text) { String hashedString = ""; try { MessageDigest md5Hash = MessageDigest.getInstance("MD5"); md5Hash.update(text.getBytes(), 0, text.length()); hashedString = new BigInteger(1, md5Hash.digest()).toString(16); } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } return hashedString; } This will return the MD5 hash. Have a great day!