• Replacing sun.misc.Base64Encoder and sun.misc.Base64Decoder with alternatives from Apache Commons Codec API
    Mar 29, 2011

    Today I had to replace sun.misc.Base64Encoder and sun.misc.Base64Decoder implementations of base64 decoding and encoding, since these packages may not be available in every JRE.

    A bit of theory: Classes in JRE/JDK are in packages java., javax., org.* and sun.. All but the sun. packages are a standard part of the Java platform and will be supported into the future. Packages that are in sun.* can be different from OS to OS, and can change without notice. Thus the programs written using classes from these packages may not work in future releases of Java. Thus they should NOT be used by developers.

    There are also packages that start with com.sun.*. As explained in this blog entry from Sun about their built-in Httpserver:

    You are probably wondering already about the package names, and why they are com.sun.httpserver rather than something like java.net.httpserver. What this distinction means, is that the API and implementation are a fully supported, publicly accessible component of Sun's implementation of Java SE 6. It does mean however, that the packages are not formally part of the Java SE platform, and are therefore not guaranteed to be available on all other (non Sun) implementations of Java SE 6.

    Thus we must replace Sun's base64 implementation with the one from Apache Commons Codec library (or any other one of your choice), and here is how I did it.

    1. Getting Apache Commons Codec into Maven

      Open pom.xml file in Eclipse (with m2eclipse plugin installed), and switch to "Dependencies" tab.Click "Add..." button, and search for "codec". You can also optionally select "Include Javadoc" and "Include Sources" to have javadocs and sources for the package. I would recommend doing so, since you are highly likely to want to see the sources and/or javadocs for method documentations. Find commons-coded from results, and select version 1.4, that is commons-codec-1.4.jar. Click Ok, and you will have this package installed in your classpath.

    2. Replacing encoder

      Replace all BASE64Encoder instances with Base64. You can then call encode() method of that instance to replace encodeBuffer, or alternatively you can use static methods from Base64 class.

    3. Replacing decoder

      The steps are almost same as above, since Apache Commons Codec library uses the same class for both encoding and decoding. You just have to use decode() instead of encode() or decodeBase64() instead of encodeBase64().

    Done! Another thing you would want to pay attention to is character encoding. Converting to String from bytes, Apache Commons Codec by default uses UTF-8 encoding, so you may encounter problems if your setup's default charset is not UTF-8. Workaround would be using only byte accepting and returning methods from Base64 class for base64 calculations, and using new String(bytes[] bytes) constructor and String.getBytes() method for "setting" (better to say "constructing", since String is immutable) and getting bytes respectively.

    Happy coding!

    Resources

    http://java.sun.com/products/jdk/faq/faq-sun-packages.html - Explanation why developers should not use sun.* packages. http://blogs.sun.com/michaelmcm/entry/http_server_api_in_java - A blog entry from Sun about their built-in HttpServer

    Read more...
  • How to read folder structure from resource path in Maven.
    Mar 28, 2011

    Today I had to read a directory structure from a folder in recourses folder of my Maven project and do some operations with it.

    So my first try was

    File myFolder = new File(<i>MYFOLDERNAME</i>);
    

    Where MYFOLDERNAME was only the name of folder to read, without any path information. In this scenario I was getting a file that was in project's home directory, and not maven's customized resource directory as specified in Maven Standart Directory Layout.

    So I decided to play around with getResource method from class loader, and I type the following:

    File myFolder = new File(getClass().getResource(<i>MYFOLDERNAME</i>).getFile());
    

    Which to my surprise throw a null pointer exception, cause getClass().getResource(MYFOLDERNAME) was returning null. Playing with getURI also did not help, until I typed

    File myFolder = new File(getClass().getClassLoader().getResource(<i>MYFOLDERNAME</i>).getFile());
    

    which made everything to magically work. I don't know why this worked, since I unfortunately don't have a strong knowledge of Java internals, such as ClassLoaders, however my wild guess is that Maven has its own class loader, so that's why this occurs.

    Happy coding!

    Read more...
  • Netbook saga
    Mar 23, 2011

    Long time no posts, I know; At the end of last year I was fully immersed into doing my OCMJD assignment, and then I also had to make few major (or maybe not) decisions about my life. Long story short: I decided to stay in Germany long enough to get German citizenship, I ended up in a new job position, and I still have to find a new apartment in Frankfurt and move.

    In a meantime I had to learn German, and I decided to attend evening courses at Goethe Institut, which are so far pretty good, albeit the price. They also have a nice library (what they call Mediotek), and I was frequently studying there. However my 5-year old notebook was just not good enough to use in library, heavy, low-battery etc. So I decided to get myself a netbook. I did not want to invest much money into it, since I needed it mostly for browsing. At the end I was stuck between Lenovo S10-3 and Acer Aspire One D255, however Acer's secondary Android system's lack of Android Marketplace and Lenovo having DDR3 RAM instead of DDR2 of Acer made my choice to end up with Lenovo.

    So far I have only best feelings about Lenovo, very light, comfortable and can keep up enough battery. Windows 7 starter also performs well, its pretty quick, and even thought I was surprised that I cannot change wallpaper, it did not take me much time to get used to it. After some time I also realized that I am all the time at browser anyway, I am not looking too much to the wallpaper.

    After hardware issues are done, its time for software issue, and I want to talk about which software I did/would install to my new netbook. The main things to consider are that it has a small screen (so forget about IDEs), and also low processing power (so no video processing software).

    So far there are only two new programs that I installed - Google Chrome and Skype. There was some software pre-installed though, like Adobe Reader and McAfee antivirus, and later one made me free of antivirus software search. However I pretty instantly realized that nowadays its indeed easily possible to "live on the web". I edit my documents with Google Docs and use web-dictionaries like dict.leo.org or Google Translate, thus I don't need extra software for productivity. If I would not have McAffee, I would probably replace it with Microsoft Security Essentials - free alternative, and I am planning to replace Adobe Reader with Foxit Reader. I would also insall OpenOffice in case I would be staying offline a lot and needing to work with Office documents, and that is it. And for media playing I use built-in Windows Media Player. So my final list of netbook software is following:

    • Google Chrome - and I would take my time to configure it.
    • Microsoft Security Essentials - antivirus
    • OpenOffice - for office productivity
    • FoxitReader - for PDF files
    • Skype
    • 7-Zip - for archiving, if I ever need it.

    Not much, isn't it? I also found a bit bigger list here, pdf alternatives like Sumatra PDF and other possibly necessary software are mentioned there.

    I also found a really nice Windows 7 cleaning guide on the same website, I am sure I will have to follow those steps sometime.

    Read more...
  • Some thoughts about Object Oriented Programming
    Sep 14, 2010

    I am preparing for SCJD this week, thus I am going through Monkhouse book for SCJD preparation. Great book I have to say!

    Reading the book I stumbled up a piece of code written there which made me think a little bit about my OOP skills, since I realized that I would have probably solved that problem in a different way: the procedural programming way.

    The code had a pretty simple and straightforward task of retrieving the DVD object from the database file. The code is as follows:

    private DVD retrieveDvd(long locationInFile) throws IOException {
    
        log.entering("DvdFileAccess", "retrieveDvd", locationInFile);
    
        final byte[] input = new byte[DVD.RECORD_LENGTH];
    
        // Block other users for minimum time possible. Get exlusive access to
    
        // the file, read the entire set of bytes, then release exclusive lock.
    
    
        synchronized (database) {
            database.seek(locationInFile);
            database.readFully(input);
        }
    
        // now convert those bytes into a Dvd value object. Note that the thread
    
        // that is doing this conversion can be running while other threads are
    
        // doing other work - we are no longer blocking them.
    
    
        /**
         * class to assist in converting from the one big byte[] into multiple
         * String[] - one String per field. Refer to the book for more info.
         */
    
        class RecordFieldReader {
            /** field to track the position within the byte array */
            private int offset = 0;
    
            /**
             * converts the required number of bytes into a String.
             *
             * @param length the length to be converted from current offset.
             * @return the converted String
             * @throws UnsupportedEncodingException if "UTF-8" not known.
             */
    
            String read(int length) throws UnsupportedEncodingException {
                String str = new String(input, offset, length, "UTF-8");
                offset += length;
                return str.trim();
            }
        }
    
        RecordFieldReader readRecord = new RecordFieldReader();
        String upc = readRecord.read(DVD.UPC_LENGTH);
        String name = readRecord.read(DVD.NAME_LENGTH);
        String composer = readRecord.read(DVD.COMPOSER_LENGTH);
        String director = readRecord.read(DVD.DIRECTOR_LENGTH);
        String leadActor = readRecord.read(DVD.LEAD_ACTOR_LENGTH);
        String supportingActor = readRecord.read(DVD.SUPPORTING_ACTOR_LENGTH);
        String year = readRecord.read(DVD.YEAR_LENGTH);
    
        int copy = Integer.parseInt(readRecord.read(DVD.COPIES_LENGTH));
    
        DVD returnValue = ("DELETED".equals(upc))
                        ? null
                        : new DVD(upc, name, composer, director, leadActor,
                                  supportingActor, year, copy);
    
        log.exiting("DvdFileAccess", "retrieveDvd", returnValue);
    
        return returnValue;
    }

    The part made me think was that he made an inner class in order to assist reading strings from byte array, and thinking of myself, I would have never done it this way! I would have surely created a helper function that would take a byte array, offset and length and returned you the String. This solution first repelled me because I am not really a big fan of inner classes (being scared from big-big-big GUI codes that used inner classes), and it seemed a bit awkward to me that there was an inner class that accessed the local variable. However thinking a bit more, I thought that this code is indeed a cleaner way to solve this task. First of all passing around many variables to different functions was abated, thus creating a clearer and better performing code. I agree that there could be a slight performance trade-off because of defining a new class, but that I believe is paid off by having offset variable to be kept in one place and not accessed and passed around many time. In addition I am pretty sure modern JVMs figure out how to optimize this code and not create new class definitions each time.

    What to say, respect for the clean solution! This made me realize that I still try to solve things in procedural manner, which I need to get rid of being a hardcore Java programmer! I have to work on updating my OOP skills regardless of what I have learned so far, and try not to just skim over the OOP concepts, but try to use then in a working code creating clean and robust solutions. There will be plenty of time for me to do so anyway, I have the SCJD assignment right in front of me and few open source projects coming up!

    Helpful links:

    http://ootips.org/

    http://en.wikipedia.org/wiki/Object-oriented_programming - also contains part about object databases, something on my to-do list.

    http://en.wikipedia.org/wiki/Object_oriented_design

    http://download.oracle.com/javase/tutorial/java/concepts/index.html

    Read more...
  • How to change favicon in Blogger
    Jun 16, 2010

    The Blogger favicon is not bad, but to personalize my page I would like to have my own favicon. The way I did here worked for me in Firefox, but somehow Chrome still has Blogger favicon, even after cleaning cache and refreshing. My theme is also based on new template designer.

    1. Go to Design -> Edit HTML

    2. Find the end of head tag, you can simply search for </head>

    3. Put the following code right above the end of head tag:

    <link href='{image url}' rel='shortcut icon'/>
    <link href='{image url}' rel='icon'/>

    where {image url} is the URL of the favicon.

    Read more...
  • Using Picasa Web Albums to put your images on web and link them from your webpage
    Jun 16, 2010

    Create an album and upload pictures as usual. Then click on the picture to view it, and you will see "Link to this Photo" button on the right side of the page. Click on it and submenu with various linking options will appear. Tick on Image only (no link) checkbox, and then you can copy the link for your image under "Embed Image" field.

    Read more...
  • Launched HashPal.com
    Jun 5, 2010

    I have recently launched HashPal.com, an AJAX-based online service for calculating various cryptographic hashes. It is a simple JSP and servlet based website on Google Apps platform. In the beginning I was thinking about making it a GWT application, but search-engine unfriendliness of GWT applications cause me to abandon that idea. I also tried integrating GWT support into application, but ran into CSS clashes. Thus my next objective is to resolve them and add file checksum computation capability to the website.

    Read more...

subscribe via RSS