Programming and writing about it.

echo $RANDOM

Category: Java

New Article: Getting Started with Clojure

Update: A PDF of the print article is now available.

I take a beginner’s look at Clojure, as the title suggests in this article which is published by Linux For You in the March, 2011 issue.

If you happen to be one of the readers of this article, I would love to hear from you!

I have been away from the Java landscape for a while, but looks like I am getting into it again, in multiple ways. Clojure, being just one of the beginnings. I kinda liked leiningenso super simple!

Random scribbles: E-reading

So, the world E-reads these days from devices which have e-ink. I wasn’t sure if I would really like reading on 6/7″ screens. To mitigate the possible waste of $, I took a relatively less risky option — go for the funny sounding Android tablet, Pendo Pad. I installed the Kindle app for Android, and I have been really enjoying e-reading. The Amazon Kindle might just be something to spend on!

Advertisement

JavaFX Launched: Start Doing More

All your cross-platform RIA needs are met here : http://www.javafx.com
JavaFX Launch: http://channelsun.sun.com/video/software/javafx/1915439297

OpenJDK 6, NetBeans 6.0.1 on Ubuntu 8.04

You can now use pre-built OpenJDK 6 for your Java development on Ubuntu 8.04.

See the links for more information:

Also, NetBeans 6.0.1 is now available in the repos (http://java.dzone.com/news/ubuntu-hardy-heron-804-reposit)

So, now you know what to do? Start using NetBeans 6.0.1 with OpenJDK 6!

Java client for del.icio.us using NetBeans

del.icio.us is a bookmarking service where you can save, share your favorite/useful URL’s.

It has a REST API: http://del.icio.us/help/api/. Using this API you can design clients (web/desktop) to use the service. NetBeans 6.1 comes bundled with the APIs for popular web-services, which includes del.icio.us.

In this post, I shall code a simple Java console client for del.icio.us to fetch your recent posts. (For details, please refer https://api.del.icio.us/v1/posts/get?‘ at http://del.icio.us/help/api/posts)

You may download the complete NetBeans 6.1 Beta project here

Needless to say, you will need a del.ico.us account to follow this post.

  • Create a new project


  • Insert a method ‘getPosts()’ in the ‘Main’ class generated:


  • /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */

    package deliciousclient;

    /**
    *
    * @author amit
    */
    public class Main {

    /**
    * @param args the command line arguments
    */
    public static void main(String[] args) {

    getPosts();
    }

    private static void getPosts() {

    }

    }

  • Expand the Web Services node and hence expand the ‘Del.icio.us’ node to finally descend to the ‘delicious.posts_get’ API call.

  • Once you are there, click on it and drag it onto the body of the ‘getPosts()’ method. You will be asked to configure the API parameters, which you can either set to your own values or leave the default values

  • The method will now look like this:

  • private static void getPosts() {

    try {
    String tag = "xml";
    String dt = null;
    String url = "";

    String result = DeliciousService.getDeliciousPostsGetResource(tag, dt, url);
    System.out.println("The SaasService returned: "+result);
    } catch (java.io.IOException ex) {
    //java.util.logging.Logger.getLogger(this.getClass().getName()).log(java.util.logging.Level.SEVERE, null, ex);
    ex.printStackTrace();
    }

    }
  • You will observe that some new classes have been added to your project. They are classes which take care of the REST API calls to the del.icio.us service

  • But before running your project and hence using the service, you will have to provide your del.icio.us account details in the ‘profile.properties’ file in the ‘org.netbeans.saas.delicious’ package. For eg.

  • username=amitkumarsaha
    password=password

  • Run the project, you should get back the the XML representation of the result.

Thus, we have seen how easy it is to design a del.icio.us client using NetBeans 6.1. Similarly the other APIs can also be explored!

API Documentation

  • You can view the API documentation by a ‘Right-Click’ on the service name,and you will be taken to the relevant API documentation (you will need to be online for this)

Happy NetBeaning!

ODF Toolkit for Java

I have decided to discontinue my dedicated blog on ODF Toolkit for Java, basically because I was finding it difficult to manage both.

From now on, all posts on ‘odf4j’ will be available here on this blog.

Some related links:

We also have a weekly meeting every Friday at 07:30 GMT on irc://freenode/#odftoolkit

Store data in a XML file using the DOM API in JAXP

Okay, if you are like me- a Java developer and think that XML is an easy solution to most of your light-weight, persistent data storage and retrieval needs, simply because of its structured nature, I shall briefly describe you how I use Java API for XML processing (JAXP)- DOM API to store and facilitate easy retrieval of data for my application.

Here it goes:

Say, I have some information which I want to store (from my application) as given in file mapping.xml

While coding up the Java class which will write the data into a XML file, the DOM approach is:

  1. Create the DOM representation of the data- this is the in-memory representation
  2. Write it to the XML file using classes from javax.xml.transform package which transforms the DOM representation into the persistent XML file

The code that I would use has two parts to it:

  1. First part deals with the scenario in which the XML file already exists
  2. Second part takes care of the scenario in which I am creating the XML file for the first time- this time the root element of the XML has to be created, which is the difference from the first part

The above logic can be easily implemented using:


String xmlFile = "mapping.xml";
File file = new File(xmlFile);
if (file.exists()) {
//then code for first part
}else
{
//code for second part
}

Here is the Java source code:


private void writeToXML(String arg1, String arg4, String arg7) throws IOException, SAXException, ParserConfigurationException {



String xmlFile = "mapping.xml";
File file = new File(xmlFile);
if (file.exists()) {



DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

// Create the builder and parse the file


Document doc = factory.newDocumentBuilder().parse(xmlFile);

org.w3c.dom.Element mddevice = doc.getDocumentElement();

org.w3c.dom.Element new_mddevice = doc.createElement("mddevice");


new_mddevice.setAttribute("name", arg1);

org.w3c.dom.Element blockdevice = doc.createElement("device");

blockdevice.setAttribute("name", arg4);

new_mddevice.appendChild(blockdevice);

org.w3c.dom.Element mountpoint = doc.createElement("mountpoint");
new_mddevice.appendChild(mountpoint);
mountpoint.setTextContent(arg7);

mddevice.appendChild(new_mddevice);

try {
TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer aTransformer = tranFactory.newTransformer();

Source src = new DOMSource(doc);
System.out.println("Starting the XML file creation");

Result dest = new StreamResult("mapping.xml");
aTransformer.transform(src, dest);


} catch (Exception e) {
System.out.println("Stream error" + e.getMessage());
}
} else {


try {


//Create instance of DocumentBuilderFactory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//Get the DocumentBuilder
DocumentBuilder docBuilder = factory.newDocumentBuilder();
//Create blank DOM Document
org.w3c.dom.Document doc = docBuilder.newDocument();


//create the root element
org.w3c.dom.Element root = doc.createElement("raidmap");

doc.appendChild(root);

org.w3c.dom.Element mddevice = doc.getDocumentElement();
org.w3c.dom.Element new_mddevice = doc.createElement("mddevice");


new_mddevice.setAttribute("name", arg1);

org.w3c.dom.Element blockdevice = doc.createElement("device");

blockdevice.setAttribute("name", arg4);

new_mddevice.appendChild(blockdevice);

org.w3c.dom.Element mountpoint = doc.createElement("mountpoint");
new_mddevice.appendChild(mountpoint);
mountpoint.setTextContent(arg7);





mddevice.appendChild(new_mddevice);
try {
TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer aTransformer = tranFactory.newTransformer();

Source src = new DOMSource(doc);
Result dest = new StreamResult("mapping.xml");
aTransformer.transform(src, dest);




} catch (Exception e) {
System.out.println("Stream error" + e.getMessage());
}

} catch (Exception e) {
System.err.println(e.toString());
}
}
}

Note: arg1, arg4, arg7 are the “data” that I will store in the XML file; please
change it to suit your needs

Related:

DOM Tree Scanner in NetBeans 6.1 Beta

Say, you have created (or otherwise) a DTD file (for eg. mapping.dtd).

Right-click on it and you will see a option “Generate DOM Tree Scanner” in the pop-up menu that appears. Click on it:

What you will have is a Java class which is all set to be used to scan through your XML file which conforms to your DTD. Its Magic!

In the Java class that is generated, you will see a method:



public void visitDocument() {
.
.
.
}

This will be your entry-point to the DOM scanner.

Just create another Java class:


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package softwareraidtool;


import java.io.IOException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

/**
*
* @author amit
*/
public class MappingScannerDemo {


public static void main(String args[]) throws IOException, SAXException{
try{

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// Create the builder and parse the file
Document doc = factory.newDocumentBuilder().parse("mapping.xml"); //the file you want to parse and which conforms to the DTD
MappingScanner demo = new MappingScanner(doc);

demo.visitDocument();
}catch(ParserConfigurationException pc){

}
}


}

You will have to modify the DOM scanner class to fit your needs. In its original form, it will just parse the XML file.

Here are the files:

HTH, have fun!

Quick tip: ‘copy’ task with Ant

Say, you need to copy a bunch of files from one location to another in your project structure after the JAR building is over. Add these lines to your ‘build.xml’ file: “


*copy todir="dist"#
*fileset dir="."#
*include name="*.sh"#
*/include#
*/fileset#
*/copy#
*/target#

Please replace ‘*’ with ”

If you know how to insert XML properly in blogger, please let me know!

Package Naming in Indiana

If you have played around a bit with the Image Packaging System (IPS) in Indiana, you will observe that all packages are prefixed with a ‘SUNW’. Why is that?

I fired my query to the pkg-discuss list and Shawn Walker quickly told me the reason why: “

Because Sun’s official previous policy on package naming was that
creators of packages used their company stock ticker to ensure package
names were easily identified and unique.

Now, it is because the existing packages in Indiana, etc. are imported
from Solaris Express builds that still use the old naming convention.

It will go away eventually.


You may follow the discussion here

knew that Sun’s stock ticker was ‘JAVA’, then why ‘SUNW’? Google took me to this blog post on Jonathan’s blog titled “JAVA is everywhere

Now, I am relieved that I know why.

Exploring the Ant build script in NetBeans

After importing my manually coded build.xml into NetBeans, I opened it to view it in the wonderful XML editor:


Looking towards the left bottom, i notice the XML view of the build script:


You may also run any of the Ant targets by a Right-click->Run Target:

Cool!