RSS

Monthly Archives: September 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


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;

    }

 
2 Comments

Posted by on September 28, 2012 in java, mysql

 

Tags: , ,

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

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;
}

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

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;
    }

 
9 Comments

Posted by on September 28, 2012 in java, mysql

 

Tags: , ,

Most Useful websites for developers


Email Marketing – http://mailchimp.com/

Time Tracking system – https://www.toggl.com/

Web Designing and hosting – http://www.webs.com/ , http://www.ucoz.com/

Issue Tracking system  –  https://www.etraxis.com/

 

 
2 Comments

Posted by on September 18, 2012 in java, MSSQL, mysql, Other

 

Tags: , , , ,

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


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

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

 
Leave a comment

Posted by on September 14, 2012 in MSSQL

 

Tags: , , ,

About log4j.properties


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

# 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

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

Level Description
ALL All levels including custom levels.
DEBUG Designates fine-grained informational events that are most useful to debug an application.
ERROR Designates error events that might still allow the application to continue running.
FATAL Designates very severe error events that will presumably lead the application to abort.
INFO Designates informational messages that highlight the progress of the application at coarse-grained level.
OFF The highest possible rank and is intended to turn off logging.
TRACE Designates finer-grained informational events than the DEBUG.
WARN Designates 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
 
Leave a comment

Posted by on September 13, 2012 in java

 

Tags: , , ,

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”

#### 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


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

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");

 }
}

Output file

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

 
10 Comments

Posted by on September 11, 2012 in java

 

Tags: , ,

Read XML in Java


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

XmlReader.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);
 }
 }

}

Here I’m Reading the Employee.xml

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());
}

}

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

<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>
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"));
}
 
Leave a comment

Posted by on September 7, 2012 in java

 

Tags: , ,

 
%d bloggers like this: