Colorwalls

Colorwalls.

Posted in Uncategorized | Leave a comment

SCROLL TO BOTTOM ON BUTTON CLICK

HTML
—-
LT div id=”main” GT
LT div class=”container-fluid” id=”subParentDiv” GT
LT /div GT
LT /div GT

JAVA SCRIPT
———–
function checkScroll(){
scroll_to($(“#main”), $(“#subParentDiv”));
}

function scroll_to(base, target){
base.animate(
{
scrollTop:target.height()
},1000
);
}

EXPLANATION
———–
Call the checkScroll() function on your any button event.
the LT div id=”#main ” GT LT /div GT will have the scroll bar to set when it exceeds the limited height.

scrollTop:target.height() : i will take height of the target element and will scroll that much from the top side.
1000: i m the time duration in milli seconds to scroll the scroll bar.

Posted in JavaScript / CSS, JQuery | Leave a comment

Copy Particular Row and Append it in a Table

function copyAndAppend(id){
$(“#”+id+” tr:last”).after(“

” + $(“#serviceRow”).html() + “

“);
}

Explanation:
1) $(“#serviceRow”).html() : I will copy all the inner content of an element having id = “serviceRow”
2) $(“#”+id+” tr:last”) : I have used ‘id’ variable, its value will be the id of a table, and “tr:last”.after() will
add the new row at the end of the table

Posted in JavaScript / CSS, JQuery | Leave a comment

SQL TO INCREMENT EXISTING COLUMN VALUE BASED ON PARENT AND CHILD ID

DECLARE
i number:=0;
BEGIN
FOR REC1 IN (SELECT * FROM TBLMCSVDRIVER)
LOOP
i := 0;

FOR REC2 IN (SELECT * FROM TBLMCSVDRIVERFIELDMAP WHERE CSVDRIVERID = REC1.CSVDRIVERID order by fieldmapid)
LOOP
i:=i+1;

update TBLMCSVDRIVERFIELDMAP set ORDERNUMBER = i where FIELDMAPID = REC2.FIELDMAPID AND CSVDRIVERID = REC1.CSVDRIVERID;
END LOOP;
END LOOP;
END;
/

Posted in Uncategorized | Leave a comment

JQUERY VALIDATION FIRST FLIGHT JSP

MyForm

<script src="/jquery/jquery-1.9.1.js”>
<script src="/jquery/jquery.validate.min.js”>

/* example styles for validation form demo */
#registrationForm label.error {
color: red;
display: inline-block;
padding: 0;
text-align: left;
}

.fieldlabel{
width:150px;
text-align: right;
}

(function($,W,D)
{
var JQUERY4U = {};

JQUERY4U.UTIL =
{
setupFormValidation: function()
{
//form validation rules
$(“#registrationForm”).validate({
rules: {
firstname: “required”,
lastname: “required”,
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 5,
maxlength:12
},
mobile:{
required: true,
number: true,
minlength:10,
maxlength:10
}

},
messages: {
firstname: “First Name is required”,
lastname: “Last Name is required”,
password: {
required: “Password is required”,
minlength: “password must be at least 5 characters long”,
maxlength: “Password can be max 12 characters long”
},
mobile:{
required:”Mobile is Required”,
number: “Mobile can have digits only”,
minLength:”Mobile should have 10 digits”,
maxLength:”Mobile should have 10 digits”
},
email:{
required: “Email is Required”,
email: “Enter valid Email address”
}
},
submitHandler: function(form) {
form.submit();
}
});
}
}

//when the dom has loaded setup form validation rules
$(D).ready(function($) {
JQUERY4U.UTIL.setupFormValidation();
});

})(jQuery, window, document);

User Registration

Password:
First Name
Last Name
Email
Mobile
Posted in JQuery | Leave a comment

If Batch Operation failed then Handle all operation separately

package com.raj.db;

import java.sql.BatchUpdateException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class Student{

private int id;
private String name;
private String queryType;

Student(){}

Student(int id, String name, String queryType){
this.id = id;
this.name = name;
this.queryType = queryType;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

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

public String getQueryType() {
return queryType;
}

public void setQueryType(String queryType) {
this.queryType = queryType;
}
}

class DBManager{

private final String INSERT_QUERY = “INSERT INTO STUDENTS_DATA (ID, NAME) VALUES (?, ?)”;
private final String UPDATE_QUERY = “UPDATE STUDENTS_DATA SET NAME = ? WHERE ID = ?”;

private Connection connection = null;

public void loadDriver(){
try {
Class.forName(“oracle.jdbc.driver.OracleDriver”);
connection = DriverManager.getConnection(“URL”,”DB_NAME”,”DB_PASSWORD”);
} catch (Exception e) {
System.out.println(“Error while executing preparedstatement, Reason: “+e.getMessage());
}
}

public void insertData(){
int response[] = null;
PreparedStatement prepStmt = null;
List studentList = new ArrayList();

try{

connection.setAutoCommit(false);
prepStmt = connection.prepareStatement(INSERT_QUERY);

int starter = 7;
for(int i=starter; i<=starter+4; i++){
studentList.add(new Student(i,"student"+i, "INSERT"));
prepStmt.setInt(1, i);
prepStmt.setString(2, "Student"+i);
prepStmt.addBatch();
}
response = prepStmt.executeBatch();

} catch (BatchUpdateException be) {

try{
connection.rollback();
}catch(Exception ex){}

/*for(int command:be.getUpdateCounts()){
if(command == Statement.SUCCESS_NO_INFO){
System.out.println("SUCCESS "+command );
}else if(command == Statement.EXECUTE_FAILED){
System.out.println("FAILED "+command );
}
}*/
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(new Worker(studentList));
executor.shutdown();
System.out.println("Thread ShutDown");

}catch (Exception e) {
System.out.println("Error while executing batch, Reason: "+e.getMessage());
if(response!=null){
System.out.println("Response: "+response.length);
}

}finally{
closeQuietly(prepStmt);
closeQuietly(connection);
}
}

public void closeQuietly(Statement statement){
try {
if (statement != null) {
statement.close();
}
} catch (SQLException e) { }
}

public void closeQuietly(Connection connection){
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) { }
}

class Worker implements Runnable{

List dataList = null;
PreparedStatement insertPrepStmt = null;
PreparedStatement updatePrepStmt = null;
Worker(List data){
this.dataList = data;
}

@Override
public void run() {
loadDriver();
try{
insertPrepStmt = connection.prepareStatement(INSERT_QUERY);
updatePrepStmt = connection.prepareStatement(UPDATE_QUERY);

for(Student student: dataList){
String message = executeTask(student);
if(message.equalsIgnoreCase(“INSERT_FAILED”)){
System.out.println(“INSERT FAILED”);
student.setQueryType(“UPDATE”);
executeTask(student);
}
}

}catch(Exception ex){
System.out.println(“Exception while executing preparedStatement, Reason: “+ex.getMessage());
}finally{
closeQuietly(insertPrepStmt);
closeQuietly(connection);
}
}

public String executeTask(Student data){
try{
if(data.getQueryType().equalsIgnoreCase(“INSERT”)){
System.out.println(“INSERTING RECORD AGAING NOW”);
insertPrepStmt.setInt(1, data.getId());
insertPrepStmt.setString(2,data.getName());
insertPrepStmt.execute();

}else if(data.getQueryType().equalsIgnoreCase(“UPDATE”)){
System.out.println(“UPDATING NOW”);
updatePrepStmt.setString(1,data.getName()+”-UPDATED”);
updatePrepStmt.setString(2,data.getId()+””);
updatePrepStmt.executeUpdate();
}
connection.commit();
}catch(Exception ex){
return “INSERT_FAILED”;
}
return “SUCCESS”;
}
}
}

public class BatchOperationFlight {
public static void main(String bag[]){
System.out.println(“–START–“);
DBManager dbmanager = new DBManager();
dbmanager.loadDriver();
dbmanager.insertData();
System.out.println(“–END–“);
}
}

Posted in J2SE | Leave a comment

About Hibernate inverse=”true” or inverse=”false” attribute

Java 

Parent.java

package javafiles;

 

import java.util.Set;

 

publicclass Parent {

privateintid;

private String name;

private Set children;

publicint getId() {

returnid;

}

publicvoid setId(int id) {

this.id = id;

}

public String getName() {

returnname;

}

publicvoid setName(String name) {

this.name = name;

}

public Set getChildren() {

returnchildren;

}

publicvoid setChildren(Set children) {

this.children = children;

}

}

 

Children.java

package javafiles;

 

publicclass Children {

privateintid;

private String name;

privateintage;

privateintparentId;

private Parent parent;

publicint getId() {

returnid;

}

publicvoid setId(int id) {

this.id = id;

}

public String getName() {

returnname;

}

publicvoid setName(String name) {

this.name = name;

}

publicint getAge() {

returnage;

}

publicvoid setAge(int age) {

this.age = age;

}

publicint getParentId() {

returnparentId;

}

publicvoid setParentId(int parentId) {

this.parentId = parentId;

}

 

public Parent getParent() {

returnparent;

}

 

publicvoid setParent(Parent parent) {

this.parent = parent;

}

}

 

Inverse=”false”

Xml

Parent.hbm.xml File

<class name=“javafiles.Parent” table=“PARENTS_DATA”>

<id name=“id”  column=“ID” >

<generator class=“increment”/>

</id>

<property name=“name” column=“NAME” length=“20”/>

<set name=“children” cascade=“all” inverse=“false”>

<key column=“PARENT_ID”/>

<one-to-many class=“javafiles.Children”/>

</set>

</class>


Children.hbm.xml file

<class name=“javafiles.Children” table=“CHILDREN_DATA”>

<id name=“id” column=“ID”>

<generator class=“increment”/>

</id>

<property name=“name”            column=“NAME”       />

<property name=“age”             column=“AGE”        />

<many-to-one name=“parent” class=“javafiles.Parent”>

<column name=“PARENT_ID” />

</many-to-one>

</class>

Insert/Save

SessionFactory factory = cfg.buildSessionFactory();

Session session = factory.openSession();

Parent parentObj=new Parent();

parentObj.setName(“Raj”);

Children childObj1=new Children();

childObj1.setName(“Krishna”);

childObj1.setAge(56);

Children childObj2=new Children();

childObj2.setName(“Rajvir”);

childObj2.setAge(29);

Set<Children> childSet=new HashSet<Children>();

childSet.add(childObj1);

childSet.add(childObj2);

parentObj.setChildren(childSet);

Transaction transaction = session.beginTransaction();

session.save(parentObj);

 

Just set the child object into parent object and perform save operation on parent object. It will perform the operation successfully.

Must Read

But here it will perform additional update operation query on the child object’s table. Number of update operation query will be same as the number of child objects added into parent object.

Delete

Parent parentObj= (Parent) session.get(Parent.class, new Integer(1));

Transaction transaction=session.beginTransaction();

session.delete(parentObj);

 

Must Read

Delete the parent object using the session.delete() method it will delete the related child objects also. In delete operation also it will fire one update operation query on child object table.

 

Inverse=”true”

Xml

Parent.hbm.xml File

<class name=“javafiles.Parent” table=“PARENTS_DATA”>

<id name=“id”  column=“ID” >

<generator class=“increment”/>

</id>

<property name=“name” column=“NAME” length=“20”/>

<set name=“children” cascade=“all” inverse=“true”>

<key column=“PARENT_ID”/>

<one-to-many class=“javafiles.Children”/>

</set>

</class>


Children.hbm.xml file

<class name=“javafiles.Children” table=“CHILDREN_DATA”>

<id name=“id” column=“ID”>

<generator class=“increment”/>

</id>

<property name=“name”            column=“NAME”       />

<property name=“age”             column=“AGE”        />

<many-to-one name=“parent” class=“javafiles.Parent”>

<column name=“PARENT_ID” />

</many-to-one>

</class>

Must Read

Same as previous code Set the child object into parent object and perform save operation on parent object. It will save the data into both parent object’s and child object’s table. But it will not save the PARENT_ID into child’s object table. It will remain null.

Same way perform delete operation it will delete the data from the parent object’s table but it will not delete the data from the child object’s table.

The reason is inverse=”true”

 

<set name=“children” cascade=“all” inverse=“true” >

<key column=“PARENT_ID”/>

<one-to-many class=“javafiles.Children”/>

</set>

It indicates that the owner of the PARENT_ID column value is name=“children”  property of parent object. Unless we will set the parent object into child object it will not perform any operation on the PARENT_ID column.

 

Insert/Save

 

Parent parentObj=new Parent();

parentObj.setName(“Raj”);

Children childObj1=new Children();

childObj1.setName(“Krishna”);

childObj1.setAge(56);

        childObj1.setParent(parentObj);

Children childObj2=new Children();

childObj2.setName(“Rajvir”);

childObj2.setAge(29);

childObj2.setParent(parentObj);

Set<Children> childSet=new HashSet<Children>();

childSet.add(childObj1);

childSet.add(childObj2);

        parentObj.setChildren(childSet);

Transaction transaction = session.beginTransaction();

session.save(parentObj);

 

Delete

        session.delete(parentObj);

 

If we will set the parent object into child object

then only in save operation it will save the PARENT_ID into child object’s table.

And in delete operation it will delete the child data from the child object’s table.

Here it will not perform additional Update operation on child object’s table as in the case of inverse=”false”

 

The inverse=”true” gives the ownership  of  particular column  value to the respected object. By default it value is inverse=”false” and it gives ownership to the parent object.

Posted in Hibernate | Leave a comment

Get Current Month Name

Calendar cale = Calendar.getInstance();

System.out.println(“Month Name: “+cale.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault()));

Posted in J2SE | Leave a comment

Apache DBUtil Create-Insert-Select-Update-Delete program

 

public class PlayerData {

         private String id;
         private String name;
         private String team;
         private Long totalRuns;
         public String getId() {
                  return id;
         }
         public void setId(String id) {
                  this.id = id;
         }
         public String getName() {
                  return name;
         }
         public void setName(String name) {
                  this.name = name;
         }
         public String getTeam() {
                  return team;
         }
         public void setTeam(String team) {
                  this.team = team;
         }
         public Long getTotalRuns() {
                  return totalRuns;
         }
         public void setTotalRuns(Long totalRuns) {
                  this.totalRuns = totalRuns;
         }
         
         @Override
         public String toString() {
                  return “PlayerData [Id=” + id + “, Name=” + name + “, Team=” + team
                  + “, TotalRun=” + totalRuns + “]”;
         }         
}

——————————————————————————————————————-

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

class DatabaseWorkController{
         private Connection connection = null;
         private QueryRunner queryRunner = null;

         long startTime = 0;

         DatabaseWorkController(){ }

         public void loadDriverAndMakeConnection(){
                  System.out.println(“Method loadDriverAndMakeConnection()\n”);
                  try
                  {
                  
                           Class.forName(“oracle.jdbc.driver.OracleDriver”);
                           connection = DriverManager.getConnection(“jdbc:oracle:thin:@192.168.8.87:1521:aaadb”, “netvertextrunk”,                                     “netvertextrunk”);
                           queryRunner = new QueryRunner();
         
                  }catch(Exception e) {
                                    System.out.println(“Error : “+e);
                  }
         }

         public void insertData(){
                  System.out.println(“\nMethod insertData()”);
                  try {
                           startTime = System.currentTimeMillis();

                           int result = queryRunner.update(connection, “INSERT INTO PLAYERS (ID, NAME, TEAM, TOTALRUNS) VALUES(?,                                     ?, ?, ?)”,”1″,”SACHIN”,”India”,46000);
                           result = queryRunner.update(connection, “INSERT INTO PLAYERS (ID, NAME, TEAM, TOTALRUNS) VALUES(?, ?,                                     ?, ?)”,”1″,”SAMSON”,”India”,1000);
                           System.out.println(“Inserted Rows: “+result);
                           System.out.println(“Total Time taken: “+(System.currentTimeMillis()-startTime)+” ms”);
                  } catch (SQLException e) {
                           e.printStackTrace();
                  }
}

public void selectAllData(){
                  System.out.println(“\nMethod selectAllData()”);

                  ResultSetHandler<List<PlayerData>> rsh = new BeanListHandler<PlayerData>(PlayerData.class);
                  try {
                           startTime = System.currentTimeMillis();
                           List<PlayerData> result = queryRunner.query( connection, “SELECT * FROM PLAYERS”,rsh);
                           for(PlayerData player: result){
                                    System.out.println(player);
                           }
                           System.out.println(“Total Time taken: “+(System.currentTimeMillis()-startTime)+” ms”);
                  } catch (SQLException e) {
                           e.printStackTrace();
                  }
         }

         public void oldWaySelectAllData(){
                  System.out.println(“\nMethod oldWaySelectAllData()”);
                  ResultSet rs = null;
                  try {
                           startTime = System.currentTimeMillis();
                           Statement stmt = connection.createStatement();
                           rs = stmt.executeQuery(“select * from players”);
                           while(rs.next()){
                                    int id = rs.getInt(“ID”);
                                    String name = rs.getString(“name”);
                                    String team = rs.getString(“team”);
                                    String totalRuns = rs.getString(“totalruns”);
                                    System.out.println(“PlayerData [Id=” + id + “, Name=” + name + “, Team=” + team
                                    + “, TotalRun=” + totalRuns + “]”);
                           }
                           rs.close();
                           System.out.println(“Total Time taken: “+(System.currentTimeMillis()-startTime)+” ms”);
                           } catch (SQLException e) {
                                    e.printStackTrace();
                           }
                  }

                  public void selectParticularData(){
                           System.out.println(“\n\nMethod selectParticularData()”);
         
                           ResultSetHandler<PlayerData> rsh = new BeanHandler<PlayerData>(PlayerData.class);

                           try {
                                    startTime = System.currentTimeMillis();
                                    PlayerData player = queryRunner.query( connection, “SELECT * FROM PLAYERS WHERE ID = ? “,rsh, “1”);
                                    System.out.println(“Total Time taken: “+(System.currentTimeMillis()-startTime)+” ms”);
                                    System.out.println(player);
                                    } catch (SQLException e) {
                                             e.printStackTrace();
                                    }
                           }
                  
                           public void updateParticularData(){
                                    System.out.println(“\n\nMethod updateParticularData()”);
                                    try {

                                             startTime = System.currentTimeMillis();
                                              int result = queryRunner.update(connection,”UPDATE PLAYERS SET NAME = ? WHERE ID = ?                                                                “,”Sachin Tendulkar”,”1″);
                                             System.out.println(“Total Time taken: “+(System.currentTimeMillis()-startTime)+” ms”);
                                             System.out.println(“Update Rows: “+result);
                                    } catch (SQLException e) {
                                             e.printStackTrace();
                                    }
         }

         public void deleteTable(){
                  System.out.println(“\n\nMethod deleteTable()”);
                           try {
                                    startTime = System.currentTimeMillis();
                                    int result = queryRunner.update(connection,”DROP TABLE PLAYERS”);
                                    System.out.println(“Total Time taken: “+(System.currentTimeMillis()-startTime)+” ms”);
                                    System.out.println(“Table deleted successfully: “+result);
                           } catch (SQLException e) {
                                    e.printStackTrace();
                           }

                  }

                  public void destroyConnection(){
                           System.out.println(“\n\nMethod destroyConnection()”);
                           try {
                                    startTime = System.currentTimeMillis();
                                    DbUtils.close(connection);
                                    System.out.println(“Total Time taken: “+(System.currentTimeMillis()-startTime)+” ms”);
                           } catch (SQLException e) {
                                    e.printStackTrace();
                           }
                  }

                  public void createTable() {
                                    System.out.println(“\n\nMethod createTable()”);
                           try {
                  
                                    startTime = System.currentTimeMillis();
                                    int result = queryRunner.update(connection,”CREATE TABLE PLAYERS ( ID int, Name varchar(255), Team                                              varchar(255), TotalRuns varchar(255))”);
                                    System.out.println(“Total Time taken: “+(System.currentTimeMillis()-startTime)+” ms”);
                                    System.out.println(“Table created successfully: “+result);
                           } catch (SQLException e) {
                                    e.printStackTrace();
                           }
                  }
         }

         public class DBUtilFlight {

         public static void main(String[] dataBag)
         {
                  DatabaseWorkController controller = new DatabaseWorkController();
                  controller.loadDriverAndMakeConnection();
                  
                  controller.createTable();
                  controller.insertData();
                  controller.selectAllData();
                  controller.oldWaySelectAllData();

                  controller.selectParticularData();
                  controller.updateParticularData();
                  controller.selectParticularData();

                  controller.deleteTable();
}
}

 

Posted in J2SE | Leave a comment

TLD to display Logo (Image)

Note: Put your Image Under the  (contextPath of your App/images/) folder

TLD FILE

<?xml version=”1.0″ encoding=”ISO-8859-1″ ?>
<!DOCTYPE taglib PUBLIC “-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN” “http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd”&gt;

<taglib>
<tlibversion>1.5</tlibversion>
<jspversion>1.1</jspversion>
<shortname>NetvertexSM</shortname>
<uri>http://https://javacircles.wordpress.com/myprojects/tags</uri&gt;
<info>I am JavaCirle</info>

<tag>
<name>logoImage</name>
<tagclass>com.raj.myproject.util.MyLogo</tagclass>
<bodycontent>empty</bodycontent>
<info>Logo Image</info>
</tag>

</taglib>

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

CLASS FILE

—————–

 

package com.raj.myproject.util;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

public class MyLogo extends TagSupport {
private static final long serialVersionUID = 1L;
private static final String MODULE = ElitecoreLogo.class.getSimpleName();

public int doStartTag() throws JspException {

JspWriter painter = pageContext.getOut();
HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
StringBuffer results = new StringBuffer();
results.append(“<input type=\”image\” src=\””+request.getContextPath()+”/images/jisp.jpg\” width=\”101\”                                                         height=\”113\” />”);
try {
painter.write(results.toString());
} catch (IOException e) {
Logger.logError(MODULE, “Exception reason : “+e.getMessage());
e.printStackTrace();
}
return EVAL_PAGE;
}
}

Posted in J2EE | Leave a comment