Digital Stronghold




November 5, 2009

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

October 29, 2009

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 handles files. This will not apply on a distributed database as well as networked file systems, if that’s the case you need to write at least a protocol for handling concurrency.

October 20, 2009

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 – Marikina, Cainta and Pasig.

The proposal, Palafox says, was to build developments in the city in the south, or northeast direction rather than west or eastward reclamations.

But instead of adopting the plan, the government at that time copied the wrong models, i.e. Los Angeles which was not even designed for pedestrians but for automobiles. On top of that, there were poor garbage disposal, and deforestation caused by illegal and legal logging to give way to the rise of subdivisions in all the wrong places.

Palafox says he came out not to fix the blame – and no, he is not running for any elective position.

“This crisis is an opportunity to learn lessons or unlearn the mistakes of the past and maybe revive those good proposals and bring them to the 21st century,” stresses Palafox who shared the same report with 32 other countries. Ironically, while most of these countries adopted the plan, the Philippines did not.

(more…)

October 18, 2009

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 VirtualBox
	
           Contrib packages installed on linux-conqueror
	
nvidia-common             Find obsolete NVIDIA drivers
nvidia-settings           Tool of configuring the NVIDIA graphics driver
	
  13 non-free packages, 0.9% of 1505 installed packages.
  2 contrib packages, 0.1% of 1505 installed packages.

Well, I need these.
- NVIDIA - Who wants to use the generic vesa driver (+ mesa) for playing games?
- Skype - I have relatives to keep in touch with.
- Virtual Box - I use Windows 7 to run web applications classified as For Microsoft Internet Explorer Only.

October 7, 2009

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 using a
“goto” is just much clearer.

(more…)

October 3, 2009

Cypress Semiconductor USB2.0 Storage Device

I’m just happy to have this device plugged in my PC.

UUID:               32efe183-7da8-4aea-8750-299d6584cc4a
VendorId:           0x04b4 (04B4)
ProductId:          0x6830 (6830)
Revision:           0.1 (0001)
Manufacturer:       Cypress Semiconductor
Product:            USB2.0 Storage Device
SerialNumber:       ############
Address:            sysfs:/sys/devices/pci0000:00/0000:00:02.2/usb1/1-8//device:/dev/bus/usb/001/004

September 10, 2009

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!”

August 26, 2009

The Linux Foundation Visa Platinum Rewards Card

With every purchase made you help the Linux Foundation. The funds raised will be used for technical events and travel grants for open source community members. Grab your Linux Foundation Visa Platinum Rewards Card now!

May 31, 2009

I turned 0x17

I just want to thank God for all the blessings. I want to remind everyone that we are not getting any younger. Have a great day ahead.

March 15, 2009

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("Cannot proceed.");
            }
        } while (!done);
	
        System.out.println("The integer is: " + input);
    }
}

February 26, 2009

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 request, HttpServletResponse response) throws ServletException, IOException {
...
    Class HandlerClass = null;
    ServletHandler handler = null;
	
    try {
        //assuming handlerClassName was defined beforehand as CreditHandler
        HandlerClass = Class.forName("com.eradicus.diamondbank.controller." + handlerClassName);
    } catch (ClassNotFoundException classNotFoundException) {
        //some logging facility here
    }
    if (HandlerClass != null) {
        try {
            handler = (ServletHandler) HandlerClass.newInstance();
        } catch (InstantiationException instantiationException) {
            //some logging facility here
        } catch (IllegalAccessException illegalAccessException) {
            //some logging facility here
        }
	
	if (handler != null) {
               //set executing servlet
		handler.setServlet(this);
               //switch control
		handler.handle(request, response);
	}
    }
...
}

in file CreditHandler.java,

public class CreditHandler implements ServletHandler {
    //use this if you need some attributes / methods from the executing servlet such as connection methods, application variables, etc.
    private MainServlet servlet;
	
    public void setServlet(HttpServlet servlet) {
        this.servlet = (MainServlet) servlet;
    }
	
    //this is where the control comes in after invoking handler.handle() above
    public void handle(HttpServletRequest request, HttpServletResponse response) {
        //some good code here
    }
}

There you go. I hope that helps. God bless.

February 13, 2009

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.

February 12, 2009

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.

January 27, 2009

MD5 Encryption 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 encrypt(String text) {
        String ecryptedText = "";
        try {
                MessageDigest md5Encrypt = MessageDigest.getInstance("MD5");
                md5Encrypt.update(text.getBytes(), 0, text.length());
                ecryptedText = new BigInteger(1, md5Encrypt.digest()).toString(16);
        }  catch (NoSuchAlgorithmException exception) {
                exception.printStackTrace();
        }
        return ecryptedText;
}

This will return the MD5-encrypted string. Have a great day!

January 1, 2009

Happy New Year!

Filed under: Progressive Studies

Welcome 2009!

Plurk with me, http://www.plurk.com/eradicus
See my multiply account, http://eradicus.multiply.com

Prospero año nuevo!

Theme designed by Joset Anthony Zamora


Digital Stronghold

↑ Get Headline Animator