Saturday 27 April 2013

JSON To XML Conversion



Hi friends,

I would like to share converting JOSN to XML format.

XML: 

  • XML (Extensible Markup Language) is a mark-up language that defines the set of rules for encoding document in Human &Machine readable format.
  • XML mainly emphasizes on Simplicity, Generality and Usability over the Internet. 
  • XML is a textual data format with strong support for all the languages of the World.
JSON:
  • JSON (JavaScript Object Notation) is a text-based open standard designed for Human-Readable data interchange.
  • Even JSON is javaScript specific, it is language-independent with parsers available for many languages.
  • JSON format is often used over network connection for serializing and transmitting structured data .

On keeping Pros and Cons of them a-part, this is the scenario which is very often needed for developing Applications (Mainly in Web environment).


Pre-Requisites:
I used net.sf.json-lib for JSON support. You can download from here.
Json-lib should contain the below dependencies in classpath:
  • commons-lang
  • commons-beanutils
  • commons-collections
  • commons-logging
  • ezmorph

Below is code for Converting JSON to XML format:

package testapp;
import java.io.InputStream;
import java.net.URL;
import net.sf.json.JSON;
import net.sf.json.xml.XMLSerializer;
import org.apache.commons.io.IOUtils;
/**
 * @author naveen.k
 */
public class JsonToXMLConverter {
    private URL url = null;
    private InputStream inputStream = null;    
    public void getJsonfromXml() {
        try{
            url = JsonToXMLConverter.class.getClassLoader().getResource("sample.txt");
            inputStream = url.openStream();
            String jsonData = IOUtils.toString(inputStream);
            XMLSerializer serializer = new XMLSerializer();
            JSON json = JSONSerializer.toJSON(jsonData);
            String xml = serializer.write(json);
            System.out.println(xml);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
     try {
                if (inputStream != null) {
                    inputStream.close();
                }
                url = null;
            } catch (IOException ex) {}
        }
    }
    public static void main(String[] args) {
        new JsonToXMLConverter().getJsonfromXml();
    }
}



Place the sample JSON in the specified path

sample.txt
==========

[
{
"@id":"bk01",
"author":"Gambardella, Matthew",
"title":"XML Developer's Guide",
"genre":"Computer",
"price":"44.95",
"publish_date":"2000-10-01",
"description":"An in-depth look at creating applications \n with XML."
},
{
"@id":"bk02",
"author":"Ralls, Kim",
"title":"Midnight Rain",
"genre":"Fantasy",
"price":"5.95",
"publish_date":"2000-12-16",
"description":"A former architect battles corporate zombies, \n an evil sorceress, and her own childhood to become queen \n of the world."
}
]
 


Output XML:
===========

   
  
  
  Gambardella, Matthew 
  An in-depth look at creating applications with XML. 
  Computer 
  44.95 
  2000-10-01 
  XML Developer's Guide 
  
  
  Ralls, Kim 
  A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world. 
  Fantasy 
  5.95 
  2000-12-16 
  Midnight Rain 
  
  


For XML to JSON conversion please refer this

XML To JSON Conversion



Hi friends,

I would like to share converting XML into JSON format.

XML: 

  • XML (Extensible Markup Language) is a mark-up language that defines the set of rules for encoding document in Human &Machine readable format.
  • XML mainly emphasizes on Simplicity, Generality and Usability over the Internet. 
  • XML is a textual data format with strong support for all the languages of the World.
JSON:
  • JSON (JavaScript Object Notation) is a text-based open standard designed for Human-Readable data interchange.
  • Even JSON is javaScript specific, it is language-independent with parsers available for many languages.
  • JSON format is often used over network connection for serializing and transmitting structured data .

On keeping Pros and Cons of them a-part, this is the scenario which is very often needed for developing Applications (Mainly in Web environment).


Pre-Requisites:
I used net.sf.json-lib for JSON support. You can download from here.
Json-lib should contain the below dependencies in classpath:
  • commons-lang
  • commons-beanutils
  • commons-collections
  • commons-logging
  • ezmorph

Below is code for Converting XML to JSON format:


package testapp;
import java.io.InputStream;
import java.net.URL;
import net.sf.json.JSON;
import net.sf.json.xml.XMLSerializer;
import org.apache.commons.io.IOUtils;
/**
 * @author naveen.k
 */
public class XMLtoJsonConverter {
    private URL url = null;
    private InputStream inputStream = null;    
    public void getXMLfromJson() {
        try{
            url = XMLtoJsonConverter.class.getClassLoader().getResource("sample.xml");
            inputStream = url.openStream();
            String xml = IOUtils.toString(inputStream);
            JSON objJson = new XMLSerializer().read(xml);
            System.out.println("JSON data : " + objJson);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
     try {
                if (inputStream != null) {
                    inputStream.close();
                }
                url = null;
            } catch (IOException ex) {}
        }
    }
    public static void main(String[] args) {
        new XMLtoJsonConverter().getXMLfromJson();
    }
}


Place the sample xml in the specified path

sample.xml
==========



   
      Gambardella, Matthew
      XML Developer's Guide
      Computer
      44.95
      2000-10-01
      An in-depth look at creating applications 
      with XML.
   
   
      Ralls, Kim
      Midnight Rain
      Fantasy
      5.95
      2000-12-16
      A former architect battles corporate zombies, 
      an evil sorceress, and her own childhood to become queen 
      of the world.
   

 


Output for the above specified xml is given below

OUTPUT:
=========

xml to json: [{"@id":"bk01","author":"Gambardella, Matthew","title":"XML Developer's Guide","genre":"Computer","price":"44.95","publish_date":"2000-10-01","description":"An in-depth look at creating applications \n      with XML."},{"@id":"bk02","author":"Ralls, Kim","title":"Midnight Rain","genre":"Fantasy","price":"5.95","publish_date":"2000-12-16","description":"A former architect battles corporate zombies, \n      an evil sorceress, and her own childhood to become queen \n      of the world."}]
 


Formated JSON data as  per the Output is given below

JSON DATA:
===========
[
{
"@id":"bk01",
"author":"Gambardella, Matthew",
"title":"XML Developer's Guide",
"genre":"Computer",
"price":"44.95",
"publish_date":"2000-10-01",
"description":"An in-depth look at creating applications \n with XML."
},
{
"@id":"bk02",
"author":"Ralls, Kim",
"title":"Midnight Rain",
"genre":"Fantasy",
"price":"5.95",
"publish_date":"2000-12-16",
"description":"A former architect battles corporate zombies, \n an evil sorceress, and her own childhood to become queen \n of the world."
}
]
For JSON To XML Conversion Check here

Monday 22 April 2013

Compare Dates In Java


This is one of the way for comparing Dates in Java using Date.compareTo() method.

Date.compareTo():
If return value is 0 - argument Date is equal to this Date
If return value is less than 0 (-ve) - this Date is before the Date argument
If return value is greater than 0 (+ve) - this Date is after the Date argument





Following is the example:

package testapp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * @author naveen.k
 */
public class CompareDates {
    public static void main(String[] args) {
        try{
            // Take SimpleDateFormat for choosing the format you need
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            // Parse the dates accordingly
        Date objDate1 = sdf.parse("2013-01-23");
        Date objDate2 = sdf.parse("2013-04-23");

            // Its nothing doing with comparing the dates....
            // It is provided only to show the Date in string format
        String firstDate = sdf.format(objDate1);
        String secondDate = sdf.format(objDate2);

            /*
             * the value 0 if the argument Date is equal to this Date;
             * a value less than 0 if this Date is before the Date argument;
             * and a value greater than 0 if this Date is after the Date argument.
             */
        if(objDate1.compareTo(objDate2)>0)
        System.out.println(firstDate + " is after to " + secondDate);
        else if(objDate1.compareTo(objDate2)<0)
        System.out.println(firstDate + " is before to " + secondDate);
        else
        System.out.println("Both Dates are equal");        

    }catch(ParseException ex){
    ex.printStackTrace();
    }
    }
}

Monday 15 April 2013

URL, URI and URN


The specifications of URI and URL are defined by World Wide Web Consortium.

The World Wide Web Consortium (W3C) is the main international standards organization for the World Wide Web (abbreviated WWW or W3).
Founded by Tim Berners-Lee at MIT and currently headed by him.

Tim Berners-Lee is one of the greatest Computer Scientists. He created the world’s first web page http://info.cern.ch/.

URI:

In computing, a uniform resource identifier (URI) provides a simple and extensible means for identifying a resource.
Best described at RFC 3986

Syntax as per RFC 3986 is:

The generic URI syntax consists of a hierarchical sequence of components referred to as the scheme, authority, path, query, and fragment.

      URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]

      hier-part   = "//" authority path-abempty
                  / path-absolute
                  / path-rootless
                  / path-empty

The following is an example URI and their component parts:

         foo://example.com:8042/over/there?name=ferret#nose
         \_/   \______________/\_________/ \_________/ \__/
          |           |            |            |        |
       scheme     authority       path        query   fragment


URL:
A uniform resource locator, abbreviated URL is the subset of URI.
In addition to identification of resource, URL provides the means of locating the resource.
That is, basically physical addresses of objects which are retrievable using protocols already deployed on the net.
Example:
http://en.example.org/navn/url


URN:
Uniform Resource Names (URNs) are the subset of URI.
URNs are intended to serve as persistent, location-independent, resource identifiers.

Syntax as per RFC 2141 is:

<URN> ::= "urn:" <NID> ":" <NSS>

where <NID> is the Namespace Identifier, and <NSS> is the Namespace Specific String.  The leading "urn:" sequence is case-insensitive.

Example:
urn:ietf:rfc:2141
The IETF's RFC 2141.


Summary:

A URI is super set of URL and URN.
URL identifies a resource using one of the URI schemes.
URN identifies a resource independent of its location.

Wednesday 10 April 2013

Running Another Application Independently from Java Application


Hi Friends,

I would like to share you some notes regarding ProcessBuilder, which helps in execution of seperate Java application.

We can run the Java application not only from console or bat/sh file, but even from another Java application also.

We can make use of Runtime class and ProcessBuilder classes for running the java application.

Now i would like to share you the process of executing java application individually from another java application using ProcessBuilder class.

Below is the snippet for Running java application as independent process.

package test;
import java.io.File;
import java.io.IOException;
/**
 * @author naveen.k
 */
public class ProcessBuilderDemo {

    public int runProcess(){
        try {
            String javaHome = System.getProperty("java.home");
            String javaBin = javaHome +
                    File.separator + "bin" +
                    File.separator + "java";
            ProcessBuilder probuilder = new ProcessBuilder(javaBin, "-cp", "d:\\", "TestProcess", "Naveen", "Naresh");
            Process process = probuilder.start();
            System.out.println("Process started successfully");
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

    public static void main(String[] args) {
            new ProcessBuilderDemo().runProcess();
    }
}

With the above execution of code, you can observe a new Java.exe task in Task Manager, with executes independently.

Below is the given TestProcess.java file which is provide as argument for above ProcessBuilder constructor:


import java.io.FileOutputStream;
import java.io.PrintWriter;
/**
 * @author naveen.k
 */
class TestProcess {

    public static void main(String[] args) {
        try {
            int i = 0;
            for (i = 0; i < args.length; i++) {
                System.out.println("Hello " + args[i] + "!");
            }
            FileOutputStream fos = new FileOutputStream("D:\\Test\\output.txt");
            PrintWriter bos = new PrintWriter(fos);
            int count = 0;
            while (count++ <= 100) {
                bos.write(" ******* " + count + " ******* ");
                bos.write("\n");
                for (i = 0; i < args.length; i++) {
                    bos.write("Hello " + args[i] + "!");
                    bos.write("\n");
                }
            }
            bos.flush();
            fos.flush();
            bos.close();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


After executing the ProcessBuilderDemo class, even if you closes/terminates the ProcessBuilderDemo class, the TestProcess execution will be continued.

Let's assume, we are calling the TestProcess class from the Web-application. Even, if we shut-down the server also the TestProcess execution will be continued.

For more details regarding ProcessBuilder you can check this space.

Monday 8 April 2013

Inserting Text at cursor position in Textarea


We can insert simple text in Text area at cursor position using javascript

Below is the snippet.

var myTextArea = document.getElementById("mymessage");
var textInArea = myTextArea.value;
var textToInsert = '$Simple Text$';
var caretPosition = myTextArea.selectionStart;
myTextArea.value = textInArea.substring(0, caretPosition)
    + textToInsert  + textInArea.substring(caretPosition);


'selectionStart' property provides the cursor position in Textarea.

Simillarly getting cursor position in JQuery

$('#mymessage').prop("selectionStart")


Try Example:

Saturday 6 April 2013

Compress Files into Zip Format


The java.util.zip package provides direct functionality to access zip files.

Below are the steps to follow for compressing files into zip file

1. create FileOutputStream
2. create ZipOutputStream using FileOutputStream
3. create a ZipEntry
4. add ZipEntry (individual files or directories) to ZipOutputStream
5. create a FileInputStream
6. write inputstream into zipoutputsteam (i.e. zipentry)
7. close inputstream
8. close zipentry
9. For multiple files continue from step 3
10. close outputstreams


The code for compressing the files into Zip file is provided below:

package testapp;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author naveen.k
 */
public class ZipUtilityTest {

    public static void main(String[] args) {
        compressToZipFile();
    }

    public static void compressToZipFile(){
        int len = 0;
        byte[] buffer = new byte[1024];
        FileOutputStream fos = null;
        ZipOutputStream zos = null;
        FileInputStream fis = null;
        try{
            fos = new FileOutputStream("D:\\Test\\TestZip.zip");    // Not a good standard of providing name like this...
            zos = new ZipOutputStream(fos);

            ZipEntry entry1 = new ZipEntry("test1.log");
            zos.putNextEntry(entry1);

            fis = new FileInputStream("D:\\Test\\TestZipContent\\Message1.log");
            while((len = fis.read(buffer)) > 0){
                zos.write(buffer, 0, len);
            }
            fis.close();
            zos.closeEntry();

            ZipEntry entry2 = new ZipEntry("test2.log");
            zos.putNextEntry(entry2);

            fis = new FileInputStream("D:\\Test\\TestZipContent\\Message2.log");
            while((len = fis.read(buffer)) > 0){
                zos.write(buffer, 0, len);
            }
            fis.close();
            zos.closeEntry();

            zos.flush();
            zos.close();
            System.out.println("Done");
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                if(fos != null)fos.close();
                if(zos != null)zos.close();
                if(fis != null)fis.close();
            }catch(Exception e){
            }
        }
    }
}

SomeNotes Regarding Favicon


How to find favicon for any website?

We can find favicon.ico for any website in any of the following ways:

Method 1:

Finding favicon.ico at the root of the desired domain.

Enter the URL in below format:
www.domain.com/favicon.ico

Example:
www.google.com/favicon.ico

www.twitter.com/favicon.ico

www.facebook.com/favicon.ico





Method 2:

By looking for <link> tag in the head part of the website source

a. search for <link> tag having rel="icon" attribute
<link rel="icon" href="/favicon.png" />

b. search for <link> tag having rel="shortcut icon" attribute
<link rel="shortcut icon" href="/favicon.ico" />


The Method 2 will provide the favicon with higher image quality.




Monday 1 April 2013

CSS MENU

Menu in CSS

Vertical menu Using CSS
HTML Code :

 <ul class="navigation">
          <li>
<a href="#">Home</a>
</li>
         <li>
<a href="#">Blogger For Java</a>
</li>
         <li>
<a href="#">About</a>
         </li>
  </ul>

CSS :

.navigation{margin: 0; padding: 0;}

.navigation {
background: #fff;
overflow: hidden;
width: 500px;
box-shadow: 0 2px 10px 2px rgba(0, 0, 0, 0.2);
}

.navigation li {
width: 136px; border-left: 5px solid #666;
float: left;
cursor: pointer;
list-style-type: none;

padding: 10px 10px 10px 15px;

-webkit-transition: all 0.5s ease-in;
-moz-transition: all 0.5s ease-in;
-o-transition: all 0.5s ease-in;
}

.navigation li a {
font-family: georgia;
font-weight: normal;
font-style: italic;
font-size: 14px;
margin-bottom: 5px;
line-height: 16px;
text-decoration: none;
}

.navigation li:hover {
background: #333;
border-left: 5px solid #000;
}

.navigation li:hover a {
font-weight: bold;
color: #fff;
}

see the DEMO here

OUTPUT :