Saturday, 23 November 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, 27 September 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, 13 September 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, 11 September 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, 8 September 2013

DROP BOX

https://www.dropbox.com


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

Friday, 6 September 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...



Wednesday, 4 September 2013

Simple steps to Use Bootstrap for UI designing



                                                          BOOTSTRAP


what is Bootstrap?

Bootstrap is a free collection of tools for creating websites and web applications. It contains HTML and CSS-based design templates for typography, forms, buttons, navigation and other interface components, as well as optional JavaScript extensions.


Bootstrap has relatively incomplete support for HTML5 and CSS 3, but it is compatible with all major browsers. Basic information of compatibility of websites or applications is available for all devices and browsers. There is a concept of partial compatibility that makes the basic information of a website available for all devices and browsers. For example, the properties introduced in CSS3 for rounded corners, gradients and shadows are used by Bootstrap despite lack of support by older web browsers. These extend the functionality of the toolkit, but are not required for its use.
Since version 2.0 it also supports responsive design. This means the layout of web pages adjusts dynamically, taking into account the characteristics of the device used (PC, tablet, mobile phone).



Developer(s) Twitter
Initial release August 2011; 2 years ago
Stable release 3.0.0 / August 19, 2013;

Website: getbootstrap.com


How to use Bootstrap?

1. Go to the below link


  http://getbootstrap.com/

2. Download the Zip File.

3. Extract it we can see 3 folders:



     bootstrap/
  ├── css/
  │   ├── bootstrap.css
  │   ├── bootstrap.min.css
  ├── js/
  │   ├── bootstrap.js
  │   ├── bootstrap.min.js
  └── img/
      ├── glyphicons-halflings.png
      └── glyphicons-halflings-white.png
 


4.Extract them and include them in home Directory of your project.


5.Then include below specified links in the header section of your page.

    <head>

        <link rel="stylesheet" href="css/bootstrap.css"  type="text/css"/>
        <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
        <script src="js/bootstrap.js"></script>
    </head>


6. Now it is ready to make attractive with Bootsrap.



How does it work?


  Here I designed the html Page with bootstrap.

  let's see how?

  <!DOCTYPE html>
  <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
        <link rel="stylesheet" href="css/bootstrap.css"  type="text/css"/>
        <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
        <script src="js/bootstrap.js"></script>
    </head>
 
    <body>
        <input type="button" value="Accept"/>
        <input type="button" value="Reject" class="btn btn-danger"/>
    </body>
  </html>



OUTPUT:







 Here we can see the difference between normal Button and Bootstrap applied Button.

 Like this we can apply validations,toggle,forms,buttons.

Monday, 2 September 2013

Style hr tag in HTML

Simple to style your hr tag by using the below code



<html>
<head>
<style type="text/css">
        hr.hline_color
 {
              background:#D99;
              height:2px;
       }

</style>

<body><br/><br/>
<hr class="hline_color"/><br/><br/>
<hr class="hline_color"/>
</body>
</html>

Friday, 30 August 2013

Changing Images in html

<!DOCTYPE html>
<html>
<head>
  <title>Demo</title>
</head>
<body onload="startTime();">
<img id="img1" />
<script>
var imgArray = new Array("images/1.png","images/2.png","images/3.png");
var imgCount = 0;
function startTime() {
    if(imgCount == imgArray.length) {
        imgCount = 0;
    }
    document.getElementById("img1").src = imgArray[imgCount];
    imgCount++;
    setTimeout("startTime()", 5000);
}
</script>
</body>
</html>

Tuesday, 27 August 2013

Send mail using Servlet


First of all we need to add activation.jar and mail.jar then write this code in Servlet it works fine change the mail addresses..


import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

@WebServlet(urlPatterns = {"/mails2"})
public class Mails extends HttpServlet {


    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here. You may use following sample code. */
       
            out.println("<html>");
            out.println("<head><link rel=\"icon\" href=\"./images/bank1.ico\"/>");
            out.println("<title>Servlet mails</title>");        
            out.println("</head>");
            out.println("<body>");
             HttpSession ses=request.getSession(false);
       String s="xxxx@xxx.com";//change mail address(to whom)
   
 
                 
  Properties props = new Properties();
  props.put("mail.smtp.host", "smtp.gmail.com");
  props.put("mail.smtp.socketFactory.port", "465");
  props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.port", "465");

  Session session = Session.getDefaultInstance(props,
   new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
     return new PasswordAuthentication("xxxxx@gmail.com","xxxxxx");
//change mail address and password (from whom) accordingly
    }
   });

  try {

   Message message = new MimeMessage(session);
   message.setFrom(new InternetAddress("XXXXX@gmail.com"));
//change mail address (from whom) accordingly
                     
   message.setRecipients(Message.RecipientType.TO,
     InternetAddress.parse(s));
   message.setSubject("Mail Testing");
   message.setText("Hai Testing");
   Transport.send(message);

   System.out.println("Done");
                        } catch (MessagingException e) {
   throw new RuntimeException(e);
  }
            out.println("</body>");
            out.println("</html>");
        } finally {        
            out.close();
        }
     
    }

 
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

 }

Thanks for Visiting......

Any comments or suggestions are accepted... thanks...