Wednesday, 16 February 2011

Convert JUnit3 Tests modules to JUnit4

I needed to convert many test files to JUnit4, after a while, I considered that is a really painful task to do it manually. So I wrote a little program to automate the process.
I tested this application on a huge number of files wrote by various Persons and having various formats, therefore I hope that I works on every possible JUnit module.
Please send me a short comment if you found a case, that I didn't included in it.

you can call the application by entering this command on Command Line:


java -jar JUnit4Converter.jar -f <your JUnit3 Java file>

this will printout the converted file to Console, if you wanted to do an Inplace Conversion, add "-i" to commands.


java -jar JUnit4Converter.jar -i -f <your JUnit3 Java file>

You can access the application on Github

Monday, 14 February 2011

Read multiple files from Resource JAR or Disk

following to my further Post about loading one file from a JAR file or Disk, here is a method which loads directly multiple files. it will decide base of given URL, if it must load those files from Disk or a Resource JAR file.
In my sample, I wanted to be more detailed and load just XML files.



    /**
     * Loads multiple xml files from Disk or Resource JAR file.
     *
     * @param clazz current class
     * @param path package path of resources
     * @return the resource listing
     * @throws URISyntaxException the URI syntax exception
     * @throws IOException Signals that an I/O exception has occurred.
     */
    List<InputStream> loadMultipleResources(final Class<?> clazz, final String path) throws URISyntaxException, IOException {
        final List<InputStream> listOfFiles = new ArrayList<InputStream>();

        // it is a normal directory, so just find and list files with XML extension
        URL directoryUrl = clazz.getClassLoader().getResource(path);
        if (directoryUrl != null && directoryUrl.getProtocol().equals("file")) {
            final File[] files = new File(directoryUrl.toURI()).listFiles(
                    new FilenameFilter() {
                        @Override
                        public boolean accept(final File dir, final String name) {
                            return name.endsWith(".xml");
                        }
                    });

            for (final File f : files)
                listOfFiles.add(new FileInputStream(f));

            return listOfFiles;
        }

        if (directoryUrl == null) {
            final String packageName = clazz.getPackage().getName();
            directoryUrl = clazz.getResource(packageName);
        }

        // the given path is a JAR file, so extract all XML Files from classpath and return their content as stream
        if (directoryUrl.getProtocol().equals("jar")) {
            final String jarPath = directoryUrl.getPath().substring(5, directoryUrl.getPath().indexOf("!"));
            final JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
            final Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                final String name = entries.nextElement().getName();
                if (name.startsWith(path) && name.endsWith(".xml")) { // filter according to the path
                    String entry = name.substring(path.length());
                    final int checkSubdir = entry.indexOf("/");
                    if (checkSubdir >= 0) {
                        entry = entry.substring(0, checkSubdir);
                    }
                    final InputStream inputStream = clazz.getClassLoader().getResourceAsStream(name);
                    
                    listOfFiles.add(inputStream);
                }
            }

            return listOfFiles;
        }

        throw new UnsupportedOperationException("Cannot list files for URL " + directoryUrl);
    }


Wednesday, 12 January 2011

Printing the Objects which has no toString method using Reflection

once you want to use toString method in your classes, you will quickly see that all Object without defined toString method, will just showed by their memory address.
Although you can walk through your classes and add a proper toString method to each of them, you will be stopped once you use a thirdparty or generated object.
I will show you here how you can simply printout your object none less. this method uses Reflection to iterate through attributes of a class and prints out its value.
I found later, using ReflectionToStringBuilder is more comfortable to write my own.
so here is the solution:

first write a class which extends ToStringStyle to customize appearance of fields (e.g. use Tabs, how to printout Array and so on)



public class PrintObjectStyle extends ToStringStyle {
    private final static ToStringStyle instance = new PrintObjectStyle();

    public PrintObjectStyle() {
        setArrayContentDetail(true);
        setUseShortClassName(true);
        setUseClassName(true);
        setUseIdentityHashCode(false);
        setArrayStart("\n\t{");
        setArrayEnd("\n\t}");
        setArraySeparator("\n\t");
        setFieldSeparator(", " + SystemUtils.LINE_SEPARATOR + "  ");
    }

    public static ToStringStyle getInstance() {
        return instance;
    }

    ;

    @Override
    public void appendDetail(StringBuffer buffer, String fieldName, Object value) {
        if (!value.getClass().getName().startsWith("java")) {
            buffer.append(ReflectionToStringBuilder.toString(value, instance));
        }
        else {
            super.appendDetail(buffer, fieldName, value);
        }
    }

    @Override
    public void appendDetail(StringBuffer buffer, String fieldName, Collection value) {
        appendDetail(buffer, fieldName, value.toArray());
    }
}



now you can call this line everywhere that you want to printout an Object.



System.out.println(ReflectionToStringBuilder.toString(myObject, PrintObjectStyle.getInstance()));


Thursday, 6 January 2011

Desoldering a XBox 360 Capacitor

If you want to reflow your XBox360 using a Hotair Gun, you have to protect all capacitors, otherwise they will blow out and must be renewed:


I show you in this film how easy you can desolder them.

Wednesday, 29 December 2010

Parsing and Standardizing an Address using GeoGoogle API

Google provides an API to address standardization. It standardizes addresses by utilizing google's geocoding service.
GeoGoogle is a client API to google's geocoding service, if you are looking for a offline solution (which has no usage limit), take a look at http://jgeocoder.sourceforge.net

To use geocoding web service, you need sign-up for your own API key at http://www.google.com/apis/maps/signup.html

more information on http://geo-google.sourceforge.net/usage.html

here is a sample:


Friday, 24 December 2010

Read a Text File from Resource JAR or Disk (Override resources with a custom file)

this sample shows how to implement a read text file in Java, the Program will first try to load file from resource jar (classes in path) and if it could not find it, then load it from given path on disk.
this is very useful if you want to implement a solution to override a resource with a customized one.

here is the program:



public class LoadFile {

    public void doLoadFile(final String fileName) throws IOException {
        InputStream inputStream;


        //try to load file from disk
        try {
            inputStream = new FileInputStream(fileName);
        }
        catch (FileNotFoundException fe) {
            //failed, so try to load it from resources in class path
            inputStream = LoadFile.class.getClassLoader().getResourceAsStream(fileName);
            if (inputStream == null)
                throw new FileNotFoundException("could not find file: " + fileName);
        }

        // Get the object of InputStreamReader
        final InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        final BufferedReader bufferReader = new BufferedReader(inputStreamReader);

        String strLine;
        while ((strLine = bufferReader.readLine()) != null) {
            // Print the content on the console
            System.out.println(strLine);
        }

        // Close the input stream
        inputStreamReader.close();
    }
}


Wednesday, 15 December 2010

Very simple Form submitting using AJAX

I wrote this module very long time ago, but I find it very simple and useful for people that want to build ajax applications quickly in their application, so I decided to publish it.

this module will be used mainly to post the content of a form and receive the response from server. it recognizes the fields and parses the server response automatically.

all you need is to include the javascript code to your page:


<script language="javascript" src="js/ajaxClass.js"></script>


and call the function at the end of your page:


function submitForm() {
ajaxObject.submitForm('myForm', 'spanResponseContainer', 'ajax-loader.gif');
}

myForm: your Form's id or name
spanResponseContainer: an Span as container for server response
ajax-loader.gif: the path to an image to show while waiting for server response, see this post if you don't know, where to get such an image.

here is the whole sample:


<html>

<head>
    <title>.:: Simple Ajax Test ::.</title>
  <script language="javascript" src="js/ajaxClass.js"></script>
</head>


<body>

<form action="/myserver/sayHello.jsp" name="myForm" method="post" onsubmit="submitForm(); return false;">
        <table>
            <tr>
                <td>Enter your name:</td>
                <td align="left">
                    <input type="text" name="textName" size="20" value="" />
                </td>
            </tr>
        </table>
      
        <input type="submit" value="send">
</form>
<br />
<br />
<span id="spanResponseContainer"></span>

<script language="JavaScript">
function submitForm() {
ajaxObject.submitForm('myForm', 'spanResponseContainer', 'ajax-loader.gif');
}
</script>

</body>
</html>


you can download the script from here