Thursday, August 16, 2018

Generate QR Code using JAVA

This mind blowing code is implemented and provided by Meghali Anand from MAIT, College, Ghaziabad.

Using this code we can create a QR Code from the string.
Means using the data of string we can generate a QR Code. This QR Code can be scanned using the scanner available with any smart phone.

Before using this code we need to download three jar files (that keeps the API to implement this code).

Names of jar files and their links are given below

1. qrgen-1.2.jar              to load 'qrgen-1.2.jar' click here
2. zxing-core-1.7.jar    to load 'zxing-core-1.7.jar' click here
3. zxing-j2se-1.7.jar     to load 'zxing-j2se-1.7.jar' click here

After downloading the jar files, please follow given guidelines
1. Create a Java Project in Eclipse IDE
2. Attach jar files using build-path approach
3. Create a TestQR.java file 
4. Copy and paste the code inside TestQR.java file

Note: Please save this code inside TestQR.java file

import java.io.FileOutputStream;
import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;

public class TestQR
{
public static void main(String[] args)
{
try
{
// create a string !!
// note: data of this string will be translated to a QR code
String myString = "Its magic it magic";

// get the object of QRCode !!
// note: from() is a static method of QRCode class that returns
// the object of QRCode using the string
QRCode qrc = QRCode.from(myString);

// specify the type of format in which the QR code will be shown
// note: here i have specified the type JPG
qrc = qrc.to(ImageType.JPG);

// open a file in write mode
// note: to open a file in write mode we are using FileOutputStream class
// the file will be created inside D: drive (we can also change the location of file)
// just change the value of filePath variable
String filePath = "D:\\demo.jpeg";

// now open this file in write mode
FileOutputStream fos = new FileOutputStream(filePath);

// store the data of QR code on the file
// note: which was opened in write mode
qrc.writeTo(fos);

// close the file
fos.close();

System.out.println("File has been created in D: drive...\n"
+ "please go there and check");

}
catch (Exception e)
{
// show the line number and cause of exception
e.printStackTrace();
}

} // end of main method

} // end of class


The QR Code generated by the code is =>>

                                            

Friday, August 10, 2018

Store file inside the database

By using this code we can store a file inside the database.

Note: In order to store a file inside database, we need to follow the given guideline

1. Create a database inside MySQL Server, here i am using files_db as a database name, however you can choose any name

>> create database files_db;

2. Use this database

>> use files_db;

3. Create a table inside this database, here i am using files_table as a table name, however you can choose any name 
note: in this table i am using four (that is 4) columns
column 1: filename, to store file name (for this i am using datatype VARCHAR)
column 2: filesize, to store file size (for this i am using datatype BIGINT)
column 3: filetype, to store file extension (for this i am using datatype VARCHAR)
column 4: filedata, to store the data of file (for this i am using datatype LONGBLOB, BLOB, means Binary Large OBject)

>> create table files_table(filename varchar(255),filesize bigint not null,filetype varchar(255) not null,filedata longblob not null, primary key(filename));

note: in order to store big files like (videos) please change the packet size of MySQL Server database

example:
1. open MySQL Server command prompt and provide username and password
2. On MySQL Server command line use the given command

 
4. Create a file as StoreFileInDB.java and copy and paste the given code 

import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Scanner;

public class StoreFileInDB 
{
public static void main(String[] args) 
{
try
{
// create object of scanner to take input from keyboard
Scanner sc = new Scanner(System.in);

System.out.print("Enter the file path to be stored in database: ");

// here we will take path of file that need to be stored
// inside the database
String filepath = sc.nextLine();

// create object of file class to denote this path
File file = new File(filepath);

// check if path of file exists and path also belongs to 
// a file rather than a directory
if(file.exists() && file.isFile())
{
// get the name of file
String filename = file.getName();

// get the size of file
long filesize = file.length();

// get last index of . (that is dot) in file name
int index = filename.lastIndexOf(".");

// get a substring from the given index plus 1
// using this approach we can extract the extension from the filename 
String ext = filename.substring(index + 1);

// now open a a file in read mode
// means now we can fetch the data from this file
FileInputStream fi = new FileInputStream(filepath);

// load the driver class for database connection
Class.forName("com.mysql.jdbc.Driver");

// get object of connection
Connection co = DriverManager.getConnection
("jdbc:mysql://localhost:3306/files_db","root","root");

// get object of PreparedStatement, to execute
// sql statements
PreparedStatement ps = co.prepareStatement
("insert into files_table values(?,?,?,?)");

// provide values in place of ? mark
// set the file name to be stored inside database
ps.setString(1, filename); 

// set the file size to be stored inside database
ps.setLong(2, filesize);

// set the file extension to be stored inside database
ps.setString(3, ext);

// set the actual data of file to be stored inside database
ps.setBinaryStream(4, fi,(int)filesize);

// execute sql statement
ps.executeUpdate();

// show a message on screen
System.out.println("File has been saved inside the database");

// close the database connection
co.close();
}
else
{
System.out.println("Either file not exits or its is a folder");
}

}
// handle runtime error, generated during the program execution
catch (Exception e) 
{
System.out.println("error "+e);
}

} // end of main method
}   // end of class


Output:
Enter the file path to be stored in database: c:\abc.txt
File has been saved inside the database

Monday, August 6, 2018

DualPivotQuickSort in Java

This code is implemented and provided by Abdul Samad from AKG, college, Ghaziabad, UP, India.

Dual-Pivot Quicksort algorithm was given by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. It offers O(n log(n)) performance and is faster than traditional (one-pivot) Quicksort implementations.
please click on this link =>> click here to know more


//class to perform dual pivot quick sort.
public class DualPivotQuickSort
{
//method to swap elements of the array.
static void swap(int[] a, int i, int j)
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}

//sorting alogorithm implementation.
static void sorting(int[] a, int start, int end)
{
//base criteria or recursive condition. 
if (start < end)
{
int pivot1, pivot2, i, lt, gt, temp;
//To ensure that pivot1 is always smaller than pivot2.
//Pivot1 is always the starting element and pivot2 is always the last element of the array.
if (a[start] > a[end])
swap(a, start, end);

pivot1 = a[start];
pivot2 = a[end];

i = start + 1;
lt = start + 1;
gt = end - 1;

//loop for sorting.
while (i <= gt) 
{
        if (a[i] <= pivot1)
{
swap(a, i, lt);
lt++;
i++;
}
else if (a[i] >= pivot2)
{
swap(a, i, gt);
gt--;
}
else
i++;


swap(a, --lt, start);
swap(a, ++gt, end);

//Recursive calls.
//Recursive call from the starting index to the element preceding pivot1.

sorting(a, start, lt - 1);

//Recursive call from the index of the element following pivot1 to the index of the element //preceding pivot2.
sorting(a, lt + 1, gt - 1);

//Recursive call from the index of the element following pivot2 to the last index.
sorting(a, gt + 1, end);
}

}

public static void main(String[] args) 
{
// create an array that need to be sorted
int[] a = { 5, 4, 3, 2, 1, 19, 18, 17, 0, 0, 0, 13, 0, 99, -78, -98, 99, 5, 6 };

//Displaying original array.
System.out.println("Original Array-");
for (int i = 0; i < a.length; ++i)
{
System.out.print(a[i] + "\t");
System.out.println();
}

//calling sorting method
// a : is the name of array to be sorted
// 0 : is the index from which the sorting  
sorting(a, 0, a.length - 1);

//Displaying sorted array.
System.out.println("Sorted Array-");
for (int i = 0; i < a.length; ++i)
{
System.out.print(a[i] + "\t");
System.out.println();
}

} // end of main method

} // end of class


Output of code =>>

Original Array-
5
4
3
2
1
19
18
17
0
0
0
13
0
99
-78
-98
99
5
6
Sorted Array-
-98
-78
0
0
0
0
1
2
3
4
5
5
6
13
17
18
19
99
99

Friday, August 3, 2018

spring - codes - 3

dao.xml =>>

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>

<!-- di for DriverManagerDataSourceMDS -->
<bean name="dm" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/navadb"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>

<!-- di or JdbcTemplate -->
<bean name="jtemp" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dm"/> 
</bean>

<!-- di for SimpleJdbcInsert -->
<bean name="sji" class="org.springframework.jdbc.core.simple.SimpleJdbcInsert">
<constructor-arg ref="dm"/>
</bean>

<!-- di for implementation of dao -->
<bean name="dao" class="dao.BookDAOImpl">
<property name="tmp" ref="jtemp"/>
<property name="insert" ref="sji"/>
</bean>

</beans>

Book.java =>>

package beans;

public class Book
{
private int id;
private String topic, author;
private float cost;

public int getId()
{
return id;
}

public void setId(int id)
{
this.id = id;
}

public String getTopic()
{
return topic;
}

public void setTopic(String topic)
{
this.topic = topic;
}

public String getAuthor()
{
return author;
}

public void setAuthor(String author)
{
this.author = author;
}

public float getCost()
{
return cost;
}

public void setCost(float cost)
{
this.cost = cost;
}

public Book()
{
}

public Book(int id, String topic, String author, float cost)
{
this.id = id;
this.topic = topic;
this.author = author;
this.cost = cost;
}

}


BookDao.java =>>

package dao;

import java.util.List;

import beans.Book;

public interface BookDAO
{
// this method will fetch a single book from the
// database
public abstract Book findBookById(int id);

// this method will fetch all the books from the
// database
public abstract List<Book> getAllBooks();
// this method will be used to store object of 
// book inside database using simple-jdbc-insert
// class
public abstract void insertBookInDB(Book book);
}


BookDAOImpl.java =>>

package dao;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;

import beans.Book;

public class BookDAOImpl implements BookDAO
{
private JdbcTemplate tmp;

private SimpleJdbcInsert insert;

public JdbcTemplate getTmp()
{
return tmp;
}

public void setTmp(JdbcTemplate tmp)
{
this.tmp = tmp;
}

public SimpleJdbcInsert getInsert()
{
return insert;
}

public void setInsert(SimpleJdbcInsert insert)
{
this.insert = insert;
}

@Override
public Book findBookById(int id)
{
System.out.println("method of dao");
// create sql query
String sql = "SELECT * FROM BOOK WHERE id = ?";

// create query args
Object[] args =
{ id };

// create object of RowMapper
RowMapperImpl rm = new RowMapperImpl();

return tmp.queryForObject(sql, args, rm);
}

@Override
public List<Book> getAllBooks()
{
// create sql query
String sql = "select * from book";

// create object of row-mapper
RowMapperImpl impl = new RowMapperImpl();

//
return tmp.query(sql, impl);
}
@Override
public void insertBookInDB(Book book)
{
insert.setTableName("book");
// create a map to specify the column name
// and their recpective value
Map<String,Object> map = new 
LinkedHashMap<String,Object>();
map.put("id",book.getId());
map.put("topic",book.getTopic());
map.put("author",book.getAuthor());
map.put("cost",book.getCost());
insert.execute(map);
}
}


RowMapperImpl.java =>>

package dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;

import beans.Book;


public class RowMapperImpl implements RowMapper<Book>
{
@Override
public Book mapRow(ResultSet resultSet, int records) 
throws SQLException
{
System.out.println("mapRow()");
System.out.println("Total records are "+records);
// create object of Book (book is a bean)
Book book = new Book();
// fetch data of column from the ResultSet and store
// it inside object of Book using setters
book.setId(resultSet.getInt("id"));
book.setTopic(resultSet.getString("topic"));
book.setAuthor(resultSet.getString("author"));
book.setCost(resultSet.getFloat("cost"));

// return the object of bean to the DAO
return book;
}
}


FetchObject.java =>>

package tests;

import java.util.List;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.EmptyResultDataAccessException;

import beans.Book;
import dao.BookDAOImpl;

public class FetchObject
{
public static void main(String[] args)
{
try
{
ClassPathXmlApplicationContext ctx = new 
ClassPathXmlApplicationContext("dao.xml");
BookDAOImpl dao = (BookDAOImpl) ctx.getBean("dao");

// fetch the list of books from database using
// dao
List<Book> books = dao.getAllBooks();
// 
for(Book book : books)
{
System.out.println(book.getId());
System.out.println(book.getTopic());
System.out.println(book.getAuthor());
System.out.println(book.getCost());
System.out.println();
}
}
catch(Exception e)
{
if(e instanceof EmptyResultDataAccessException)
{
System.out.println("invalid id");
}
}
}
}

Wednesday, August 1, 2018

spring codes - 2

Note:
Before using these codes please follow the given guidelines
1. create a database newdb in MySQL server database

>> create database newdb;

3. create a table book inside newdb database

>> create table book (id int auto_increment,topic varchar(100) not null,author varchar(100) not null,cost float not null,primary key(id));

4. insert some records inside book table

>> insert into book (topic,author,cost) values('c','kanitkar','300');
>> insert into book (topic,author,cost) values('c++','pankaj','400');
>> insert into book (topic,author,cost) values('java','nitin','500');

-----------------------------------------------------

Note: 
This is a Data Transfer Object, Object of this class will be stored and fetched using DAO (Data Access Object, DAO is an approach to store and fetch object to and from the database)

Note ->
1. create a package beans
2. create class Book in beans package


3. copy and paste this code in Book  

<< code of Book.java starts >>

package beans;

public class Book
{
// data members
private int id;
private String topic, author;
private float cost;

// getters and setters public int getId()
{
return id;
}

public void setId(int id)
{
this.id = id;
}

public String getTopic()
{
return topic;
}

public void setTopic(String topic)
{
this.topic = topic;
}

public String getAuthor()
{
return author;
}

public void setAuthor(String author)
{
this.author = author;
}

public float getCost()
{
return cost;
}

public void setCost(float cost)
{
this.cost = cost;
}

// no argument constructor  public Book()
{
}

// parameter  constructor  public Book(int id, String topic, String author, float cost)
{
this.id = id;
this.topic = topic;
this.author = author;
this.cost = cost;
}

}

<< code of Book.java ends >>

Note: 
BookDAO is a Data Access Object (DAO) by which we will fetch and store the object of Book from and to the database.

DAO is just a guideline (means what to do?). The implementation of DAO (the class who implements this interface) will decide how to fetch and store the object.


Note ->
1. create a package dao
2. create interface BookDAO in dao package
3. copy and paste this code in BookDAO

<< code of BookDao.java starts >>

package dao;

import beans.Book;

public interface BookDAO
{
public abstract Book findBookById(int id);
}

<< code of BookDao.java ends >>


Note:
BookDAOImpl is the implementation of DAO. 


Note ->
1. create a package dao
2. create class BookDAOImpl in dao package
3. copy and paste this code in BookDAOImpl



<< code of BookDAOImpl.java starts >>

package dao;

import org.springframework.jdbc.core.JdbcTemplate;

import beans.Book;

public class BookDAOImpl implements BookDAO
{
// object of JdbcTemplate class to execute the sql statements
private JdbcTemplate tmp;

// getter and setter for the JdbcTemplate class
public JdbcTemplate getTmp()
{
return tmp;
}

public void setTmp(JdbcTemplate tmp)
{
this.tmp = tmp;
}

@Override
public Book findBookById(int id)
{
System.out.println("method of dao");
// create sql query
String sql = "SELECT * FROM BOOK WHERE id = ?";
// create query args
Object[] args = {id};
// create object of RowMapper
RowMapperImpl rm = new RowMapperImpl();

// call the method of JdbcTemplte to execute the select query and fetch the object of bean
// (means the object of Book) from the database
return tmp.queryForObject(sql,args,rm);
}
}

<< code of BookDAOImpl.java ends >>

Note:
RowMapperImpl is an implemenatsion of RowMapper interface. It is used to fetch and object from the database and store that inside the object of ResultSet. Then we fetch record from ResultSet and pass it to DAO using the object of bean (here the bean is Book ie. The DTO)


Note ->
1. create class RowMapperImpl in dao package
2. copy and paste this code in RowMapperImpl 

<< code of RowMapperImpl .java starts >>

package dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;

import beans.Book;

public class RowMapperImpl implements RowMapper<Book>
{
@Override
public Book mapRow(ResultSet resultSet, int records) 
throws SQLException
{
System.out.println("mapRow() executes");
System.out.println("Total records are "+records);

// create object of Book (book is a bean)
Book book = new Book();
// fetch data of column from the ResultSet and store
// it inside object of Book using setters
book.setId(resultSet.getInt("id"));
book.setTopic(resultSet.getString("topic"));
book.setAuthor(resultSet.getString("author"));
book.setCost(resultSet.getFloat("cost"));

// return the object of bean to the DAO
return book;
}
}

<< code of RowMapperImpl .java ends >>


Note:
dao.xml is used by the spring container in order to read the mapping for the dependency injection.
container creates object of bean using the mapping available inside this file.

<< code for dao.xml starts >

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<!-- di for DriverManagerDataSource -->
<bean name="dm" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/navadb"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>

<!-- di or JdbcTemplate -->
<bean name="jtemp" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dm"/> 
</bean>
<!-- di for implementation of DAO  -->
<bean name="dao" class="dao.BookDAOImpl">
<property name="tmp" ref="jtemp"/>
</bean>
</beans>

<< code of dao.xml file end>


Note:
In FetchObject.java we will start the spring container and will fetch object of DAO from it. After that we will fetch object of bean class (here the bean is Book) from the database by invoking the method of DAO.


Note ->
1. create a package tests
2. create a class FetchObject in tests package
3. copy and paste this code in FetchObject 



<< code of FetchObject.java starts >>

package tests;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.EmptyResultDataAccessException;

import beans.Book;
import dao.BookDAOImpl;

public class FetchObject
{
public static void main(String[] args)
{
try
{
        // start the spring container using xml file
ClassPathXmlApplicationContext ctx = new 
ClassPathXmlApplicationContext("dao.xml");
        // fetch the object of DAO from the container
BookDAOImpl dao = (BookDAOImpl) ctx.getBean("dao");

        //  variable to store an Book id 
int id = 3;
        // invoke method of DAO to fetch object of Book from the database
Book b = dao.findBookById(id);
        // fetch the data from the object of Book using getters and show it on console
System.out.println(b.getId());
System.out.println(b.getTopic());
System.out.println(b.getAuthor());
System.out.println(b.getCost());
}
         // for invalid Book id the exception will be raised
catch(Exception e)
{
                // check if exception was generated due to empty ResultSet 
if(e instanceof EmptyResultDataAccessException)
{
System.out.println("invalid id");
}
}

} // end of main method
} // end of class



<< code of FetchObject.java ends >>