Tuesday, September 15, 2009

call servlet from java, call the URL using java stand alone program

1. MyJsp.jsp

<html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Insert title here</title></head><body>THIS IS BINOD JSP PAGE<%
System.out.println("THIS IS OUTPUT FROM JSP PAGE");
%></body></html>

2. Stand alone Java Code
callURL.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class CallURL {
public static void main(String[] args) {
callURL();
}
public static void callURL(){
String urlName = "http://localhost:8080/TestServlet/MyJsp.jsp";
URL url;
try {
url = new URL(urlName);
URLConnection conn = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println("Output from Server :: "+line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}
}

Output from Client
Output from Server :: <html>Output from Server :: <head>Output from Server :: <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">Output from Server :: <title>Insert title here</title>Output from Server :: </head>Output from Server :: <body>Output from Server :: THIS IS BINOD JSP PAGEOutput from Server :: Output from Server :: </body>Output from Server :: </html>

Output from Server Console:
21:46:11,453 INFO [STDOUT] THIS IS OUTPUT FROM JSP PAGE

Friday, September 11, 2009

Overriding the equals and hashCode methods

Override the equals method when you want to specify the rules of logical equality of objects.
If these methods are not override then :
Person p1 = new Person("Binod",26);
Person p2 = new Person("Binod",26);
p1.equals(p2) -> Will return FALSE. But logically both object are same. Because equals method in Object class only check the references of object NOT containts.

So make the logical equals, Use override equals methods in Person class.

public boolean equals(Object obj) {
if(this == obj) {
return true;
}
if (!(obj instanceof Person)) {
return false;
}
Person person = (Person)obj;
return age == person.getAge() && name.equals(person.getName());

}
After adding this method in Person class then
Person p1 = new Person("Binod",26);
Person p2 = new Person("Binod",26);
p1.equals(p2) -> Will return TRUE.

Why override hashcode() method.
When use the hash based collection in your code then only equals method will not work. For example. Now as above code p1 and p2 are logically equal objects. So,

Set set = new HashSet();
set.add(p1);
set.add(p2);
System.out.println("Size of Set :: "+set.size()); Output would be 2, but it should be 1, as both objects are logically same and Set keeps unique data. So, we have to override the hashCode() method.
In Person class, add one more method.


public int hashCode() {
int hashCode = 0;
final int multiplier = 23;
if (hashCode == 0) {
int code = 133;
code = multiplier * code + age;
code = multiplier * code + name.hashCode();
hashCode = code;
}
return hashCode;
}

after compilation check
Set set = new HashSet();
set.add(p1);
set.add(p2);
System.out.println("Size of Set :: "+set.size()); Output would be 1.

During add the p1 object into Set, it will call hashCode() method of p1, now adding p2 object then again it will call hashCode() method of p2. If both hashcode values are equals then it will call object equals() method to final check, if it return true then set will not add second p2 object. If equals() method does not override then it will add second p2 object. If hashcode values are not equal then set would not be call equals() method.

Tuesday, September 8, 2009

Java Data Structure, Java LinkList

public class Node {
protected Object obj;
protected Node node;
}


public class SingleLinkList {
Node linkList;
int count;
public SingleLinkList() {
linkList = null;
count = 0;
}
public void insert(Object obj){
if(linkList == null){
linkList = new Node();
linkList.obj = obj;
linkList.node = null;
}else{
Node temp = new Node();
temp.obj = obj;
temp.node = null;
Node last = getLastNode();
last.node = temp;
}
}
public void insertFirst(Object obj){
if(linkList == null){
linkList = new Node();
linkList.obj = obj;
linkList.node = null;
}
else{
Node temp = new Node();
temp.obj = obj;
temp.node = linkList;
linkList = temp;
}
}
public void removeFirst(){
if(linkList == null){
System.out.println("Link List does not exist");
}else if(linkList.node == null){
System.out.println("Deleting data :: "+linkList.obj.toString());
linkList = null;
}
else{
System.out.println("Deleting from First :: "+linkList.obj.toString());
linkList = linkList.node;
}
}
public void remove(Object obj){
if(linkList == null){
System.out.println("Link List does not exist");
}else if(linkList.node == null){
if(linkList.obj == obj){
System.out.println("Deleting data :: "+linkList.obj.toString());
linkList = null;
}else{
System.out.println("NOT FOUND");
}
}
else{
Node temp = new Node();
temp = linkList;
Node pre = temp;
while(temp.node!= null&&temp.obj!=obj){
pre = temp;
temp = temp.node;
}
if(temp.obj==obj){
System.out.println("Deleting data :: "+temp.obj.toString());
if(pre==temp){
linkList=temp.node;
}
else{
pre.node = temp.node;
}
}
else{
System.out.println("NOT FOUND");
}
}
}
public void remove(){
if(linkList == null){
System.out.println("Link List does not exist");
}else if(linkList.node == null){
System.out.println("Deleting data :: "+linkList.obj.toString());
linkList = null;
}
else{
// Get node before last node
Node temp = new Node();
temp = linkList;
while(temp.node.node!=null){
temp = temp.node;
}
System.out.println("Deleting data :: "+temp.node.obj.toString());
temp.node = null;
}
}
public Node getLastNode(){
Node temp = new Node();
temp = linkList;
while(temp.node!=null){
temp = temp.node;
}
return temp;
}
public void show(){
Node temp = new Node();
temp = linkList;
while(temp!=null){
System.out.println("Data :: "+temp.obj.toString());
temp = temp.node;
}
}
public static void main(String[] args) {
SingleLinkList singleLinkList = new SingleLinkList();
String str="Binod";
singleLinkList.insert(str);
String str1="MCA";
singleLinkList.insert(str1);
str1="SATYAM";
singleLinkList.insert(str1);
str1="Bangalore";
singleLinkList.insert(str1);
str1="India";
singleLinkList.insertFirst(str1);
str1="SATYAM2";
singleLinkList.insert(str1);
str1="USA";
singleLinkList.insertFirst(str1);
singleLinkList.show();
// singleLinkList.remove();
/*singleLinkList.remove();
singleLinkList.remove();*/
// singleLinkList.removeFirst();
// singleLinkList.show();
singleLinkList.remove("SATYAM2");
singleLinkList.show();
}
}

Java Structure, Java Doule LinkList

public class DoubleNode {
DoubleNode pre;
Object obj;
DoubleNode post;
}


public class DoubleLinkList {
DoubleNode linkList;
public DoubleLinkList(){
linkList = null;
}
public void insert(Object obj){
DoubleNode temp = new DoubleNode();
temp.pre = null;
temp.obj = obj;
temp.post = null;
if(linkList == null){
linkList = temp;
}
else{
DoubleNode curr = new DoubleNode();
curr = linkList;
while(curr.post!=null){
curr=curr.post;
}
temp.pre = curr;
curr.post=temp;
}
}
public void insertFirst(Object obj){
DoubleNode temp = new DoubleNode();
temp.pre = null;
temp.obj = obj;
temp.post = null;
if(linkList == null){
linkList = temp;
}
else{
temp.post = linkList;
linkList = temp;
}
}
public void remove(){
if(linkList == null){
System.out.println("Link List does not exist");
}else{
DoubleNode curr = new DoubleNode();
curr = linkList;
while(curr.post!=null){
curr = curr.post;
}
System.out.println("Deleting Element :: "+curr.obj.toString());
if(curr == linkList){linkList = null;}
else{curr.pre.post = null;}
}
}
public void show(){
DoubleNode curr = new DoubleNode();
curr = linkList;
while(curr!=null){
System.out.println("Data :: "+curr.obj.toString());
curr = curr.post;
}
}
public static void main(String[] args) {
DoubleLinkList doubleLinkList = new DoubleLinkList();
doubleLinkList.insert("Binod");
doubleLinkList.insert("Suman");
doubleLinkList.insert("IGNOU");
doubleLinkList.insertFirst("India");
doubleLinkList.insert("SATYAM");
doubleLinkList.show();
doubleLinkList.remove();
doubleLinkList.remove();
doubleLinkList.show();
}
}

Tuesday, June 16, 2009

JMS easy example in RAD, Get started with JMS on RAD

This tutorial is based on RAD (Rational Architect Development) that uses the WebShpere Application Server V6.0.

1. start the server and go to admin console
2. Service Integration -> Buses -> New -> Give Name: BinodBus -> Apply -> save -> save
3. click on BinodBus -> In Additional Properties Section, click on Bus Member -> Next -> Finsh -> Save -> save
4. Again click on BinodBus -> In Additional Properties Section, click on Destination -> check Queue Type present or not. If
not present then click on New -> Choose Queue -> Next -> put Identifier QueueDestination -> Next -> Finish -> Save -> Save

5. Open Resources Tree from left panel
6. click on JMS Providers -> Default Messaging -> JMS Connection Factory -> New -> Name -> BinodConnectionProvider -> JNDI
Name -> jms/BinodConnectionProvider -> Bus Name -> BinodBus -> click on Apply -> Save -> Save

7. click on JMS Providers -> Default Messaging -> Go to Right side Destination -> JMS Queue -> New -> Name -> BinodQueue ->
JNDI -> jms/BinodQueue -> Bus Name -> BinodBus -> QueueName -> QueueDestination -> OK -> Save -> Save

8. Restart the server.
9. Create one Dynamic Web Project (JMSSECOND)and Write two servlet to check the simple example

10. Write first servlet (ProducerServlet.java)

import java.io.IOException;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ProducerServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("******** THIS IS MESSAGE PRODUCER SERVLET **********");
check();
}

public void check(){
System.out.println("********* Producer check **********");
String destName = "jms/BinodQueue";
final int NUM_MSGS = 5;
Context jndiContext = null;

try { jndiContext = new InitialContext(); }
catch (NamingException e) { System.out.println("Could not create JNDI API context: " + e.toString()); System.exit(1);
}

ConnectionFactory connectionFactory = null;
Destination dest = null;

try {
connectionFactory = (ConnectionFactory) jndiContext.lookup("jms/BinodConnectionProvider");
dest = (Destination) jndiContext.lookup(destName); }
catch (Exception e) { System.out.println("JNDI API lookup failed: " + e.toString()); e.printStackTrace(); System.exit(1);
}

Connection connection = null;
MessageProducer producer = null;
try {
connection = connectionFactory.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); producer = session.createProducer(dest);
TextMessage message = session.createTextMessage();

for (int i = 0; i < NUM_MSGS; i++) {
message.setText("This is message from JMSSECOND DEMO " + (i + 1));
System.out.println("Sending message: " + message.getText());
producer.send(message);
}

producer.send(session.createMessage());
} catch (JMSException e) { System.out.println("Exception occurred: " + e.toString()); }
finally { if (connection != null) { try { connection.close(); }
catch (JMSException e) { }
}
}
}
}

11. Write second servlet (ConsumerServlet.java)

import java.io.IOException;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ConsumerServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("********** MESSAGE CONSUMER SERVLET 2 ************");
check();
}

public void check(){
System.out.println("********* Consumer check **********");
String destName = "jms/BinodQueue";
Context jndiContext = null;
ConnectionFactory connectionFactory = null;
Connection connection = null;
Session session = null;
Destination dest = null;
MessageConsumer consumer = null;
TextMessage message = null;
System.out.println("Destination name is " + destName);

try {
jndiContext = new InitialContext();
}catch (NamingException e) { System.out.println("Could not create JNDI API context: " + e.toString()); System.exit(1);
}

try {
connectionFactory = (ConnectionFactory) jndiContext.lookup("jms/BinodConnectionProvider");
dest = (Destination) jndiContext.lookup(destName);
} catch (Exception e) { System.out.println("JNDI API lookup failed: " + e.toString()); System.exit(1);
}

try {
connection = connectionFactory.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
consumer = session.createConsumer(dest);
connection.start();
while (true) {
Message m = consumer.receive(1);
if (m != null) {
if (m instanceof TextMessage) {
message = (TextMessage) m;
System.out.println("Reading message: " + message.getText()); }
else { break; }
}
}
} catch (JMSException e) { System.out.println("Exception occurred: " + e.toString()); }
finally { if (connection != null) { try { connection.close(); }
catch (JMSException e) { }
}
}
}
}

First run Producer Servlet:
http://localhost:9080/JMSSECOND/ProducerServlet
Output:

Sending message: This is message from JMSSECOND DEMO 1
Sending message: This is message from JMSSECOND DEMO 2
Sending message: This is message from JMSSECOND DEMO 3
Sending message: This is message from JMSSECOND DEMO 4
Sending message: This is message from JMSSECOND DEMO 5

Then run Consumer Servlet:
http://localhost:9080/JMSSECOND/ConsumerServlet
Output:


Reading message: This is message from JMSSECOND DEMO 1
Reading message: This is message from JMSSECOND DEMO 2
Reading message: This is message from JMSSECOND DEMO 3
Reading message: This is message from JMSSECOND DEMO 4
Reading message: This is message from JMSSECOND DEMO 5

Please put your comments to give better information in next blog. :)
Source of example.

Thursday, June 11, 2009

what is the difference between JAR, WAR and EAR files

jar - Java archive (file with .jar extension) [For simple java application]
war - Web archive (file with .war extension) [For simple java + jsp/servlet]
ear - Enterprise archive (file with .ear extension) [For simple java + jsp/servlet + EJB]

All three files are zipped file system and used for different purpose.

JAR : JAR is a platform-independent file format that aggregates many files into one. Typically a JAR file contains the class files and auxiliary resources like libraries files, properties file, image, sound etc.

WAR : It is used to deployed in web application like Tomcat. It typically contains servlets, JSPs and their supporting classes and files. A servlet container like Tomcat is required to deploy these file. There are special files and directories within a WAR file. A WAR has a specific directory structure. The top-level directory of a WAR is the document root (WEB-INF) of the application. The document root is where JSP pages, client-side classes and archives, and static Web resources are stored. WEB-INF contains web.xml, classes, lib and Tag library descriptor files.

EAR : An EAR file is a standard JAR file with a .ear extension which is a generally J2EE application. It contains one or more entries representing the modules of the application, and a metadata directory called META-INF which contains one or more deployment descriptors. It is a top-level container which contains modules like: EJB modules, web modules, application client modules etc and deployed to an application server like WebLogic, WebSphere, JBOSS, etc. It might contain WARs, JARs, etc.

JAR -> WAR -> EAR

EAR = WAR(Web module) + JAR(can be EJB module or application client module)

Tuesday, June 9, 2009

How to compare two images, check two image are same or not

You can compare two images using imagemagick.
You can download imagemagick from here. Version must be greater than 6.0. (like ImageMagick-6.4.3-Q16). Suppose you install in "C:\Program Files " folder then you can run command from this location C:\Program Files\ImageMagick-6.4.3-Q16>

After successfully installation you can use this below command
C:\Program Files\ImageMagick-6.4.3-Q16>compare -metric AE 5001.MAIN.jpg 5002.MAIN.jpg difference.jpg
if it returns value 0 means both images are same.

Even you can use -verbose attribute with this command to get more output.
C:\Program Files\ImageMagick-6.4.3-Q16>compare -verbose -metric AE 5001.MAIN.jpg 5002.MAIN.jpg difference.jpg

You can check this command with two different images, two same images.

There are some more command
C:\Program Files\ImageMagick-6.4.3-Q16> compare -compose src rose.jpg reconstruct.jpg difference.png
C:\Program Files\ImageMagick-6.4.3-Q16> compare -verbose -metric mae rose.jpg reconstruct.jpg difference.png
C:\Program Files\ImageMagick-6.4.3-Q16> compare -channel red -metric PSNR rose.jpg reconstruct.jpg difference.png

You can get more info from these link
http://www.imagemagick.org/script/compare.php
http://www.imagemagick.org/Usage/compare/

Tuesday, June 2, 2009

How to get client and server IP address in JSP page

Some time we have to show the server IP address on JSP page and some time we need to store client IP address to next visit purpose.
Using very few lines of code, you can get both server side and client side (browsing) IP address.

GetIPAddress.jsp

<h3> Server Side IP Address </h3><br>
<%@page import="java.net.InetAddress;" %>
<%String ip = "";
InetAddress inetAddress = InetAddress.getLocalHost();
ip = inetAddress.getHostAddress();
out.println("Server Host Name :: "+inetAddress.getHostName());%><br>
<%out.println("Server IP Address :: "+ip);%>

<h3> Client Side IP Address </h3><br>
<%out.print( "Client IP Address :: " + request.getRemoteAddr() ); %><br>
<%out.print( "Client Name Host :: "+ request.getRemoteHost() );%><br>

Sunday, May 31, 2009

How to read Properties file in Java using ResourceBundle and Properties class

There are many ways to read properties file in java. Here explained two way, using

1. ResourceBundle
2. Properties Class
3. How to write properties file is also mentioned in ReadPropFile.java

How to use this tutorial
1. Create one directory src and put both below files (MyProp.properties and ReadPropFile.java)

2. MyProp.properties
name = Binod Kumar Suman
roll = 110
city = Bangalore

3. ReadPropFile.java

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
import java.util.ResourceBundle;


public class ReadPropFile {

public static void main(String[] args) {
// readpropFile();
otherway();
}

public static void readpropFile(){
ResourceBundle bundle = ResourceBundle.getBundle("MyProp");
String studentName = bundle.getString("name");
String roll = bundle.getString("roll");
System.out.println("Student Name :: "+studentName);
System.out.println("Roll Number :: "+roll);

// Fetch all the Properties.

Enumeration keys = bundle.getKeys();
while(keys.hasMoreElements()){
System.out.println(keys.nextElement());
}

}

public static void otherway(){
try{
Properties propertiesFile = new Properties();
propertiesFile.load(new FileInputStream("src/MyProp.properties"));
String studentName = propertiesFile.getProperty("name");
String roll = propertiesFile.getProperty("roll");
System.out.println("Student Name :: "+studentName);
System.out.println("Roll Number :: "+roll);

//Fetch all the Properties.

String key;
Enumeration e = propertiesFile.propertyNames();
while (e.hasMoreElements()) {
key = (String)e.nextElement();
System.out.println(key+" "+propertiesFile.getProperty(key));
}

// Write to properties file
propertiesFile.setProperty("Compnay","Satyam");
propertiesFile.store(new FileOutputStream("src/MyProp.properties"),null);


}catch(IOException e){
e.printStackTrace();
}
}
}

Saturday, May 23, 2009

How to read file in Java

Put both java file and Myfile.txt file in same folder.


import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;


public class ReadFile {

public static FileReader reader;
public static BufferedReader br;

public static void main(String[] args) {
try {
reader = new FileReader("MyFile.txt");
br = new BufferedReader(reader);
String data="";

while((data = br.readLine())!= null){
System.out.println(data);
}

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

How to write file in Java

Put both java file and Myfile.txt file in same folder.

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;

public class WriteFile {

public static FileWriter writer;
public static BufferedWriter bw;

public static void main(String[] args) {
try{
writer = new FileWriter("MyFile.txt",true);
// writer = new FileWriter("src\\MyFile.txt"); For every time new file.

bw = new BufferedWriter(writer);
bw.write("\n");
bw.write("WRITTING some thing");
bw.close();
System.out.println("Check your file");
}catch(FileNotFoundException e){ e.printStackTrace(); }
catch(IOException e){ e.printStackTrace(); }
}
}

How to get IP Address by Java

import java.net.InetAddress;
public class GetIPAddress {

public static void main(String[] args) {
String ip = "";
try {
InetAddress inetAddress = InetAddress.getLocalHost();
ip = inetAddress.getHostAddress();
System.out.println("IP Address :: "+ip);
} catch (Exception e) {
e.printStackTrace();
}
}

}

Thursday, May 14, 2009

How to get other TimeZone time by JAVA

You can get any timezone time just you should have the timezone ID. Here I gave two methods.
1. How to get all timezone ID.
2. How to get time of any timezone ID.
Both methods are in the same java file (OtherTimeZoneTime.java)


import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

public class OtherTimeZoneTime {

public static void main(String[] args) {
String timeZoneId = "America/Chicago";
getTime(timeZoneId);
// getAllTimeZone();
}

public static void getAllTimeZone() {
String[] zoneIds = TimeZone.getAvailableIDs();
for (int i = 0; i < zoneIds.length; i++) {
TimeZone tz = TimeZone.getTimeZone(zoneIds[i]);
System.out.println(tz.getID() + " " + tz.getDisplayName());
}
}

public static void getTime(String timeZoneId) {
Calendar calTZ = new GregorianCalendar(TimeZone.getTimeZone(timeZoneId));
calTZ.setTimeInMillis(new Date().getTime());
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, calTZ.get(Calendar.YEAR));
cal.set(Calendar.MONTH, calTZ.get(Calendar.MONTH));
cal.set(Calendar.DAY_OF_MONTH, calTZ.get(Calendar.DAY_OF_MONTH));
cal.set(Calendar.HOUR_OF_DAY, calTZ.get(Calendar.HOUR_OF_DAY));
cal.set(Calendar.MINUTE, calTZ.get(Calendar.MINUTE));
cal.set(Calendar.SECOND, calTZ.get(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, calTZ.get(Calendar.MILLISECOND));
System.out.println(cal.getTime());
}
}

Some timeZoneId :
Asia/Calcutta
Europe/Vatican
Asia/Istanbul
Australia/Darwin
Australia/Melbourne
Australia/Sydney
America/Cordoba
America/Fortaleza
America/Godthab
America/Jujuy
America/Maceio

Tuesday, May 12, 2009

How to backup of your blogger blog

There are many ways to take your blog backup. Even some tools are also available in market. But here I explain two ways:

1. Write one simple java program and take many blog backup together with timestamp.
2. Use Export and Import facility of blogger

1. Write one simple java code (BlogBackup.java)


import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;

public class BlogBackup {
public static String repo = "E:\\Blog_BACKUP\\";
public static String ext = ".xml";
public static String url1 = "http://your_blogName _1.blogspot.com/feeds/posts/default?max-results=1000";
public static String url2 = "http://your_blogName _2.blogspot.com/feeds/posts/default?max-results=1000";
public static String url3 = "http://your_blogName _3.blogspot.com/feeds/posts/default?max-results=1000";

public static void main(String[] args) {
takeBackup();
}
public static void takeBackup(){
String folderName = createFolder();
String[] url = {url1,url2,url3};
try {
for(int i=0;iString fileName = folderName+"\\"+getFileName(url[i]);
doDownload(url[i],fileName);
System.out.println("Completed :: "+fileName);
}
} catch (IOException e) {e.printStackTrace();}
}
public static String getFileName(String url){
String fileName = url.substring(url.indexOf("//")+2,url.indexOf("."));
Format formatter = new SimpleDateFormat("MMM-dd-yyyy-HH-mm");
String now = formatter.format(new Date());
return fileName+"_"+now+ext;
}
public static String createFolder(){
Format formatter = new SimpleDateFormat("MMM-dd-yyyy");
String folderName = repo + formatter.format(new Date());
System.out.println("Folder Name :: "+folderName);
File file = new File(folderName);
if(!file.exists()){
file.mkdir();
}
return folderName;
}
public static void doDownload(String blogURL, String fileName) throws IOException {
String charset = "utf-8";
URL url = new URL(blogURL);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
InputStream inputStream = null;
inputStream = url.openStream();
StringBuffer s = new StringBuffer();
if(charset==null"".equals(charset)){
charset="utf-8"; }
String rLine = null;
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream,charset));
PrintWriter printWriter = null;
FileOutputStream fo = new FileOutputStream(fileName);
OutputStreamWriter writer = new OutputStreamWriter(fo, "utf-8");
printWriter = new PrintWriter(writer);
while ( (rLine = bReader.readLine()) != null) {
String line = rLine;
int str_len = line.length();
if (str_len > 0) {
s.append(line);
printWriter.println(line);
printWriter.flush();
}
line = null;
}
inputStream.close();
printWriter.close();
}
}

You can change the repository folder name, I used here "E:\\Blog_BACKUP\\";
Whenever you will run this java code, it will create folder as running date and inside that folder your all blog backup will come with timestamp.

Please share your comments with me ........... :)

2. Another way
Step1 : Login to your blog (http://www.blogger.com)
Step2: Go to Setting tab
Step3: You will get Blog Tools (Upper left side)
Step4: Right side option are there like Import blogs, Export blogs, Delete blogs.

String.replaceAll not working, solution here

Sometime we get Exception in thread "main" java.util.regex.PatternSyntaxException during String.replaceAll() using.
When I used this code :

public void replaceString(String path){
System.out.println("Original Path :: "+path);
String ret = path.replaceAll("\\","/");
System.out.println("Return :: "+ret);
}
I got this exception
Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1.


So for my project I am using this below custome method by the replaceAll method.


public void replaceString(String path){
System.out.println("Original Path :: "+path);
String ret = replaceAllString(path,"\\","/");
System.out.println("Return :: "+ret);
//return ret;
}
public String replaceAllString(String strOrig, String strFind, String strReplace) {
if(strOrig == null) {
return null;
}
StringBuffer sb = new StringBuffer(strOrig);
String toReplace = "";
if (strReplace == null) toReplace = "";
else toReplace = strReplace;
int pos = strOrig.length();
while (pos > -1) {
pos = strOrig.lastIndexOf(strFind, pos);
if (pos > -1) sb.replace(pos, pos+strFind.length(), toReplace);
pos = pos - strFind.length();
}
return sb.toString();
}

Its working fine for my project.

Monday, May 11, 2009

How to use Runtime.getRuntime().exec, How to solve java.io.IOException, error 2, Use Dos command in Java

This below code is very perfect to use Runtime.getRuntime().exec in windows platform as well as unix platform. You will not get ioexception error2 using this code.

Here, there are three method. Out of these first two you can put in common java file. Three is calling method to execute any dos commnad.

public Boolean exec(String[] command) {
Process proc;
StringBuffer cmdStr= new StringBuffer();
for(int i=0; icmdStr.append(command[i].trim());
if(i!=command.length-1){
cmdStr.append(" ");
}
}
try {
proc = Runtime.getRuntime().exec(cmdStr.toString());
} catch (IOException e) {
System.out.println("EXCEPTION_IO" + command);
System.out.println("EXCEPTION_TRACE"+ e);
return new Boolean(false);
}
int exitStatus;
while (true) {
try {
exitStatus = proc.waitFor();
break;
} catch (java.lang.InterruptedException e) {
System.out.println("EXCEPTION_TRACE"+ e);
}
}
if (exitStatus == 0) {
InputStream is = proc.getInputStream();
readStreamData(is);
}
if (exitStatus != 0) {
InputStream e = proc.getErrorStream();
String error = readStreamData(e);
System.out.println("ERROR_COMMAND"+ error);
}
return new Boolean(exitStatus == 0);
}

private static String readStreamData(InputStream e) {
BufferedInputStream bre = new BufferedInputStream(e);
String output = new String(" ");
try {
int readInt = bre.read();
while (readInt != -1) {
char c = (char) readInt;
output = output + c;
readInt = bre.read();
}
} catch (IOException e1) {
e1.printStackTrace();
}
return output;
}


public void copyFile(){
String sourceFile = "c:\\abcd\\mainImage\\DSC01596.JPG";
String destFile = "C:\\BackupImage\\Home";
List command = new ArrayList();
command.add("cmd.exe");
command.add("/c");
command.add("copy");
command.add(sourceFile);
command.add(destFile);
System.out.println("Executing Command :: " + command);
if(exec((String[]) command.toArray(new String[1]))){
System.out.println("Copied Successfully");
}
else{
System.out.println("Some Problem during copy");
}
}