Monday, March 3, 2014

Make life easy with Guice

I decided to write my experience with Guice and how I have used it but before moving fwd Would like to announce it has nothing to do with Guice Tutorial or Guide. It's about my experience with Guice and it's usages as I conceived.

First I would like to announce that Guice has made my life hell lot easier and organised. I may not be the expert but would not mind to achieve the pinnacle :).

Without contradicting I model Guice into 2 parts. Binder and Injector.

"Without Binding no Injection" - was quite clear in first read.

 But I wanted more. How I can use Binding along as I see it as a tool to provide me instance of class. But how to achive it was the question.

But I discovered the answer but may or may not be the best but who wants to be the best ?
"Best is degrading"

I create  ClassInstanceLocator.


public class ClassInstanceLocator {
 private static Injector injector = null;
 
 /**
         * Get Class Instance
         */
 public static <T> T getInstance(final Class<T> t) {
  return injector.getInstance(t);
 }

 /**
  * Initialize Modules during bootstraping.
         * It should be initialized during bootstraping thus making it thread aware.
  * 
  * @param modules
  */
 public synchronized static void initializeModule(final AbstractModule... modules) {

  /* Common module should iniitialized as rest module depends on it
                 * One can make it conditional so that once 
                 *commond is initialized should not be initialized again 
                 */
                if(injector==null){
                 injector = Guice.createInjector(new CommonModule());
                }
  
  if (modules != null) {
   injector = injector.createChildInjector(modules);
  }
 }

 /**
  * Destroys Guice injection tree
  */
 public synchronized static void deInitializeModules() {
  
  injector = null;
 }
 
 /**
  * 
  * @return - Are modules Initialized
  */
 public static boolean isModulesInitialized() {
  return injector != null;
 }

 
}

My life became so easy after this beautiful piece of code. Infact I sometime feel, I am abusing it and become so much addictive of it that I have stop using new. Any way the whole idea of life is to make it more simple.

I can count lot of benefit if I am using it like this.

  • I can always change my implementation from single place without changing it's usages even if it's a concrete class.
  • I can always make class instance as  Singleton as and when I need.
    There are many more I am sure. Without doubt  it's Guice which gives me this liberty, But I am just trying to maximize on it.

Happy Injecting happyness in life.

Adios 
Prabhat








Saturday, April 6, 2013

MySQL Basics


I will briefly take you through creating a table in Mysql (using MySQL prompt).

To start the MySQL prompt

c:\>mysql -u root -p

Enter the password and access the MySQL prompt.

mysql>

1. Create new database:

SYNTAX: create database databasename;

mysql> create database emp_db;

To see the created database

mysql>Show databases;

+--------------------+
| Database           |
+--------------------+
| information_schema |
| emp_db            |
| mysql              |
| test               |
+--------------------+


To use the database you created

SYNTAX: use databasename;

mysql> use emp_db;


2. Create a table

SYNTAX: create table tablename (columnname1 datatype(size), columnname2 datatype(size) , columnname3 datatype(size),PRIMARY KEY (columname));

mysql>Create table employee (userid INT NOT NULL AUTO_INCREMENT , firstname varchar (50), lastname varchar (50) , PRIMARY KEY (userid));


3. Insert values into the table

SYNTAX: Insert into tablename (columname1,columname2…..) values (‘value1’,’value2’,…..);

mysql>Insert into employee(userid , firstname ,lastname) values ('1068' , 'JHON' , 'R');


4. Select table data

SYNTAX: Select * from tablename;

mysql>Select * from employee;

Result:
+--------+-----------+----------+
| userid | firstname | lastname |
+--------+-----------+----------+
|   1068 | JHON      | R        |
+--------+-----------+----------+


5. Update data in a table

SYNTAX: Update tablename SET column1='newvalue' where column1="oldvalue";

or

SYNTAX: Update tablename SET column1='newvalue' where column2="referencevalue";

mysql> Update employee SET lastname='Robert' where column1="R";


6. Select data by joining two tables

SYNTAX: SELECT table1.column1 ,table1.column2, FROM table1 INNER JOIN table2 ON table1.column1=table2.column1;

mysql> SELECT employee.userid , employee.firstname, emp_details.city ,emp_details.country  FROM employee  INNER JOIN emp_details  ON employee. userid = emp_details. userid;

mysql> select * from employee;
+--------+-----------+----------+
| userid | firstname | lastname |
+--------+-----------+----------+
|   1068 | JHON      | R        |
|   1069 | MICKEL    | C        |
|   1070 | ADAM      | S        |
|   1071 | BELL      | D        |
|   1072 | DANIEL    | A        |
+--------+-----------+----------+

mysql> select * from emp_details;
+--------+-----------+-----------+
| userid | city      | country   |
+--------+-----------+-----------+
|   1068 | newyork   | USA       |
|   1069 | london    | UK        |
|   1070 | paris     | Germeny   |
|   1071 | new delhi | india     |
|   1072 | sydney    | Australia |
+--------+-----------+-----------+

mysql> SELECT employee.userid , employee.firstname, emp_details.city ,emp_details.country  FROM employee  INNER JOIN emp_details  ON employee. userid = emp_details. userid;
+--------+-----------+-----------+-----------+
| userid | firstname | city      | country   |
+--------+-----------+-----------+-----------+
|   1068 | JHON      | newyork   | USA       |
|   1069 | MICKEL    | london    | UK        |
|   1070 | ADAM      | paris     | Germeny   |
|   1071 | BELL      | new delhi | india     |
|   1072 | DANIEL    | sydney    | Australia |
+--------+-----------+-----------+-----------+


7. Delete table data

SYNTAX: DELETE FROM table_name WHERE columnname=value;

mysql> FROM employee WHERE lastname=’Robert’;


8. Delete all rows in a table

SYNTAX: DELETE * FROM table_name ;

mysql> DELETE * FROM employee;


9. Delete a table

SYNTAX: DROP TABLE table_name;

mysql> DROP TABLE employee;


10. Delete a database

SYNTAX: DROP DATABASE database_name;

mysql> DROP DATABASE employee;


For more visit Collegelabs


Saturday, February 16, 2013

Login Tutorial Using Ajax and JQuery

I will briefly take you through creating a login page using jquery. Instead of boring you with a how-to here is the code with comments for each part of the code.

<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Dialog - Default functionality</title>
<!--
1) Include the jquery base css. It's mandatory to include this since it is being used
by jquery internally to render and manipulate the dom tree
-->
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />
<!--
2) Include the jquery javascript library files
-->
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<!--
3) Include custom css for the customized dialog box for the login form  and also for the progress bar which indicates the login progress.
-->
<style type="text/css">
.ui-dialog-titlebar-close {visibility: hidden;} //Hides the close button of dialog box
label, input { display:block; }
input.text { margin-bottom:12px; width:95%; padding: .4em; }
fieldset { padding:0; border:0; margin-top:25px; }
.progress-label {
float: left;
margin-left: 50%;
margin-top: 10px;
font-weight: bold;
text-shadow: 1px 1px 0 #fff;
}
</style>
<!--
4) Javascript functions for customized dialog box and provide action buttons for login and cancel.  See inline comments for more granularity
-->
<script>
//
// 5) Hides progress bar and enables login and password fields.
//
function hideProgressBar(){
$( "#user_name").prop('disabled', false);
$( "#password").prop('disabled', false);
$( "#progressbar" ).hide();
}
//
// 6) Show progress bar and disable login and password fields.
//
function showProgressBar(){
$( "#user_name").prop('disabled', true);
$( "#password").prop('disabled', true);
$( "#progressbar" ).show();
var progressbar = $( "#progressbar" ),
progressLabel = $( ".progress-label" );
progressbar.progressbar({
value: false,
change: function() {
progressLabel.text( progressbar.progressbar( "value" ) + "%" ); // Set % completion of task
},
complete: function() {
progressLabel.text( "Complete!" ); // Set task completed
}
});
function progress() {
var val = progressbar.progressbar( "value" ) || 0;
progressbar.progressbar( "value", val + 1 ); // Value with in range of 1 to 100
if ( val < 99 ) {
setTimeout( progress, 100 ); // It's a timer which will start after 100 mili sec
}
}
setTimeout( progress, 3000 ); // Set a timer of 3 sec before progress bar starts.
}
 // This function does the most important task of adding action to login form.
// Adds login button and attaches showProgressBar function to display progress bar.
// Adds cancel button and attaches hideProgressBar function to hide progress.
// When page is getting loaded this function will be executed.
$(function() {
$( "#dialog" ).css('text-align','left' );
$( "#dialog" ).dialog({
autoOpen: false,
height: 400,
width: 500,
modal: true,
buttons: {
"Login": function() {
// E-Mail and password validation can be provided here
showProgressBar();
$.ajax({
type: "POST", //Ajax type Get/POST
url: "www.google.com", //URL to post the data.
data: { name: $( "#user_name"), password: $( "#password")}
}).done(function( msg ) {
// Receives information from server after successful post.
}).fail(function() {
alert("error"); //Catch any error while posting.
});
},
Cancel: function() {
hideProgressBar();
}
}
});
});
//This piece of code will hide the <div id="progressbar"><div class="progress-label">Loading...</div></div> tag from display and will show login form.
$(function(){
$( "#progressbar" ).hide();
$( "#dialog" ).dialog("open");
});
</script>
</head>
<body>
<!--
Login form
-->
<div id="dialog" title="Please login" >
<fieldset>
<label for="email">Email</label>
<input type="text" name="userData.user_name" id="user_name" value="" class="text ui-widget-content ui-corner-all" />
<label for="password">Password</label>
<input type="password" name="userData.password" id="password" value="" class="text ui-widget-content ui-corner-all" />
</fieldset>
<div id="progressbar"><div class="progress-label">Loading...</div></div>
</div>
</body>
</html>
in.linkedin.com/in/prabhat1981/


For more visit Collegelabs