Saturday, November 23, 2013

JAVA – How To Calculate An Age From A Date Of Birth (DOB)

The following code illustrates how to derive an age from a given DOB.

This example uses the DOB format YYYY-MM-DD.

This can be altered to any format by changing the substrings taken from the original DOB input.


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


String dob = “1990-05-07″;
//TAKE SUBSTRINGS OF THE DOB SO SPLIT OUT YEAR, MONTH AND DAY
//INTO SEPERATE VARIABLES
int yearDOB = Integer.parseInt(dob.substring(0, 4));
int monthDOB = Integer.parseInt(dob.substring(5, 7));
int dayDOB = Integer.parseInt(dob.substring(8, 10));
//CALCULATE THE CURRENT YEAR, MONTH AND DAY
//INTO SEPERATE VARIABLES
DateFormat dateFormat = new SimpleDateFormat(“yyyy”);
java.util.Date date = new java.util.Date();
int thisYear = Integer.parseInt(dateFormat.format(date));
dateFormat = new SimpleDateFormat(“MM”);
date = new java.util.Date();
int thisMonth = Integer.parseInt(dateFormat.format(date));
dateFormat = new SimpleDateFormat(“dd”);
date = new java.util.Date();
int thisDay = Integer.parseInt(dateFormat.format(date));
//CREATE AN AGE VARIABLE TO HOLD THE CALCULATED AGE
//TO START WILL – SET THE AGE EQUEL TO THE CURRENT YEAR MINUS THE YEAR
//OF THE DOB
int age = thisYear – yearDOB;
//IF THE CURRENT MONTH IS LESS THAN THE DOB MONTH
//THEN REDUCE THE DOB BY 1 AS THEY HAVE NOT HAD THEIR
//BIRTHDAY YET THIS YEAR
if(thisMonth < monthDOB){
age = age – 1;
}
//IF THE MONTH IN THE DOB IS EQUEL TO THE CURRENT MONTH
//THEN CHECK THE DAY TO FIND OUT IF THEY HAVE HAD THEIR
//BIRTHDAY YET. IF THE CURRENT DAY IS LESS THAN THE DAY OF THE DOB
//THEN REDUCE THE DOB BY 1 AS THEY HAVE NOT HAD THEIR
//BIRTHDAY YET THIS YEAR
if(thisMonth == monthDOB && thisDay < dayDOB){
age = age – 1;
}
//THE AGE VARIBALE WILL NOW CONTAIN THE CORRECT AGE
//DERIVED FROMTHE GIVEN DOB
System.out.println(age);

Friday, September 27, 2013

RESTORE MYSQL DATABASE WITHOUT USING MYSQL COMMAND PROMPT




<%@page import="java.sql.*"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link rel="icon" href="./images/fav.ico"/>
        <link rel="stylesheet" type="text/css" href="tabcontent.css" />
        <title>Indian WildLife</title>
        <script type="text/javascript" src="tabcontent.js"></script>
    </head>
    <body>
       
    <center>
        <div style="border-radius: 25px; width:800px; height:650px;background:#f0D0D0 "><br/>

<h3>Restore Database</h3>
<%

String database = null;
String username = "root";//Mysql User Name
String password = "root";//Mysql Password
String urlmysql = "jdbc:mysql://localhost:9999";//CHANGE PORT NUMBER


String dbtype = null;
Connection connection = null;
Statement statement = null;
ResultSet rset = null;
int result = -1;

try {
    Class.forName("com.mysql.jdbc.Driver").newInstance();

} catch(ClassNotFoundException e) {
    out.println("Class not found: "+ e.getMessage());
    return;
}
if (request.getParameter("dbtype") != null) { dbtype = request.getParameter("dbtype"); };


try {

    connection = DriverManager.getConnection(urlmysql, username, password);
    statement = connection.createStatement();

    out.println("<b>List of MySQL databases accessible by user " + username + ":</b><br/>");
    rset = statement.executeQuery("SHOW DATABASES");
    while (rset.next())   {
        out.println(rset.getString(1) + "<br/>");
    }
    rset.close();
    statement.close();
    connection.close();
    out.println("<hr>");
  if (request.getParameter("database") != null) {
        database = (String)request.getParameter("database");
        if (request.getParameter("Restore") != null &&
            request.getParameter("Restore").equals("Restore")) {

            String[] executeCmd = new String[]{"mysql", "--user=" + username, "--password=" + password, "-e", "source "+ database + ".sql"};
         
            Process runtimeProcess;
            try {
                runtimeProcess = Runtime.getRuntime().exec(executeCmd);
                int processComplete = runtimeProcess.waitFor();
                if (processComplete == 0) {
                    out.println("Backup restored successfully");
                } else {
                    out.println("Could not restore the backup");
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

  }

%>
<form action="restore.jsp" method="post"><table>
<tr><td align="left">Database name to restore: <input type="text" name="database" size="20"></td></tr>
<tr><td><input type="radio" name="dbtype" value="mysql" checked="checked">MySQL<br>
</tr>
<tr><td align="left">
<input type="submit" name="Restore" value="Restore">
<input type="reset" name="Reset" value="Reset"></td></tr>
</table></form>
   
<%
} catch (SQLException e) {
    out.println(e.getMessage());
} finally {
    try {
        if(connection != null) connection.close();
    } catch(SQLException e) {}
}
%>

        </div>
    </center>
     
    </body>
</html>

BACKUP MYSQL DATABASE WITHOUT USING MYSQL COMMAND PROMPT



<%@page import="java.sql.*"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
         <title>BACKUP DATABASE</title>
        <script type="text/javascript" src="tabcontent.js"></script>
    </head>
    <body>
       
    <center>
        <div style="border-radius: 25px; width:800px; height:650px;background:#f0D0D0 ">
<h3>BackUp Database</h3>
<%
String database = null;
String username = "root";
String password = "root";
String urlmysql = "jdbc:mysql://localhost:9999";  //CHANGE ACCORDINGLY


String dbtype = null;
Connection connection = null;
Statement statement = null;
ResultSet rset = null;
int result = -1;

try {
    Class.forName("com.mysql.jdbc.Driver").newInstance();

} catch(ClassNotFoundException e) {
    out.println("Class not found: "+ e.getMessage());
    return;
}

if (request.getParameter("dbtype") != null) { dbtype = request.getParameter("dbtype"); };

try {

    connection = DriverManager.getConnection(urlmysql, username, password);
    statement = connection.createStatement();


   //To Display List of  Databases Existed in the Mysql Database

    out.println("<b>List of MySQL databases accessible by user " + username + ":</b><br/>");
    rset = statement.executeQuery("SHOW DATABASES");
    while (rset.next())   {
        out.println(rset.getString(1) + "<br/>");
    }
    rset.close();
    statement.close();
    connection.close();
    out.println("<hr>");


    if (request.getParameter("database") != null) {
        database = (String)request.getParameter("database");
        if (request.getParameter("Backup") != null &&
            request.getParameter("Backup").equals("Backup")) {

            String executeCmd = "mysqldump -u " + username + " -p" + password + " --add-drop-database -B " + database + " -r " + database + ".sql";
         

            Process runtimeProcess;
            try {
                 runtimeProcess = Runtime.getRuntime().exec(executeCmd);
                int processComplete = runtimeProcess.waitFor();
                 if (processComplete == 0) {
                    out.println("Backup created successfully");
                     } else {
                    out.println("Could not create the backup");
                 }
              } catch (Exception ex) {
                ex.printStackTrace();
            }
         }
    }
 

%>
<form action="backup.jsp" method="post"><table>
<tr><td align="left">Database name to backup : <input type="text" name="database" size="20"></td></tr>
<tr><td><input type="radio" name="dbtype" value="mysql" checked="checked">MySQL<br>
</tr>
<tr><td align="left"><input type="submit" name="Backup" value="Backup">
<input type="reset" name="Reset" value="Reset"></td></tr>
</table>
</form>
<%
} catch (SQLException e) {
    out.println(e.getMessage());
} finally {
    try {
        if(connection != null) connection.close();
    } catch(SQLException e) {}
}
%>

        </div>
    </center>
     
    </body>
</html>



Friday, September 13, 2013

Just for Fun



Hai guys type these words in google search and see how does it works. 


1. do a (makes the page to rotate in clock-wise direction)



2. zerg rush (Finally makes the entire page with only two G letters)






3. google garvity (makes the page collapsed and we can drag whatever part in the page)


Click on I'm Feeling Lucky After typing google gravity








Wednesday, September 11, 2013

UPLOAD VIDEO USING JSP

Here is the code to upload videos using java.There are 2 files
1. index.jsp
2. upload.jsp

Here i have considered the mysql database.
If you also use mysql then consider the datatype as longblob.so that we can insert max sized video

After this set max_allowed_packet which is explained below.so that we can upload video with maximum size.


mysql> SHOW GLOBAL VARIABLES LIKE 'max_allowed_packet';
+--------------------+---------+
| Variable_name      | Value   |
+--------------------+---------+
| max_allowed_packet | 8388608 |
+--------------------+---------+
1 row in set (0.00 sec)

mysql> SHOW SESSION VARIABLES LIKE 'max_allowed_packet';
+--------------------+---------+
| Variable_name      | Value   |
+--------------------+---------+
| max_allowed_packet | 8388608 |
+--------------------+---------+
1 row in set (0.00 sec)

mysql> SET GLOBAL max_allowed_packet = 40000000;
Query OK, 0 rows affected (0.00 sec)

mysql> SHOW GLOBAL VARIABLES LIKE 'max_allowed_packet';
+--------------------+----------+
| Variable_name      | Value    |
+--------------------+----------+
| max_allowed_packet | 39999488 |
+--------------------+----------+
1 row in set (0.00 sec)

mysql> SHOW SESSION VARIABLES LIKE 'max_allowed_packet';
+--------------------+---------+
| Variable_name      | Value   |
+--------------------+---------+
| max_allowed_packet | 8388608 |
+--------------------+---------+
1 row in set (0.00 sec)

mysql> SET SESSION max_allowed_packet = 20000000;
Query OK, 0 rows affected (0.02 sec)

mysql> SHOW SESSION VARIABLES LIKE 'max_allowed_packet';
+--------------------+----------+
| Variable_name      | Value    |
+--------------------+----------+
| max_allowed_packet | 19999744 |
+--------------------+----------+

1 row in set (0.00 sec)



index.jsp:


<%@ page language="java" %><Html>
<HEAD><TITLE>Display file upload form to the user</TITLE></HEAD>
<BODY>
<FORM ENCTYPE="multipart/form-data" ACTION="upload.jsp" METHOD=POST>
<br><br><br>
<center><table border="2" >
<tr><center><td colspan="2"><p align="center"><B>UPLOAD THE FILE</B><center></td></tr>
<tr><td><b>Choose the file To Upload:</b>
</td>
<td><INPUT NAME="file" TYPE="file"></td></tr>
<tr><td colspan="2">
<p align="right"><INPUT TYPE="submit" VALUE="Send File" ></p></td></tr>
<table>
</center>
</FORM>
</BODY>
</HTML>


upload.jsp




<%@ page import="java.io.*" %><%@ page import="java.sql.*" %>
<%
String contentType = request.getContentType();
if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
DataInputStream in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while (totalBytesRead < formDataLength) {
byteRead = in.read(dataBytes, totalBytesRead,formDataLength);
totalBytesRead += byteRead;
}
String file = new String(dataBytes);
String saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
out.println(saveFile);
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex + 1,contentType.length());
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
FileOutputStream fileOut = new FileOutputStream(saveFile);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();

%><Br><table border="2"><tr><td><b>You have successfully upload the file by the name of:</b>
<% out.println(saveFile);%></td></tr></table>
<%
Connection connection = null;
String connectionURL = "jdbc:mysql://localhost:9999/wild_life";
ResultSet rs = null;
PreparedStatement psmnt = null;
FileInputStream fis;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "root");
//change username password
File f = new File(saveFile);
psmnt = connection.prepareStatement("insert into file(file_data,path) values(?,?)");
fis = new FileInputStream(f);
psmnt.setBinaryStream(1, (InputStream)fis, (int)(f.length()));
psmnt.setString(2,saveFile);
int s = psmnt.executeUpdate();
if(s>0) {
System.out.println("Uploaded successfully !");
}
else {
System.out.println("unsucessfull to upload file.");
}
}
catch(Exception e){e.printStackTrace();}
}
%>





Sunday, September 8, 2013

DROP BOX

https://www.dropbox.com


USE THESE DROP BOX TO SHARE DOCUMENTS,PHOTOS UPTO 200MB FOR FREE

Friday, September 6, 2013

How to copy Mysql database from one Computer to another / backup database using mysqldump



1.   Creating a dumpfile from database/ Taking      backup of MySQL database:
-     Open command prompt.
-     Execute following commands to change directory
>c:  “press enter”
>cd  program files/MySQL/MySQL Server 5.1/ bin “press enter”
>mysqldump -u root  -p databse_name > database_name.sql 
   “press enter”

  Enter password: password of MySQL

Copy sql file and paste it in PC where you want to transfer database.

         2. Dumping sql file into database:-
          - Open MySQL  command line client command prompt.
          - Execute following command to create database.
                 >create database database_name;  “press enter”
   Database name is must as that of your database _name.
 Copy that sql file into location “c:/program files/MySQL/MySQL Server 5.1/bin”

          - Now open command prompt and execute following commands.
                >C: “press enter”
                >cd program files/MySQL/MySQL Server5.1/bin “press enter”
                >mysql –u root –p database_name < database_name.sql    “press enter”



           Your database is created on PC.
           Now in MySQL command prompt check your database.  

Guess You Got the Answer...