Monday, July 30, 2018

spring codes - 1

<< this is a Data Transfer Object class (our DAO will store and fetch object of DTO to and from the Database) >>

package beans;

public class Person 
{
// data members
private String name, city;

// getters and setters
public String getName() {
return name;
}

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

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

}


<< this is a Data Access Object >>

package dao;

import beans.Person;

public interface PersonDao 
{
        // this DAO will store the object of Person inside the database
public abstract void savePerson(Person person);
}


<< this is the implementation class of DAO >>

package dao;

import org.springframework.jdbc.core.JdbcTemplate;

import beans.Person;

public class PersonDaoImpl implements PersonDao {

        // JdbcTempltate to insert | update | delete | fetch object to from the database
private JdbcTemplate tmp;

@Override
public void savePerson(Person person) {
// create a query
String sql = "insert into person values(?,?)";

// create an array of Object class to specify
// the argument for the query
Object[] queryParam = { person.getName(), person.getCity() };

// exceute this query
tmp.update(sql, queryParam);
}

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

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

}

<< the xml file in which we keep the Dependency Injection of beans >>

<?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/dao"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!-- DI for DriverManagerDataSource -->
<bean name="jt" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dm"/>
</bean>
<!-- DI for the DAO -->
<bean name="objDao" class="dao.PersonDaoImpl">
<property name="tmp" ref="jt"/>
</bean>
</beans>


<< this is a test application >>


package test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import beans.Person;
import dao.PersonDao;

public class Test01 
{
public static void main(String[] args) 
{
// start container
ClassPathXmlApplicationContext ctx = new 
ClassPathXmlApplicationContext("sao.xml");
// create object of Person
Person p = new Person();
        
        // provide data for person using setters
  p.setName("Nishant");
p.setCity("Mandi Dhanora");
// fetch the object of DAO from the container
PersonDao dao = (PersonDao) ctx.getBean("objDao");
// save the object of person inside database using
// dao
dao.savePerson(p);

        System.out.println("Object saved inside database");
}
}

Thursday, July 26, 2018

Quick sort implementation in Java

This code is implemented and provoded by 'Abdul Samad' from A.K.G. College, Ghaziabad, UP, India.

The Quick sort algorithm is one of the best sorting algorithm. It is based on Divide and Conquer approach. In Worst case it has complexity of O(n2).
In this algorithm we are selecting the last element of array as a pivot. The Element from which we are going to divide the array.      

Note: Please save this clas inside QuickSort.java file

public class QuickSort    
{
// method to sort the elements of the array with respect to pivot
static int quickSort(int[] array, int start, int end)
{
 // Considering the last element as pivot
int pivot = array[end];   
int i = start - 1;
int temp;

//This loop will move all the smaller elements of the array with respect to pivot towards the left hand side and all the bigger elements towards the right hand side respectively the pivot
for (int j = start; j < end + 1; ++j)
{
//if the element at jth position is smaller or equal to pivot we swap it with
//the element at i+1 position(because at this position the element is always bigger than pivot)
if (array[j] <= pivot)
{
i++;
temp = array[j];
array[j] = array[i];
array[i] = temp;
}
}
   //returning the index of the pivot.
return i; 
}
// This method will call the quickSort() method each time for sorting the array using different pivot elements

// It will also recursively call itself until a base criteria is meet.
static void callQuickSort(int[] array, int start, int end)
{
//base criteria condition or recursive condition
if (start < end) 
{
//getting the index of the pivot element in the array after the sorting has occcured with respect to that pivot.
int pivotIndex = quickSort(array, start, end);   
//Recursive calls->
//Recursive call for sorting array elements to the left of pivot.
callQuickSort(array, start, pivotIndex - 1);
//Recursive call for sorting array elements to the right of pivot.
callQuickSort(array, pivotIndex + 1, end);
}
}

//main method for calling the above defined static methods to sort array
public static void main(String[] args)
{
//Defining an array.
int[] array = {10,1,20,2,30,3,1};

//Calling the callQuickSort() method to sort the above array.
QuickSort.callQuickSort(array, 0, array.length - 1);

//Loop to display the array
for (int i = 0; i < array.length; i++)
{
System.out.print(array[i]+"\t");
}

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

Output is:

1 1 2 3 10 20 30

Sunday, July 22, 2018

Very useful and Mind blowing API

Lets get some knowledge about 'InetAddress'

1. It is a pre-defined-class in java.net package

2. It is mandatory to import java.net package to use this class


3. This class is used to denote an IP address, also it is used to translate string into IP address and vice versa


4. Object of InetAddress stores IP address along with machine name 



How to get object of InetAddress class to denote IP address of my machine (my machine bole toh localhost) 

>> InetAddress referenceVariable = InetAddress.getLocalHost()


How to get object of InetAddress class to denote IP address of any machine which is connected to a network


>> InetAddress referenceVariable = InetAddress.getByName("here we can pass the hostname or IP address of any machine")


Note: We can't create object of  InetAddress class using constructor, because its constructor is private

Methods of InetAddress class ==>>


1. public String getHostName() <<== this method is used to fetch the name of machine

denoted by InetAddress

2. public String getHostAddress() <<== this method is used to fetch the IP address of machine denoted by InetAddress


--- Here are some codes to show the the functionality of InetAddress class ---

<< save this clas inside InetAddressDemoOne .java file >>

import java.net.InetAddress;

public class InetAddressDemoOne 
{
public static void main(String[] args) 
{
try 
{
// get the object of InetAddress
InetAddress ref = InetAddress.getLocalHost();

// get the name of machine
String host = ref.getHostName();
System.out.println("Hostname is "+host);

// get the IP address of machine
String ip = ref.getHostAddress();
System.out.println("Ip address is "+ip);

catch (Exception e) 
{
System.out.println("Runtime error in code "+e);
}
}

}

Output of code is:
Hostname is admin-PC

Ip address is 192.168.0.3


<< save this clas inside InetAddressDemoTwo .java file >>

import java.net.InetAddress;
import java.util.Scanner;

public class InetAddressDemoTwo 
{
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("Input machine name or ip address:");
String text = sc.nextLine();

// get the object of InetAddress to denote any machine
// it will be done using getByName() method
// note: make sure the machine is connected on a network 
// note: if the machine is not connected to network
// this method will return localhost or 127.0.0.1 
// (bole toh this computer)
InetAddress ref = InetAddress.getByName(text);

// get the name of machine
String host = ref.getHostName();
System.out.println("Hostname is "+host);

// get the IP address of machine
String ip = ref.getHostAddress();
System.out.println("Ip address is "+ip);

catch (Exception e) 
{
System.out.println("Runtime error in code "+e);
}
}

}

Output of code is:
Input machine name or ip address:<please provide name of machine>
Hostname is localhost
Ip address is 127.0.0.1

Saturday, July 21, 2018

How to fetch values of check boxes from JSP

Please follow given guidelines before using these codes

1. Create two jsps inside Web Content folder (in your web-application). Names of jsp must be index.jsp and checkbox_demo.jsp

Note: In order to fetch the data of check boxes we need to use getParameterValues() method (This method belongs to HttpServletRequest interface). This methods takes name of check-boxes and returns an array of string (which is having values of check boxes).
We can use this method inside scriptlet tag in a JSP.

example >> String[] array = request.getParameterValues("name of check box");

<< code for index.jsp starts here >>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Home Page</title>
</head>
<body>
<fieldset>
<legend>Demo For Check boxes</legend>
<form action="checkbox_demo.jsp" method="post">
Area of Interest<br>
Java<input type="checkbox" name="choices" value="Java">
DBMS<input type="checkbox" name="choices" value="DBMS">
OS<input type="checkbox" name="choices" value="OS">
Testing<input type="checkbox" name="choices" value="Testing"><br>
<input type="submit" value="Test It">
</form>
</fieldset>
</body>
</html>

<< code for index.jsp ends here >>

<< code for checkbox_demo.jsp starts here >>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>checkbox_demo</title>
</head>
<body>
<center>
<%
// fetch the values associated with check boxes 
// using getParameterValues() method
// this method returns an array of string which stores
// the values of check boxes 
// note: if no check box is selected, this method will return null
// store array given by getParameterValues() method
String[] values = request.getParameterValues("choices");

// check if array has null
if(values == null)
{
out.println("<p>No selection found</p>");
}
else // if array has some values
{
// show values of array using for loop
out.println("<h3>you selected</h3>");
out.println("<ul>");
for(int i = 0; i < values.length; i++)
{
out.println("<li>");
out.println(values[i]);
out.println("</li>");
}
out.println("</ul>");
}
%>
</center>
</body>
</html>

<< code for checkbox_demo.jsp ends here >>

Output:






Friday, July 20, 2018

Project Admin Module

Please follow given guidelines before using this code

Note: Using these codes the admin can create a SUBJECT and later on admin can add a QUESTION in the subject (as per the admin need)

A. Create a database in MySQL server 

>> create database admin;

B. Create a Dynamic Web Project in Eclipse IDE and following  some jsp files inside the Web Content folder. 
Names of jsp must be following
1. admin.jsp
2. add_subject.jsp
3. add_subject_handler.jsp
4. add_questions.jsp
5. add_question_handler.jsp

C. Copy and paste mysqlconnector.jar inside lib folder (lib is inside WEB-INF folder)

<< code for admin.jsp starts >>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<ul>
<li><a href="add_subject.jsp">To add a subject click here</a></li>
<li><a href="add_questions.jsp">To add a question click here</a></li>
</ul>
</body>

</html>
<< code for admin.jsp ends >>

<< code for add_subject.jsp starts >>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<fieldset>
<legend>Add-Subject</legend>
<form action="add_subject_handler.jsp" method="post">
Input the title for subject<br>
<input type="text" name="subject" required><br>
<input type="submit" value="add-subject">
</form>
</fieldset>
</body>

</html>




<< code for add_subject.jsp ends >>




<< code for add_subject_handler.jsp starts >>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
   
<%@ page import="java.sql.*" %>   
    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String subject = request.getParameter("subject");

Class.forName("com.mysql.jdbc.Driver");

Connection co = DriverManager.getConnection
("jdbc:mysql://localhost:3306/admin","root","root");

Statement st = co.createStatement();

String sql = "create table admin."+subject+"(id int,question varchar(255),answer1 varchar(255),"+
"answer2 varchar(255),answer3 varchar(255),answer4 varchar(255),correct varchar(255), primary key(id))";

System.out.println(">>>>"+sql);

int nora = st.executeUpdate(sql);

if(nora >= 0)
{
out.println("<i style='color : blue'>subject has been saved</i>");
out.println("<a href=''>show dashboard</a>");
out.println("<a href='add_questions.jsp'>add a question</a>");
}
%>
</body>

</html>

<< code for add_subject_handler.jsp ends >>

<< code for add_questions.jsp starts >>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    
    <%@ page import="java.sql.*" %>
    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%

Class.forName("com.mysql.jdbc.Driver");

Connection co = DriverManager.getConnection
("jdbc:mysql://localhost:3306/admin","root","root");

Statement st = co.createStatement();
Statement st2 = co.createStatement();

String sql = "show tables in admin";

ResultSet rs = st.executeQuery(sql);
ResultSet rs2 = st2.executeQuery(sql);

int records = 0;

while(rs.next())
{
records++;
}

String[] tables = new String[records];

int i = 0;

while(rs2.next())
{
tables[i] = rs2.getString(1);
i++;
}

co.close();
%>
<fieldset>
<legend>Add-Question</legend>
<form action="add_question_handler.jsp" method="post">

<select name="subject">
<%
for(int index = 0; index < tables.length; index++)
{
%>
<option><%=tables[index]%></option>
<%
}
%>
</select>
<br>

Input a question id<br>
<input type="text" name="id" required><br>

Input a question<br>
<textarea rows="3" cols="40" name="question"></textarea><br>

Input answer one<br>
<textarea rows="3" cols="40" name="ans1"></textarea><br>

Input answer two<br>
<textarea rows="3" cols="40" name="ans2"></textarea><br>

Input answer three<br>
<textarea rows="3" cols="40" name="ans3"></textarea><br>

Input answer four<br>
<textarea rows="3" cols="40" name="ans4"></textarea><br>

Input correct answer<br>
<textarea rows="3" cols="40" name="correct_ans"></textarea><br>

<input type="submit" value="add-a-question">
</form>
</fieldset>
</body>

</html>

<< code for add_questions.jsp ends >>

<< code for add_question_handler.jsp starts >>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    
    <%@ page import="java.sql.*" %>
    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String id = request.getParameter("id");
String subject = request.getParameter("subject"),
ques = request.getParameter("question"),
a1 = request.getParameter("ans1"),
a2 = request.getParameter("ans2"),
a3 = request.getParameter("ans3"),
a4 = request.getParameter("ans4"),
ca = request.getParameter("correct_ans");

Class.forName("com.mysql.jdbc.Driver");

Connection co = DriverManager.getConnection
("jdbc:mysql://localhost:3306/admin","root","root");

Statement st = co.createStatement();

String sql = "insert into admin."+subject+" values('"+id+"','"+ques+"','"+a1+"','"+a2+"','"+a3+"','"+a4+"','"+ca+"')";

int rec = st.executeUpdate(sql);

if(rec > 0)
{
out.println("<i>question added</i>");
out.println("<a href='add_questions.jsp'>add more questions</a>");
}

co.close();

%>

<< code for add_question_handler.jsp ends >>



Wednesday, July 18, 2018

Useful facts of Collection Part One

The ArrayList, Vector, Stack, and LinkedList stores the data in First Come First Server Order (also known as Insertion order) also they do supports duplicate objects

The LinkedHashSet also stores objects in Insertion order, but does not allow duplicate objects

The HashSet stores objects in any order, means No specific order, and it does not allow duplicate objects

The TreeSet stores objects in Sorted order (means in their natural order), and does not allow duplicate objects

The PriorityQueue stores objects on the basis of their priorities (using a MIN HEAP DATA STRUCTURES)

Note: Save this code in SomeCollections.java file 

// import collection API 
// the Collection API is inside java.util package
import java.util.*;

public class SomeCollections 
{
public static void main(String[] args) 
{
// create an fruits of string
String[] fruits = {"dates","cherry","banana","mango","apple","fig"};

// create few collections to store string objects
LinkedList<String> c1 = new LinkedList<String>();
HashSet<String> c2 = new HashSet<String>();
LinkedHashSet<String> c3 = new LinkedHashSet<String>();
TreeSet<String> c4 = new TreeSet<String>();
PriorityQueue<String> c5 = new PriorityQueue<String>();

// fetch data from string fruits using for loop
for (int i = 0; i < fruits.length; i++) 
{
// store the data of i'th element of fruits
// inside the collection
c1.add(fruits[i]);
c2.add(fruits[i]);
c3.add(fruits[i]);
c4.add(fruits[i]);
c5.add(fruits[i]);
}

                // show data of LinkedList
System.out.println("-- LinkedList --");
System.out.println(c1);
System.out.println();

                // show data of HashSet
System.out.println("-- HashSet --");
System.out.println(c2);
System.out.println();

                // show data of LinkedHashSet
System.out.println("-- LinkedHashSet --");
System.out.println(c3);
System.out.println();

                // show data of TreeSet
System.out.println("-- TreeSet --");
System.out.println(c4);
System.out.println();

                // show data of PriorityQueue
System.out.println("-- PriorityQueue --");
System.out.println(c5);
}
}


Output of the code ==>

-- LinkedList --
[dates, cherry, banana, mango, apple, fig]

-- HashSet --
[banana, cherry, apple, fig, dates, mango]

-- LinkedHashSet --
[dates, cherry, banana, mango, apple, fig]

-- TreeSet --
[apple, banana, cherry, dates, fig, mango]

-- PriorityQueue --
[apple, banana, cherry, mango, dates, fig]