Monday 28 January 2013

Get the website ranking using Alexa API in Java

Using DOM Parser and Alexa API
You have to send a normal HTTP request to the Alexa API, and by using DOM XML parser to get the Alexa ranking of any web site. Here I am referring to my own web site and the ranking is not so good :). Refer the below code snippet for your reference.

package com.sanjeetpandey;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
 
public class AlexaRanking {
 
	public static void main(String[] args) {
 
	AlexaSEO obj = new AlexaSEO();
	System.out.println("Ranking is ::: " + obj.getAlexaRanking("sanjeetpandey.com"));
 
	}
 
	public int getAlexaRanking(String domain) {
 
	int result = 0;
	String url = "http://data.alexa.com/data?cli=10&url=" + domain;
 
	try {
	URLConnection conn = new URL(url).openConnection();
	InputStream is = conn.getInputStream();
 
	DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
	Document doc = dBuilder.parse(is);
	Element element = doc.getDocumentElement();
	NodeList nodeList = element.getElementsByTagName("POPULARITY");
	if (nodeList.getLength() > 0) {
	Element elementAttribute = (Element) nodeList.item(0);
	String ranking = elementAttribute.getAttribute("TEXT")
		if(!"".equals(ranking)){
			result = Integer.valueOf(ranking);
		}
	}
 
	} catch (Exception e) {
		System.out.println(e.getMessage());
	}
 
	return result;
}
}

Output -
Ranking is ::: 123123

Construct File Path In Java

Examples to construct a file path in Java :

Identify the operating system and create the file separator manually. (Not recommend)
Let’s Java do all the job, i.e File.separator. (Best Practice)
File.separator is always recommended, because it will check your OS and display the correct file separator automatically, and also you can use this best practice to reduce the code. For example,

Windows – Return “\”
*nix – Return “/”.

Manual file separator example
Way to construct a file path manually, which is not recommended in programming world.

package com.sanjeetpandey;
 
import java.io.File;
import java.io.IOException;
 
public class FilePath 
{
    public static void main( String[] args )
    { 
     try {
 
       String filename = "test.txt";
       String finalPath = "";
       String workingDir = System.getProperty("user.dir");
 
       String osName = System.getProperty("os.name").toLowerCase();
       if(osName.indexOf("win") >= 0){
        finalfile = workingDir + "\\" + filename;
       }else if(osName.indexOf( "nix") >=0 || your_os.indexOf( "nux") >=0){
        finalfile = workingDir + "/" + filename;
       }else{
        finalfile = workingDir + "{others}" + filename;
       }
 
       System.out.println("Final filepath : " + finalPath);
       File file = new File(finalPath);
 
   if (file.createNewFile()){
      System.out.println("Done");
   }else{
      System.out.println("File already exists!");
   }
 
     } catch (IOException e) {
      e.printStackTrace();
 }
    }
}

File.separator example
A proper way is use the File.separator, see the different below, just one line code can do all the checking above.

package com.sanjeetpandey;
 
import java.io.File;
import java.io.IOException;
 
public class FilePath 
{
    public static void main( String[] args )
    { 
     try {
 
       String filename = "test.txt";
       String finalPath = "";
       String workingDir = System.getProperty("user.dir");
 
       finalPath = workingDir + File.separator + filename;
 
       System.out.println("Final filepath : " + finalPath);
       File file = new File(finalPath);
 
   if (file.createNewFile()){
      System.out.println("Done");
   }else{
      System.out.println("File already exists!");
   }
 
     } catch (IOException e) {
      e.printStackTrace();
 }
    }
}

Wednesday 1 August 2012

Convert XML File Into Properties File

Most of the Software developers may not aware of this function, actually, the java.util.Properties class come with a loadFromXML() method to load above XML file into a properties objec.
To convert properties file into XML file. See following XML file :

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
   <properties>
 <comment>Support Email</comment>
 <entry key="email.support">me@sanjeetpandey.com</entry>
   </properties>

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
 
public class PropertiesXMLExample
{
    public static void main(String[] args) throws IOException
    { 
     Properties props = new Properties();
 
     InputStream is = new FileInputStream("c:/email-configuration.xml");
     //load the xml file into properties format
     props.loadFromXML(is);
 
     String email = props.getProperty("email.support");
 
     System.out.println(email);
 
    }
}

Output:

me@sanjeetpandey.com

Convert Properties File Into XML File

Most of the Software developers may not aware of this function, actually, the java.util.Properties class come with a storeToXML() method to convert existing properties data into a XML file.

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
 
public class PropertiesXMLExample
{
    public static void main(String[] args) throws IOException
    { 
     Properties props = new Properties();
     props.setProperty("email.support", "me@sanjeetpandey.com");
 
     //where to store?
     OutputStream os = new FileOutputStream("c:/email-configuration.xml");
 
     //store the properties detail into a pre-defined XML file
     props.storeToXML(os, "Support Email","UTF-8");
 
     System.out.println("Done");
    }
}

The above example will write the properties detail into a XML file “c:/email-configuration.xml“.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
 <properties>
  <comment>Support Email</comment>
  <entry key="email.support">me@sanjeetpandey.com</entry>
 </properties>


Saturday 21 July 2012

Try-With-Resources In JDK 7

In Java, normally we open a file in a try block, and close the file in the finally block, see following :

try{
  //open file or resources
}catch(IOException){
  //handle exception
}finally{
  //close file or resources
}
In JDK 7, a new “try-with-resources” approach is introduced. When a try block is end, it will close or release your opened file automatically.
try(open file or resource here){
 //...
}
//after try block, file will close automatically.
In JDK 6:
package com.sanjeetpaney.io;
 
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
 
public class Example1 {
 
 public static void main(String[] args) {
 
  BufferedReader br = null;
 
  try {
 
   String line;
 
   br = new BufferedReader(new FileReader("C:\\testing.txt"));
 
   while ((line = br.readLine()) != null) {
    System.out.println(line);
   }
 
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    if (br != null)br.close();
   } catch (IOException ex) {
    ex.printStackTrace();
   }
  }
 
 }
}
In JDK 7:
package com.sanjeetpandey.io;
 
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
 
public class Example2 {
 
 public static void main(String[] args) {
 
  try (BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt")))
  {
 
   String line;
 
   while ((line = br.readLine()) != null) {
    System.out.println(line);
   }
 
  } catch (IOException e) {
   e.printStackTrace();
  } 
 
 }
}

Tuesday 17 July 2012

How to get free Disk Space in Java

In Java old days, it really difficult to determine the free disk space on a partition of local system. But now this is changed since JDK 1.6 released, a few new methods like getTotalSpace(), getUsableSpace() and getFreeSpace(), are bundled with java.io.File to retrieve the partition or disk space detail.

package com.sanjeetpandey.core;
 
import java.io.File;
 
public class DiskSpaceDetail
{
    public static void main(String[] args)
    { 
     File file = new File("c:");
     long totalSpace = file.getTotalSpace(); //total disk space in bytes.
     long usableSpace = file.getUsableSpace(); //allocated / free disk space in bytes.
     long freeSpace = file.getFreeSpace(); //unallocated / free disk space in bytes.
 
     System.out.println(" === Partition Detail ===");
 
     System.out.println(" === bytes ===");
     System.out.println("Total size : " + totalSpace + " bytes");
     System.out.println("Space free : " + usableSpace + " bytes");
     System.out.println("Space free : " + freeSpace + " bytes");
 
     System.out.println(" === mega bytes ===");
     System.out.println("Total size : " + totalSpace /1024 /1024 + " mb");
     System.out.println("Space free : " + usableSpace /1024 /1024 + " mb");
     System.out.println("Space free : " + freeSpace /1024 /1024 + " mb");
    }
}

Output:

=== Partition Detail ===
 === bytes ===
Total size : 107269320704 bytes
Space free : 50940715008 bytes
Space free : 50940715008 bytes
 === mega bytes ===
Total size : 102299 mb
Space free : 48580 mb
Space free : 48580 mb

How To Loop ArrayList In Java



Four ways to loop ArrayList in Java:
For loop
For loop (Advance)
While loop
Iterator loop

package com.sanjeetpandey.core;
 
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
public class ArrayListLoopingExample {
 public static void main(String[] args) {
 
  List<String> list = new ArrayList<String>();
  list.add("Text 1");
  list.add("Text 2");
  list.add("Text 3");
 
  System.out.println("#1 normal for loop");
  for (int i = 0; i < list.size(); i++) {
   System.out.println(list.get(i));
  }
 
  System.out.println("#2 advance for loop");
  for (String temp : list) {
   System.out.println(temp);
  }
 
  System.out.println("#3 while loop");
  int j = 0;
  while (list.size() > j) {
   System.out.println(list.get(j));
   j++;
  }
 
  System.out.println("#4 iterator");
  Iterator<String> iterator = list.iterator();
  while (iterator.hasNext()) {
   System.out.println(iterator.next());
  }
 }
}

Output:

#1 normal for loop
Text 1
Text 2
Text 3
#2 advance for loop
Text 1
Text 2
Text 3
#3 while loop
Text 1
Text 2
Text 3
#4 iterator
Text 1
Text 2
Text 3