Friday, September 28, 2012

Restore MySql Backup file by using JAVA

First read my early blog post "Take the MySql DB backup in JAVA" and you can download the source from there

[sourcecode language="java"]

public boolean restoreDatabase(String dbUserName, String dbPassword, String source) {

String[] executeCmd = new String[]{"mysql", "--user=" + dbUserName, "--password=" + dbPassword, "-e", "source " + source};

Process runtimeProcess;
try {
runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();

if (processComplete == 0) {
log.info("Backup restored successfully with " + source);
return true;
} else {
log.info("Could not restore the backup " + source);
}
} catch (Exception ex) {
log.error(ex, ex.getCause());
}

return false;

}

[/sourcecode]

Take the MySql DB backup in JAVA

This is very impotent blog post for the most application developers
Here I'm talking about how to backup the mysql databasae through JAVA program.
Download MySqlBackup.java you have to download mysql.jar and log4j.jar

1. Following method will create the data base backup without create and drop database commands
It's only creating tables and included data
When your going to restore the database first you have to create new DB

[sourcecode language="java"]
public boolean backupDataWithOutDatabase(String dumpExePath, String host, String port, String user, String password, String database, String backupPath) {
boolean status = false;
try {
Process p = null;

DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = new Date();
String filepath = "backup(without_DB)-" + database + "-" + host + "-(" + dateFormat.format(date) + ").sql";

String batchCommand = "";
if (password != "") {
//only backup the data not included create database
batchCommand = dumpExePath + " -h " + host + " --port " + port + " -u " + user + " --password=" + password + " " + database + " -r \"" + backupPath + "" + filepath + "\"";
} else {
batchCommand = dumpExePath + " -h " + host + " --port " + port + " -u " + user + " " + database + " -r \"" + backupPath + "" + filepath + "\"";
}

Runtime runtime = Runtime.getRuntime();
p = runtime.exec(batchCommand);
int processComplete = p.waitFor();

if (processComplete == 0) {
status = true;
log.info("Backup created successfully for without DB " + database + " in " + host + ":" + port);
} else {
status = false;
log.info("Could not create the backup for without DB " + database + " in " + host + ":" + port);
}

} catch (IOException ioe) {
log.error(ioe, ioe.getCause());
} catch (Exception e) {
log.error(e, e.getCause());
}
return status;
}

[/sourcecode]

2. This method will create a backup from Specified database with create and drop database commands
When your going to restore the DB you don't need to create the DB it will handle by the script

[sourcecode language="java"]
public boolean backupDataWithDatabase(String dumpExePath, String host, String port, String user, String password, String database, String backupPath) {
boolean status = false;
try {
Process p = null;

DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = new Date();
String filepath = "backup(with_DB)-" + database + "-" + host + "-(" + dateFormat.format(date) + ").sql";

String batchCommand = "";
if (password != "") {
//Backup with database
batchCommand = dumpExePath + " -h " + host + " --port " + port + " -u " + user + " --password=" + password + " --add-drop-database -B " + database + " -r \"" + backupPath + "" + filepath + "\"";
} else {
batchCommand = dumpExePath + " -h " + host + " --port " + port + " -u " + user + " --add-drop-database -B " + database + " -r \"" + backupPath + "" + filepath + "\"";
}

Runtime runtime = Runtime.getRuntime();
p = runtime.exec(batchCommand);
int processComplete = p.waitFor();

if (processComplete == 0) {
status = true;
log.info("Backup created successfully for with DB " + database + " in " + host + ":" + port);
} else {
status = false;
log.info("Could not create the backup for with DB " + database + " in " + host + ":" + port);
}

} catch (IOException ioe) {
log.error(ioe, ioe.getCause());
} catch (Exception e) {
log.error(e, e.getCause());
}
return status;
}

[/sourcecode]

Friday, September 14, 2012

How to Create Sample Database in MSSQL with Sample Data

This is very useful for application testing.

First you have to download the relevant sample databases from http://msftdbprodsamples.codeplex.com/releases/view/59211

Then copy the relevant AdventureWorks2008R2_Data.mdf file in to your machine where the MSSQL is installed. then go to MSSQL Editor and run the following query

[sourcecode language="sql"]

CREATE DATABASE AdventureWorks2012
ON (FILENAME = 'D:\AdventureWorks2012_Data.mdf')
FOR ATTACH_REBUILD_LOG ;

[/sourcecode]

Don't delete the above AdventureWorks2008R2_Data.mdf because this will be your database in MSSQL

Thursday, September 13, 2012

About log4j.properties

log4j.properties Syntax:
Following is the syntax of log4j.properties file for an appender X:

[sourcecode language="text"]
# Define the root logger with appender X
log4j.rootLogger = DEBUG, X

# Set the appender named X to be a File appender
log4j.appender.X=org.apache.log4j.FileAppender

# Define the layout for X appender
log4j.appender.X.layout=org.apache.log4j.PatternLayout
log4j.appender.X.layout.conversionPattern=%m%n
[/sourcecode]

log4j.rootLogger - the first element should be the logging level, Second one should be the appender

Logging levels -
TRACE < DEBUG < INFO < WARN < ERROR < FATAL < ALL







































LevelDescription
ALLAll levels including custom levels.
DEBUGDesignates fine-grained informational events that are most useful to debug an application.
ERRORDesignates error events that might still allow the application to continue running.
FATALDesignates very severe error events that will presumably lead the application to abort.
INFODesignates informational messages that highlight the progress of the application at coarse-grained level.
OFFThe highest possible rank and is intended to turn off logging.
TRACEDesignates finer-grained informational events than the DEBUG.
WARNDesignates potentially harmful situations.

We have used only one appender FileAppender in our example above. All the possible appender options are:

  • AppenderSkeleton

  • AsyncAppender

  • ConsoleAppender

  • DailyRollingFileAppender

  • ExternallyRolledFileAppender

  • FileAppender

  • JDBCAppender

  • JMSAppender

  • LF5Appender

  • NTEventLogAppender

  • NullAppender

  • RollingFileAppender

  • SMTPAppender

  • SocketAppender

  • SocketHubAppender

  • SyslogAppender

  • TelnetAppender

  • WriterAppender


We have used PatternLayout with our appender. All the possible options are:

  • DateLayout

  • HTMLLayout

  • PatternLayout

  • SimpleLayout

  • XMLLayout

Tuesday, September 11, 2012

Log4j with NetBeans IDE

I think this post will help you to configure the log4j in Netbeans IDE

First you have to create the Java Project "Log4j"
Then you have to put the "log4j.properties" file in to your src folder "This should be located in root"

[sourcecode language="text"]
#### Use Three appenders,
#stdout - is used for write to console
#R - is used for write to file
log4j.rootLogger=debug, stdout, R
# Print only messages of priority WARN or higher for your category
# log4j.category.your.category.name=WARN
# Specifically inherit the priority level
#log4j.category.your.category.name=INHERITED

# Print only messages of level WARN or above in the package
#This is use for debuging mode
log4j.logger.testlogging=DEBUG

&nbsp;

#### Appender writes to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd} %5p [%t] (%F:%L) - %m%n

&nbsp;

#### Appender writes to a file
#log4j.appender.R=org.apache.log4j.FileAppender
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=example.log
# Control the maximum log file size
log4j.appender.R.MaxFileSize=100KB
# Archive log files (one backup file here)
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d{yyyy-MM-dd} %5p [%t] (%F:%L) - %m%n
#log4j.appender.R.layout.ConversionPattern=%n%p - %m
[/sourcecode]


Finally you have to take this "log4j-1.2.17.jar" file and add in to the class path

Now you done all configuration lets try to use it

[sourcecode language="java"]
package log4j;

import org.apache.log4j.Logger;

/**
*
* @author dinuka
*/
public class Log4J {

//initializing the logger
static Logger log = Logger.getLogger(Log4J.class.getName());

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
//logging in different levels
log.trace("This is a Trace");
log.debug("This is a Debug");
log.info("This is an Info");
log.warn("This is a Warn");
log.error("This is an Error");
log.fatal("This is a Fatal");

}
}
[/sourcecode]

Output file

[sourcecode language="text"]
2012-09-11 TRACE [main] (Log4J.java:19) - This is a Trace
2012-09-11 DEBUG [main] (Log4J.java:20) - This is a Debug
2012-09-11 INFO [main] (Log4J.java:21) - This is an Info
2012-09-11 WARN [main] (Log4J.java:22) - This is a Warn
2012-09-11 ERROR [main] (Log4J.java:23) - This is an Error
2012-09-11 FATAL [main] (Log4J.java:24) - This is a Fatal

[/sourcecode]

Friday, September 7, 2012

Read XML in Java

First follow this post http://malalanayake.wordpress.com/2012/09/07/write-xml-in-java/

XmlReader.java

[sourcecode language="java"]
package mysamples;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XmlReader {

private String name;
private String content;
private Map<String, String> nameAttributes = new HashMap<String, String>();
private Map<String, ArrayList<XmlReader>> nameChildren = new HashMap<String, ArrayList<XmlReader>>();

public XmlReader(InputStream inputStream, String rootName) {
this(rootElement(inputStream, rootName));
}

public XmlReader(String filename, String rootName) {
this(fileInputStream(filename), rootName);
}

public XmlReader(String rootName) {
this.name = rootName;
}

private XmlReader(Element element) {
this.name = element.getNodeName();
this.content = element.getTextContent();
NamedNodeMap namedNodeMap = element.getAttributes();
int n = namedNodeMap.getLength();
for (int i = 0; i < n; i++) {
Node node = namedNodeMap.item(i);
String name = node.getNodeName();
addAttribute(name, node.getNodeValue());
}
NodeList nodes = element.getChildNodes();
n = nodes.getLength();
for (int i = 0; i < n; i++) {
Node node = nodes.item(i);
int type = node.getNodeType();
if (type == Node.ELEMENT_NODE) {
XmlReader child = new XmlReader((Element) node);
addChild(node.getNodeName(), child);
}

}
}

public void addAttribute(String name, String value) {
nameAttributes.put(name, value);
}

private void addChild(String name, XmlReader child) {
ArrayList<XmlReader> children = nameChildren.get(name);
if (children == null) {
children = new ArrayList<XmlReader>();
nameChildren.put(name, children);
}
children.add(child);
}

public String name() {
return name;
}

public void setContent(String content) {
this.content = content;
}

public String content() {
return content;
}

public void addChild(XmlReader xml) {
addChild(xml.name(), xml);
}

public void addChildren(XmlReader... xmls) {
for (XmlReader xml : xmls) {
addChild(xml.name(), xml);
}
}

public XmlReader child(String name) {
XmlReader child = optChild(name);
if (child == null) {
throw new RuntimeException("Could not find child node: " + name);
}
return child;
}

public XmlReader optChild(String name) {
ArrayList<XmlReader> children = children(name);
int n = children.size();
if (n > 1) {
throw new RuntimeException("Could not find individual child node: " + name);
}
return n == 0 ? null : children.get(0);
}

public boolean option(String name) {
return optChild(name) != null;
}

public ArrayList<XmlReader> children(String name) {
ArrayList<XmlReader> children = nameChildren.get(name);
return children == null ? new ArrayList<XmlReader>() : children;
}

public String string(String name) {
String value = optString(name);
if (value == null) {
throw new RuntimeException(
"Could not find attribute: " + name + ", in node: " + this.name);
}
return value;
}

public String optString(String name) {
return nameAttributes.get(name);
}

public int integer(String name) {
return Integer.parseInt(string(name));
}

public Integer optInteger(String name) {
String string = optString(name);
return string == null ? null : integer(name);
}

public double doubleValue(String name) {
return Double.parseDouble(optString(name));
}

public Double optDouble(String name) {
String string = optString(name);
return string == null ? null : doubleValue(name);
}

private static Element rootElement(InputStream inputStream, String rootName) {
try {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document document = builder.parse(inputStream);

Element rootElement = document.getDocumentElement();
if (!rootElement.getNodeName().equals(rootName)) {
throw new RuntimeException("Could not find root node: " + rootName);
}
return rootElement;
} catch (IOException exception) {
throw new RuntimeException(exception);
} catch (ParserConfigurationException exception) {
throw new RuntimeException(exception);
} catch (SAXException exception) {
throw new RuntimeException(exception);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception exception) {
throw new RuntimeException(exception);
}
}
}
}

private static FileInputStream fileInputStream(String filename) {
try {
return new FileInputStream(filename);
} catch (IOException exception) {
throw new RuntimeException(exception);
}
}

}
[/sourcecode]


Here I'm Reading the Employee.xml

[sourcecode language="java"]
public static void main(String[] args) {
XmlReader config = new XmlReader("Employee.xml", "employees");

System.out.println("title: " + config.child("employee").content());

for(XmlReader firstname : config.child("employee").children("firstname")){
System.out.println("First Name :" + firstname.content());
}

for(XmlReader firstname : config.child("employee").children("lastname")){
System.out.println("Last Name :" + firstname.content());
}

for(XmlReader firstname : config.child("employee").children("age")){
System.out.println("Age :" + firstname.content());
}

for(XmlReader firstname : config.child("employee").children("email")){
System.out.println("Email :" + firstname.content());
}

}
[/sourcecode]

If You need to read something like this kind of xml you can do it in this way

[sourcecode language="java"]
<config>
<title>test</title>
<version
major="1"
minor="2"/>
<roles>
<role name="admin"/>
<role name="user"/>
</roles>
<users>
<user name="joe" password="pass" role="admin"/>
<user name="harry" password="secret" role="user" email="harry@me.com"/>
</users>
<test/>
</config>
[/sourcecode]


[sourcecode language="java"]
public static void main(String[] args) {
Xml config = new Xml("config.xml","config");

System.out.println("title: "+config.child("title").content());

Xml version = config.child("version");
System.out.println("version: "+version.integer("major")+"."+version.integer("minor"));

for(Xml role:config.child("roles").children("role"))
System.out.println("role: name: "+role.string("name"));

for(Xml user:config.child("users").children("user")) {
String email = user.optString("email");
System.out.println(
"user: name: "+user.string("name")+
", password: "+user.string("password")+
", role: "+user.string("role")+
", email: "+(email==null ? "-" : email));
}

System.out.println("test: "+config.option("test"));
}
[/sourcecode]

Write XML in JAVA

XmlWriter.java is a simple XML file generator.

[sourcecode language="java"]
package mysamples;

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
*
* @author dinuka
*/
public class XmlWriter {

public static void main(String argv[]) {

try {

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

// root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("employees");
doc.appendChild(rootElement);

// staff elements
Element staff = doc.createElement("employee");
rootElement.appendChild(staff);

// set attribute to staff element
Attr attr = doc.createAttribute("id");
attr.setValue("1");
staff.setAttributeNode(attr);

// shorten way
// staff.setAttribute("id", "1");

// firstname elements
Element firstname = doc.createElement("firstname");
firstname.appendChild(doc.createTextNode("Dinuka"));
staff.appendChild(firstname);

// lastname elements
Element lastname = doc.createElement("lastname");
lastname.appendChild(doc.createTextNode("Malalanayake"));
staff.appendChild(lastname);

// nickname elements
Element age = doc.createElement("age");
age.appendChild(doc.createTextNode("25"));
staff.appendChild(age);

// salary elements
Element email = doc.createElement("email");
email.appendChild(doc.createTextNode("dinuka.malalanayake@gmail.com"));
staff.appendChild(email);

// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("Employee.xml"));

// Output to console for testing
//StreamResult result = new StreamResult(System.out);

transformer.transform(source, result);

System.out.println("File saved!");

} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
}
}
[/sourcecode]

Bettor to read following posts as well

http://malalanayake.wordpress.com/2012/09/07/read-xml-file-to-object-in-java/

http://malalanayake.wordpress.com/2012/09/07/persist-java-object-to-xml/

Read XML file to Object in Java

Read this first persist-java-object-to-xml

Here I'm doing just read the data from given XML file

XmlToBean.java

[sourcecode language="java"]
package mysamples;

import java.beans.XMLDecoder;
import java.io.BufferedInputStream;
import java.io.FileInputStream;

/**
*
* @author dinuka
*/
public class XmlToBean {

public static void main(String[] args) {
try {

//Read the xml file and set data to MyBean Object
MyBean myReadBean = new MyBean();
XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(new FileInputStream("MyBean.xml")), myReadBean);
myReadBean = (MyBean) decoder.readObject();
decoder.close();

//print the myReadBean object
myReadBean.print();

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

[/sourcecode]

Persist JAVA object to XML

This is very useful for developers who are going to implement the XML base java solutions. Here I'm showing how to persist the simple java object to XML.

First I create the MyBean.java class.

[sourcecode language="java"]
package mysamples;

import java.util.ArrayList;

/**
*
* @author dinuka
*/
public class MyBean {

private String name = null;
private int age;
private ArrayList telephonNos;

public MyBean() {
telephonNos = null;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public ArrayList getTelephonNos() {
return telephonNos;
}

public void setTelephonNos(ArrayList add) {
this.telephonNos = add;
}

public void print(){
System.out.println("Name :"+this.name);
System.out.println("Age :"+this.age);
for(Integer tp: telephonNos){
System.out.println("Tp :"+tp);
}
}
}
[/sourcecode]

BeanToXml.java this is a simple class to persist the above MyBean.java

[sourcecode language="java"]
package mysamples;

import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
/**
*
* @author dinuka
*/
public class BeanToXml {

public static void main(String[] args) {
try {
MyBean myWriteBean = new MyBean();
myWriteBean.setName("Tom");
myWriteBean.setAge(28);
ArrayList places = new ArrayList();

places.add(123456789);
places.add(623623828);
myWriteBean.setTelephonNos(places);

//Save the MyBean object to xml
XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream("MyBean.xml")));
encoder.writeObject(myWriteBean);
encoder.close();

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

}
}
[/sourcecode]

Output - MyBean.xml

Monday, September 3, 2012

own java application for tweet

In this article I'm going to discuss how to create our own java application for tweet.

This sample we need to have twitter4j libraries. Here you can download twitter netbeans project.

1. First go to this site https://dev.twitter.com/ and log in to your account



2. Then create a new application

Here you have to fill the necessary fields for create the application but in our JAVA program we are not going to use those details.





3. Then select the "settings" tab in the application and change the "Access type" - "Read only" to "Read,Write Access direct messages"



4. Now go to "Details" tab "Create access token" then you will get the access token details. Now we have own application details in our twitter account server

5. In this step I'm going to create the JAVA application. First open the downloaded netbeans project and set this twitter4j libs in your project class path

Now you have to change the property file "twitter4j.properties" by replacing your following keys

oauth.consumerKey
oauth.consumerSecret
oauth.accessToken
oauth.accessTokenSecret

Now you can run this application then you can see the message that you gave in the program(by default i gave  Hi guys this is test application) will be posted in your account.

Enjoy with own JAVA Application for Twitter. Thanks.