Fast and Flexible DB Retrieval API from Apache DB Util

Sample Program : 

Dependency Jar Library Files :

1] commons-dbcp-1.4.jar

2] commons-dbutils-1.7.jar

3] commons-lang3-3.7.jar

4] commons-pool2-2.4.3.jar

5] mysql-connector-java-6.0.6.jar

=============================================

public class ErrorBean {
private int id;
private String severity;
private String errorcode;

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSeverity() {
return severity;
}
public void setSeverity(String severity) {
this.severity = severity;
}
public String getErrorcode() {
return errorcode;
}
public void setErrorcode(String errorcode) {
this.errorcode = errorcode;
}
}

===========================================

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

public class AsbmQueryGenerator {

public static void main(String[] args) throws SQLException {

final String url = “jdbc:mysql://localhost:3306/imig_error_engine”;
final String driver = “com.mysql.jdbc.Driver”;
final String usr = “root”;
final String pwd = “root”;
Connection connection =null;
try{

AsbmQueryGenerator asbm = new AsbmQueryGenerator();
connection = asbm.AsbmDatabaseConnector(url,driver,usr,pwd);
System.out.println(“Connection Success :=> “+connection);

QueryRunner run = new QueryRunner();
ResultSetHandler<List<ErrorBean>> resultHandler = new BeanListHandler<ErrorBean>(ErrorBean.class);
List<ErrorBean> errorList = run.query(connection, “SELECT * FROM core_error”,resultHandler);
System.out.println(” ERROR SIZE :”+errorList.size());

for(ErrorBean errBean:errorList){
//System.out.print( ToStringBuilder.reflectionToString((Object)errorList.get(1),ToStringStyle.MULTI_LINE_STYLE));
System.out.print(“ID: ” + errBean.getId());
System.out.print(“, SEVERITY: ” + errBean.getSeverity());
System.out.print(“, ERROR_CODE: ” + errBean.getErrorcode());
}
} finally {
DbUtils.close(connection);
}

}

/*
* This will return the Database Connection
*
*/
public Connection AsbmDatabaseConnector(String urlString,String driverString,String userName,String password)throws SQLException
{
DbUtils.loadDriver(driverString);
Connection connection = DriverManager.getConnection(urlString, userName, password);
return connection;
}

}

Advertisements
Posted in Core Java | Leave a comment

Software Quality is one of the major factor for Software Delivery

Delivering great software depends on many factors, quality surely being one of the most important ones. Software quality management is key in making sure that the final product meets all requirements and works as expected.

Therefore quality management should start the same day a new project is laid out. Just as important as the development plan, the software quality plan lists quality goals, resources, and the time line for making sure that quality standards are met.

One critical part of the quality plan is defining the set of test cases to measure quality and confirm that all requirements are covered. Depending on the size of the project this can range from a few dozen to hundreds if not thousands of test cases.

Sonar is one of the good Software Code Quality management tool to help developer to identify the Root causes and loop holes in the software code

How to Install and Configure Sonar Software Quality Control Tool:

Prerequisite :

1] Java JDK 8 and Above

2] Sonar Package

3] Apache Maven

Database :

CREATE DATABASE sonar CHARACTER SET utf8 COLLATE utf8_general_ci;
CREATE USER ‘sonar’ IDENTIFIED BY ‘sonar’;
GRANT ALL ON sonar.* TO ‘sonar’@’%’ IDENTIFIED BY ‘sonar’;
GRANT ALL ON sonar.* TO ‘sonar’@’localhost’ IDENTIFIED BY ‘sonar’;
FLUSH PRIVILEGES;

Here i am using the MySQL Database,But you can choose any Database,Oracle,H2 DB or Any other databases

Set Java 8 – Java Home Environment Variable :

C:\Program Files\Java\jdk1.7.0_79\bin;

Deploy and Start Sonar Package :

1] C:\Users\eashmru\Documents\Softwares\SonarQube\sonarqube-7.0\bin

2] Execute StartSonar.bat

Open Browser and Enter URL:

http://127.0.0.1:9000/sonar/

OR

http://localhost:9000/sonar/

Login Sonar User Interface:

1] Enter Username : admin

2] Enter Password : admin

3] Generate Unique ID with your credentials

Open Project Directory in Command Prompt where your Project POM.xml file located :

1] Execute this Command

mvn sonar:sonar -Dsonar.host.url=http://127.0.0.1:9000

-Dsonar.login=662bb2c970e63b13a08f2386349876eae8688acf

2] Else Execute this Command as Default

mvn clean install sonar:sonar

View Project Code Quality:

Now you can view all Quality gateway of code managements

 

 

 

 

 

| Leave a comment

Database Partition Systems – Cluster Architecture

CREATE PARTITION AND TABLE SPACES:

CREATE BIGFILE TABLESPACE bigtbs_00
DATAFILE ‘/u01/imig/clusterdb/PARTITION_0.dat’
SIZE 250M AUTOEXTEND ON;

CREATE BIGFILE TABLESPACE bigtbs_01
DATAFILE ‘/u01/imig/clusterdb/PARTITION_1.dat’
SIZE 250M AUTOEXTEND ON;

CREATE BIGFILE TABLESPACE bigtbs_02
DATAFILE ‘/u01/imig/clusterdb/PARTITION_2.dat’
SIZE 250M AUTOEXTEND ON;

CREATE SAMPLE TABLE FOR DEMO :

CREATE TABLE SAMPLE_DEMO (
CHUNK_ID NUMBER NOT NULL,
NAME VARCHAR2(30) NOT NULL,
DESCRIPTION VARCHAR2(4000),
PARTITION_ID NUMBER GENERATED ALWAYS AS         (MOD(TO_NUMBER(“CHUNK_ID”),3)) VIRTUAL
)
PARTITION BY LIST (PARTITION_ID)
(
PARTITION PARTITION_0 VALUES (0) TABLESPACE  bigtbs_00,
PARTITION PARTITION_1 VALUES (1) TABLESPACE  bigtbs_01,
PARTITION PARTITION_2 VALUES(2) TABLESPACE  bigtbs_02
);

INSERT SAMPLE VALUES TO TABLE :

INSERT INTO SAMPLE_DEMO VALUES(12,’Pepe Ortiz’,’Demo Execution 1′,default);
INSERT INTO SAMPLE_DEMO VALUES(13,’Ashoka Bhat’,’Demo Execution 2′,default);
INSERT INTO SAMPLE_DEMO VALUES(14,’Shivakumar’,’Demo Execution 3′,default);

RETRIEVE THE VALUE FROM TABLE :

SELECT * FROM SAMPLE_DEMO

VIEW THE LIST OF AVAILABLE TABLESPACES :

SELECT TABLESPACE_NAME, STATUS, CONTENTS FROM USER_TABLESPACES;

select * from database_properties where property_name like ‘%TABLESPACE’;

select * from user_part_tables;

DROP TABLE SPACES AND PARTITIONS :

DROP TABLESPACE bigtbs_00
INCLUDING CONTENTS AND DATAFILES;

DROP TABLESPACE bigtbs_01
INCLUDING CONTENTS AND DATAFILES;

DROP TABLESPACE bigtbs_02
INCLUDING CONTENTS AND DATAFILES;

DROP TABLESPACE PARTITION_0
INCLUDING CONTENTS AND DATAFILES;

DROP TABLESPACE PARTITION_1
INCLUDING CONTENTS AND DATAFILES;

DROP TABLESPACE PARTITION_2
INCLUDING CONTENTS AND DATAFILES;

 

| Leave a comment

Lift Operation – Program Development in Java Interesting !!!

import java.awt.geom.*;

public class elevator
{

    static int floor;

    public static void main(String args[])
    {

        floor = (int) (Math.random() * 10 + 1);

        System.out.println("The elevator is now on floor " +floor);
        System.out.print("Which floor are you at now (0-10) where 0 = basement: ");
        int current_floor = Keyboard.readInt();

        if(floor == current_floor)
        {
            System.out.println("Enter the elevator");
        }
        else
        {
            MoveElevator(current_floor);
        }


        System.out.println("To which floor would you want to go (0-10) where 0 = basement");
        int target_floor = Keyboard.readInt();

        MoveElevator(target_floor);
    }

    public static void MoveElevator(int target_floor)
    {
        int direction;
        if( target_floor > floor )
        {
            System.out.println("The elevator is on it's way up...");
            direction = 1;
        }else{
            System.out.println("The elevator is on it's way down...");
            direction = -1;
        }

        while(target_floor != floor)
        {
            floor += direction;
            System.out.println(floor);
        }

        System.out.println("The elevator has arrived");
    }
| Leave a comment

Matrix Graph Implementation in Java

public class MatrixGraphs {

public static void main(String args[]) {
AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(10);
graph.addEdge(1, 2);
graph.addEdge(1, 5);
graph.addEdge(2, 5);
graph.addEdge(1, 2);
graph.addEdge(2, 3);
graph.addEdge(3, 4);
graph.addEdge(4, 1);
graph.addEdge(2, 3);
System.out.println(graph);
}

}

class AdjacencyMatrixGraph {
private int _numberOfVertices;
private int _numberOfEdges;
private int[][] _adjacency;

static final int EDGE_EXIST = 1;
static final int EDGE_NONE = 0;

public AdjacencyMatrixGraph(int givenNumberOfVertices) {
this.setNumberOfVertices(givenNumberOfVertices);
this.setNumberOfEdges(0);
this.setAdjacency(new int[givenNumberOfVertices][givenNumberOfVertices]);
for (int i = 0; i < givenNumberOfVertices; i++) {
for (int j = 0; j < givenNumberOfVertices; j++) {
this.adjacency()[i][j] = AdjacencyMatrixGraph.EDGE_NONE;
}
}
}

private void setNumberOfVertices(int newNumberOfVertices) {
this._numberOfVertices = newNumberOfVertices;
}

public int numberOfVertices() {
return this._numberOfVertices;
}

private void setNumberOfEdges(int newNumberOfEdges) {
this._numberOfEdges = newNumberOfEdges;
}

public int numberOfEdges() {
return this._numberOfEdges;
}

private void setAdjacency(int[][] newAdjacency) {
this._adjacency = newAdjacency;
}

private int[][] adjacency() {
return this._adjacency;
}

private boolean adjacencyOfEdgeDoesExist(int from, int to) {
return (this.adjacency()[from][to] != AdjacencyMatrixGraph.EDGE_NONE);
}

public boolean vertexDoesExist(int aVertex) {
if (aVertex >= 0 && aVertex < this.numberOfVertices()) {
return true;
} else {
return false;
}
}

public boolean edgeDoesExist(int from, int to) {
if (this.vertexDoesExist(from) && this.vertexDoesExist(to)) {
return (this.adjacencyOfEdgeDoesExist(from, to));
}

return false;
}

/**
* This method adds an edge to the graph between two specified
* vertices
*
* @param from the data of the vertex the edge is from
* @param to the data of the vertex the edge is going to
* @return returns true if the edge did not exist, return false if it already did
*/
public boolean addEdge(int from, int to) {
if (this.vertexDoesExist(from) && this.vertexDoesExist(to)) {
if (!this.adjacencyOfEdgeDoesExist(from, to)) {
this.adjacency()[from][to] = AdjacencyMatrixGraph.EDGE_EXIST;
this.adjacency()[to][from] = AdjacencyMatrixGraph.EDGE_EXIST;
this.setNumberOfEdges(this.numberOfEdges() + 1);
return true;
}
}

return false;
}

/**
* this method removes an edge from the graph between two specified
* vertices
*
* @param from the data of the vertex the edge is from
* @param to the data of the vertex the edge is going to
* @return returns false if the edge doesn’t exist, returns true if the edge exists and is removed
*/
public boolean removeEdge(int from, int to) {
if(!this.vertexDoesExist(from) || !this.vertexDoesExist(to)) {
if (this.adjacencyOfEdgeDoesExist(from, to)) {
this.adjacency()[from][to] = AdjacencyMatrixGraph.EDGE_NONE;
this.adjacency()[to][from] = AdjacencyMatrixGraph.EDGE_NONE;
this.setNumberOfEdges(this.numberOfEdges() – 1);
return true;
}
}
return false;
}

/**
* this gives a list of vertices in the graph and their adjacencies
*
* @return returns a string describing this graph
*/
public String toString() {
String s = new String();
s = ” “;
for (int i = 0; i < this.numberOfVertices(); i++) {
s = s + String.valueOf(i) + ” “;
}
s = s + ” \n”;

for (int i = 0; i < this.numberOfVertices(); i++) {
s = s + String.valueOf(i) + ” : “;
for (int j = 0; j < this.numberOfVertices(); j++) {
s = s + String.valueOf(this._adjacency[i][j]) + ” “;
}
s = s + “\n”;
}
return s;
}

}

| Leave a comment

HashMap Implementation in Java Easy…

import java.util.ArrayList;
import java.util.LinkedList;

public class HashMap<K,V> {
public class hmnodes{ //HashMap nodes
K key;
V value;
}

private int size=0; //size of hashmap
private LinkedList<hmnodes> buckets[]; //array of addresses of list

public HashMap(){
buckets=new LinkedList[4]; //initially create bucket of any size
for(int i=0;i<4;i++)
buckets[i]=new LinkedList<>();
}

public void put(K key,V value) throws Exception{
int bi=bucketIndex(key); //find the index,the new key will be inserted in linklist at that index
int fountAt=find(bi,key); //check if key already exists or not
if(fountAt==-1){
hmnodes temp=new hmnodes(); //if doesn’t exist create new node and insert
temp.key=key;
temp.value=value;
buckets[bi].addLast(temp);
this.size++;
}else{
buckets[bi].get(fountAt).value=value;//if already exist modify the value
}

double lambda = (this.size*1.0)/this.buckets.length;
if(lambda>2.0){
rehash(); //rehashing function which will increase the size of bucket as soon as lambda exceeds 2.0
}

return;
}

public V get(K key) throws Exception{
int bi=bucketIndex(key);
int fountAt=find(bi,key);
if(fountAt==-1){
return null;
}else{
return buckets[bi].get(fountAt).value;
}
}

public V remove(K key) throws Exception{
int bi=bucketIndex(key);
int fountAt=find(bi,key);
if(fountAt==-1){
return null;
}else{
this.size–;
return buckets[bi].remove(fountAt).value;
}
}

public boolean containskey(K key) throws Exception{
int bi=bucketIndex(key);
int fountAt=find(bi,key);
if(fountAt==-1){
return false;
}else{
return true;
}
}

public int size(){
return this.size;
}

public boolean isempty(){
return this.size==0;
}

public ArrayList<K> keyset() throws Exception{
ArrayList<K> arr=new ArrayList<>();
for(int i=0;i<buckets.length;i++){
for(int j=0;j<buckets[i].size();j++){
arr.add(buckets[i].get(j).key);
}
}
return arr;
}

public ArrayList<V> valueset() throws Exception{
ArrayList<V> arr=new ArrayList<>();
for(int i=0;i<buckets.length;i++){
for(int j=0;j<buckets[i].size();j++){
arr.add(buckets[i].get(j).value);
}
}
return arr;
}

public void display() throws Exception{
for(int i=0;i<buckets.length;i++){
System.out.print(“Bucket: “+i+” “);
for(int j=0;j<buckets[i].size();j++){
hmnodes temp=buckets[i].get(j);
System.out.print(“[“+temp.key+”->”+temp.value+”]”);
}
System.out.println();
}
}

public int find(int bi,K key) throws Exception{
for(int i=0;i<buckets[bi].size();i++){
if(key.equals(buckets[bi].get(i).key))
return i;
}
return -1;
}

public int bucketIndex(K key) throws Exception{
int bi=key.hashCode();
return Math.abs(bi%buckets.length);
}

private void rehash() throws Exception{
LinkedList<hmnodes> ob[]= buckets;
buckets=new LinkedList[ob.length*2];
for(int i=0;i<ob.length*2;i++)
buckets[i]=new LinkedList<>();

size = 0;
for(int i=0;i<ob.length;i++){
for(int j=0;j<ob[i].size();j++){
put(ob[i].get(j).key,ob[i].get(j).value);
}
}

}
}

| Leave a comment

Unzip Utility in Java

public class UnzipUtility
{
/* Automaticaly UnCompress Tar files
* @author Ashoka BM
*
*/

public static List unTar(File tarFile, File directory) throws IOException {
List<String> result = new ArrayList<String>();
InputStream inputStream = new FileInputStream(tarFile);
TarArchiveInputStream in = new TarArchiveInputStream(inputStream);
TarArchiveEntry entry = in.getNextTarEntry();
while (entry != null) {
if (entry.isDirectory()) {
entry = in.getNextTarEntry();
continue;
}
File curfile = new File(directory, entry.getName());
File parent = curfile.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
OutputStream out = new FileOutputStream(curfile);
IOUtils.copy(in, out);
out.close();
result.add(entry.getName());
entry = in.getNextTarEntry();
}
in.close();
return result;
}

}

| Leave a comment