How to Create Online Dictionary using JSP and Servlet with Jquery

Our Project Structure::


Words.java : this Class is used to stored each words retrieved from the database.
discServlet.java : this is used to handle all the servlet request and responses
DBConnection.java : this is used to connect to sexy database called MySQL
db.propertise : this guy called security ;) contains the credential for the database as well all the information required to connect DB

dict.html: this is beautiful lady which is only thing that is visible in the web.  <3 <3

Now lets start to dive in to the ocean of love ( which means only for real programmers others please ignore this word called love )

Step 1 : Creating The database connection
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */package com.disc.jdbc;import com.mysql.jdbc.Connection;import java.io.IOException;import java.io.InputStream;import java.sql.DriverManager;import java.sql.SQLException;import java.util.Properties;
/** * * @author yubraj */public class DBConnection {
    
    public static Connection connection = null;        public static void main() throws IOException, SQLException, ClassNotFoundException{
     connection = getConnection();    }
    

    
    public static Connection getConnection() throws IOException, SQLException, ClassNotFoundException{
        if(connection!=null) return connection;        else{
                Properties prop = new Properties();                InputStream input = DBConnection.class.getClassLoader().getResourceAsStream("/com/disc/resourses/db.properties");                prop.load(input);                String driver = prop.getProperty("driver");                String url = prop.getProperty("url");                String user = prop.getProperty("user");                String password = prop.getProperty("password");                Class.forName(driver);                connection = (Connection) DriverManager.getConnection(url, user, password);                System.out.println("Connection to MySQL is Establised...");                return connection;        }
    }
    
    public static void close() throws SQLException {
        DBConnection.connection.close();
    }
    
}

also db.properties
driver= com.mysql.jdbc.Driverurl= jdbc:mysql://localhost:3306/entriesuser= rootpassword=xxx


Step 2 : Writing our Mr. Tough servlet

package com.dict.servlets;
import com.disc.jdbc.DBConnection;import com.google.gson.Gson;import com.mysql.jdbc.Connection;import java.io.IOException;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.logging.Level;import java.util.logging.Logger;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.ws.rs.core.MediaType;
/** * * @author yubraj */@WebServlet(name = "discServlet", urlPatterns = {"/discServlet"})
public class discServlet extends HttpServlet {
    
    @Override    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {    
        
         System.out.println("inside the servlet");         ArrayList<Words> map = new ArrayList<Words>();         String searchedWord = request.getParameter("word");         System.out.println("Searched Keyword: "+searchedWord);                try {
            Connection conn = DBConnection.getConnection();            map = getData(conn, request, response, searchedWord);            write(response, map);                                } catch (SQLException | ClassNotFoundException ex) {
            Logger.getLogger(discServlet.class.getName()).log(Level.SEVERE, null, ex);        } catch (Exception ex) {
            Logger.getLogger(discServlet.class.getName()).log(Level.SEVERE, null, ex);        }
    }

    private void write(HttpServletResponse response, ArrayList<Words> map) throws IOException{
        response.setContentType(MediaType.APPLICATION_JSON);        response.setCharacterEncoding("UTF-8");        response.getWriter().write(new Gson().toJson(map));    }
    
    
    
    @Override    public String getServletInfo() {
        return "Short description";    }// </editor-fold>
    private ArrayList getData(Connection conn, HttpServletRequest request, HttpServletResponse response, String searchedWord) throws SQLException, Exception {        
        ArrayList messageData = new ArrayList();                String selectSQL = "SELECT * FROM entries WHERE word = ? order by wordtype";        PreparedStatement preparedStatement = conn.prepareStatement(selectSQL);        preparedStatement.setString(1, searchedWord);        ResultSet rs = preparedStatement.executeQuery();        while (rs.next()) {
            Words words = new Words();            words.setWord(rs.getString("word"));            words.setWordtype(rs.getString("wordtype"));            words.setDefination(rs.getString("definition"));            messageData.add(words);        }
        return messageData;                    }
   

}

Step 3 : Creating our Beautiful lady i.e. View

<!DOCTYPE html>
<html>
    <head>
        <title>Online Dictionary</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="css/style.css" rel="stylesheet" type="text/css"/>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
        <script src="js/dict.js" type="text/javascript"></script>

    </head>
    <body>
        <div class="container">
           <section>
                <h2>Online Dictionery</h2>
                <form id="dictForm">
                <ul class="input-list mystyle clearfix">
                  <li >
                     <input type="text" name="word" placeholder=":Enter your word">
                  </li>
                  <li>
                    <input id="search" type="submit" value="Search">
                  </li>
                </ul>
                    </form>
              </section>
                <div id='loadingDiv'>
                        Please wait... 
                 </div> 
            
            <div id="result">
           
            </div>
        </div>
    </body>
</html>



Step 4 : Make over to our Beautiful Lady i.e style.css

/*
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
*/
/* 
    Created on : Mar 15, 2016, 11:47:44 AM
    Author     : yubraj
*/

body{
       background-color: #dc2850;
    color: #505050;
    font-family: "Open Sans", sans-serif;
    font-weight: 400;
    font-size: 14px;
    line-height: 1.8;
}

section , .result{
  margin-bottom: 10px;
  padding: 30px;
  background-color: #efefef;
}

.result{
    margin-bottom: 5px;
}

.word{
    font-weight: bold;
}

.grammer{
    font-style: italic;
}

#loadingDiv{
       background-color: #EFEFEF;
        padding: 10px;
        margin-bottom: 10px;
        text-align: center;
        font-size: 20px;
}

/* headings */
h2 {
     margin-bottom: 0px;
    padding: 5px;
    font-size: 2em;
}

/* form elements */
label {
  display: block;
}

input[type="text"], input[type="submit"] {
  display: block;
  margin: 0;
  width: 100%;
  font-family: "Open Sans", sans-serif;
  font-size: 18px;
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  -webkit-box-shadow: none;
  -moz-box-shadow: none;
  box-shadow: none;
  -webkit-border-radius: none;
  -moz-border-radius: none;
  -ms-border-radius: none;
  -o-border-radius: none;
  border-radius: none;
}


input[type="text"]:focus {
  outline: none;
}

/* lists */
ul.input-list {
  list-style: none;
  margin: 0 -10px;
  padding: 0;
}
ul.input-list li {
  display: block;
  padding: 0 10px;
  width: 46%;
  float: left;
  margin:5px;
}




/* ============================================================
  STYLE 1
============================================================ */
.mystyle input[type="text"], input[type="submit"]  {
  padding: 10px;
  border: solid 1px gainsboro;
  -webkit-transition: box-shadow 0.3s, border 0.3s;
  -moz-transition: box-shadow 0.3s, border 0.3s;
  -o-transition: box-shadow 0.3s, border 0.3s;
  transition: box-shadow 0.3s, border 0.3s;
}
.mystyle input[type="text"]:focus, .style-1 input[type="text"].focus {
  border: solid 1px #707070;
  -webkit-box-shadow: 0 0 5px 1px #969696;
  -moz-box-shadow: 0 0 5px 1px #969696;
  box-shadow: 0 0 5px 1px #969696;
}
.container{
    width:960px;
    margin: auto;
    padding: 10px;
}

.clearfix:after {
  content: "";
  display: table;
  clear: both;
}

Step 5 : Assigning some power to our Lady i.e. JQuery i.e dict.js


$(document).ready(function(){
    $('#loadingDiv').hide();
    
    $("#search").click(function(){
         $('#loadingDiv').show();
        event.preventDefault();
       $.ajax({
            type: "POST",
            url: 'discServlet',
            dataType: 'json',
            data:$("#dictForm").serialize(),
            success: function(resp) {
                $("#result").html(""); 
                var result="";
                if(resp.length=== 0){
                    $("#result").html("<section>No matching word found :(</section>");
                    $('#loadingDiv').fadeOut();
                }else{
                
                 $.each(resp, function(key,value) { 
                     $('#loadingDiv').fadeOut();
                        if(value['wordtype']===""){
                            result = result+ '<section><span class="word">'+value['word']+' </span> : <span class="desc">'+value['definition']+'</span></section>';
                        }
                        else
                             result = result+ '<section><span class="word">'+value['word']+' </span><span class="grammer"> ['+value['wordtype']+' ]</span> : <span class="desc">'+value['definition']+'</span></section>';
                });
                $("#result").html(result);
            }
        }
        });
    });
});

            

Step 6 : Tada Time 
Now runt he app using apache tomcat or Glassfish server.

Step 7 : Coffee time
Happy Coding with Coffee. This project can also be found on Github here : OnlineDictionery

How to import SQL file in phpmyadmin which is over sized then allowed.

I am creating this tutorial using the Ubuntu so some of the directory may not be the same:

Step 1: 

Open the file named config.inc.php which is especially located in  /etc/phpmyadmin/config.inc.php
in Window generally located at : C:\wamp\apps\phpmyadmin3.2.0.1\config.inc.php

Step 2: 
Now find the line containing $cfg['UploadDir'] = ''; 
and replace it 
with $cfg['UploadDir'] = '/etc/phpmyadmin/upload'; 

in Window it will work
$cfg['UploadDir'] = 'upload'; 

Step 3: Now create the new folder named upload in the same directory of config.inc.php

Step 4: Now copy or place your .sql file in that upload folder.

Step 5: Now restart the server and refresh the upload page in the phpmyadmin

Step 6: Now You will be able to see the select option just below the upload option and now you can select the .sql file to import. Thats it now it start to import as a charm

Happy Importing :)

How to reverse Integer Array in Java


Here is the reverse the integer array in java,


 public class Reverse {  
      static int array[] = { 1, 2, 3, 4, 5 };  
      public static void main(String args[]) {  
           System.out.println("Before Reverse");  
           for (int i = 0; i < array.length; i++) {  
                System.out.print(array[i]+" ");  
           }  
           for (int i = 0; i < array.length / 2; i++) {  
                int temp = array[i];  
                array[i] = array[array.length - i - 1];  
                array[array.length - i - 1] = temp;  
           }  
           System.out.println("\n");  
           System.out.println("After Reverse");  
           for (int i = 0; i < array.length; i++) {  
                System.out.print(array[i]+" ");  
           }  
      }  
 }  


Output:

Before Reverse
1 2 3 4 5

After Reverse
5 4 3 2 1

How to check a string “StartsWith” another String and one string contains another substring? in Javascript


In JavaScript ,
var carname = 'Volvo XC60'; String indexes are zero-based: The first character is in position 0, the second in 1, and so on.

How to check a string “StartsWith” another String

You can use ECMAScript 6's String.prototype.startsWith() method, but it's not yet supported in all browsers.

you can use it like this:

"Hello World!".startsWith("He"); // true

var haystack = "Hello world";
var prefix = 'orl';
haystack.startsWith(prefix); // false

Another alternative with .lastIndexOf:

haystack.lastIndexOf(needle, 0) === 0


How to check one string contains another substring

String.prototype.indexOf returns the position of the string in the other string. If not found, it will return -1.

var string = "foo",
    substring = "oo";
console.log(string.indexOf(substring) > -1);


Or some times it works with,javaScript is case sensitive.

indexof() should actually be indexOf()

Try fixing it and see if that helps:

if (test.indexOf("title") !=-1) {
    alert(elm);
    foundLinks++;
}


How to page redirect using jQuery?


jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.


One does not simply redirect using jQuery
jQuery is not necessary, and window.location.replace(...) will best simulate an HTTP redirect.


For example:

// similar behavior as an HTTP redirect
window.location.replace("http://codingworkspace.com");

// similar behavior as clicking on a link
window.location.href = "http://codingworkspace.com";


Sometimes its works also,

$(window).attr("location","http://codingworkspace.com");






Towers of Honai solution in java

The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:
  1. Only one disk can be moved at a time.
  2. Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
  3. No disk may be placed on top of a smaller disk.


Towers of Honai solution , source:wikipedia

public class TowersOfHanoi {
/** Main method */
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
System.out.print("Enter number of disks: ");
int n = input.nextInt();

// Find the solution recursively
System.out.println("The moves are:");
moveDisks(n, 'A', 'B', 'C');
}
/** The method for finding the solution to move n disks
from fromTower to toTower with auxTower */
public static void moveDisks(int n, char fromTower,char toTower, char auxTower)
{
if (n == 1) // Stopping condition
System.out.println("Move disk " + n + " from " +
fromTower + " to " + toTower);
else {
moveDisks(n - 1, fromTower, auxTower, toTower);
System.out.println("Move disk " + n + " from " +
fromTower + " to " + toTower);


moveDisks(n - 1, auxTower, toTower, fromTower);
}
}
}

Find the last even in java


In some java interview, most asked question is find the last even of the given array, now we are going to solve this problem.

package one;

public class LastEven {

public static int[] arr = { 28, 3, 4, 6, 10, 11 ,11,23,22,3};

public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Last evend=" + lastEven(arr));
}

public static int lastEven(int[] arr) {
int lE = -1;
for (int x = 0; x < arr.length; x++) {
if (arr[x] % 2 == 0) {
lE = arr[x];
}
}
return lE;
}

}


Output:

Last evend=22

Open Links in New Pop off Window using Jquery


Here we want to open the links provided in the a tag in the new window.


HTML

<html>
    <head>
        <title></title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js"></script>
    </head>
    <body>
        <a href="http://www.google.com.com/" >click me</a>
        <a href="http://www.facebook.com/" >click me</a>
    </body>
</html>


Jquery  

$(document).ready(function(){ $("a").click(function(){ event.preventDefault(); window.open($(this).attr("href"), "My Task", width=600,height=300); }); })

Run it here Jsfiddle