Sunday, August 15, 2010

Rhino JavaScript Tutorial, Rhino js using java code, JavaScript interface

Download js-1.6R7.jar from net. Or you can use this pom.xml to download this jar file
<dependency>
<groupId>rhino</groupId>
<artifactId>js</artifactId>
<version>1.6R7 </version>
</dependency>

How to setup rhino js in console:

I have put my this above jar into D:\.m2\repository\rhino\js\1.6R7\js-1.6R7.jar

creat one bat file like rhino.bat and put this command
java -classpath .;D:\.m2\repository\rhino\js\1.6R7\js-1.6R7.jar org.mozilla.javascript.tools.shell.Main

save it.

Now double click on that batch file you will get
js> prompt.

now you can check bit code here
js> print('Binod')
Binod
js> 37+57
94
js>

for quiting:

quit();

js> quit();


You can open windows application using js
js> runCommand("notepad"); // It will open notepad
0
js> runCommand("mspaint");
0
js> runCommand("calc");
0
js> runCommand("cmd", "/C", "date /T")
Fri 08/13/2010

create one java script like abc.js
function check(name) {
for(i=0;i<10;i++){
print(name);
}

}


js> load("abc.js");
js> check("Binod");
Binod
Binod
Binod
Binod
Binod
Binod
Binod
Binod
Binod
Binod
js>

How to use the Rhino javascript embedded into java code



import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

/**
* @author Binod Suman
*/
public class Demo {


public static void main(String[] args) {
new Demo().check();
}

public void check(){
ScriptEngineManager engineMgr = new ScriptEngineManager();
ScriptEngine engine = engineMgr.getEngineByName("JavaScript");
try {
engine.eval("function sayHello(s,c) {" +" println('Hello, world! '+s+' '+c);" +"}");
Invocable invocableEngine = (Invocable) engine;
invocableEngine.invokeFunction("sayHello","Binod","Tecnotree");
} catch (ScriptException ex) { ex.printStackTrace();}
catch(Exception e){e.printStackTrace();}
}

}

Useful link:
http://www.mozilla.org/rhino/tutorial.html
Good Tutorial : http://www.mozilla.org/rhino/ScriptingJava.html
http://java.sun.com/developer/technicalArticles/J2SE/Desktop/scripting/

Tuesday, July 13, 2010

Null value was assigned to a property of primitive type setter of

While fetching data from database using jpa and hibernate I got one error and this is

org.springframework.orm.jpa.JpaSystemException: org.hibernate.PropertyAccessException: Null value was assigned to a property of primitive type setter of com.ayush.suman.bo.Address.trusted; nested exception is javax.persistence.PersistenceException: org.hibernate.PropertyAccessException: Null value was assigned to a property of primitive type setter of com.ayush.suman.bo.Address.trusted

My Address.java was like this:

@Entity
@Table(name="address")
public class Address {

@Id
private long id;
private String address;
@Column(name="country_code")
private String countryCode;
@Column(name="address_type")
private String addressType;

private int trusted;

with getter and setter methods

}

Solution:

Just change int to Integer simple ....... :)

Now updated Address.java

@Table(name="address")
public class Address {

@Id
private long id;
private String address;
@Column(name="country_code")
private String countryCode;
@Column(name="address_type")
private String addressType;

private Integer trusted;

with getter and setter methods

}

Dont forgate to change int to Integer in setter and getter method of trusted field.

Turning off hibernate logging console output, How to hide/disable Hibernate log to console

Just sharing my experiance with Hibernate 3.0.

Even after using the log4j.xml with

<logger name="org.hibernate">
<level value="info"/>
</logger>


I could not able to trun off the huge hibernate log on console, it was coming like this:

7 [main] INFO org.hibernate.cfg.annotations.Version - Hibernate Annotations 3.4.0.GA
37 [main] INFO org.hibernate.cfg.Environment - Hibernate 3.3.0.SP1
43 [main] INFO org.hibernate.cfg.Environment - hibernate.properties not found
48 [main] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist
52 [main] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
163 [main] INFO org.hibernate.annotations.common.Version - Hibernate Commons Annotations 3.1.0.GA
168 [main] INFO org.hibernate.ejb.Version - Hibernate EntityManager 3.4.0.GA
202 [main] INFO org.hibernate.ejb.Ejb3Configuration - Processing PersistenceUnitInfo [

name: VMSPersistenceUnit

...]



Finally I got solution and that is here:

Just add slf4j-log4j12-1.5.2.jar in your classpath if you are using slf4j-api. Actually SLF4J is used by hibernate and if you are using log4j you need to setup the bridge for your logging system.



In my case, I have these jar files in my project classpath:


slf4j-api-1.5.6.jar
slf4j-log4j12-1.5.6.jar
slf4j-simple-1.4.2.jar


Thats it ...... :)

Monday, June 14, 2010

Check small java code on groovy console

For this tutorial, Groovy should be installed to your pc.
For how to install Groovy and fundamental of Groovy, check here.
http://ayushsuman.blogspot.com/2010/04/groovy-getting-started-how-use-groovy.html

If you want to check some java code then no need to write the one complete java class to check you bit code.You can use groovy console to check your java codes.

If you have already configured your groovy bin folder with path then
c:\>groovyConsole.bat
It will open one window then you can paste your code

String name = "BINOD KUMAR SUMAN";
System.out.println("Name :: "+name);
System.out.println("Now :: "+new Date());

and press Ctrl+R and see your code result on below screen.
Name :: BINOD KUMAR SUMAN
Now :: Sat Jun 12 11:28:02 EEST 2010

Ctrl+W for clear the output. Again you can check your some code. :)

Get the fild value from java class during run time using reflection

Get the fild value from java class during run time using reflection.

Suppose, you have one java class that is having a lot of static value and you want that int value during run time with dynamic field name.
Like,

public class Types
{
public static final int BIT = -7;
public static final int TINYINT = -6;
public static final int SMALLINT = 5;
public static final int INTEGER = 4;
public static final int BIGINT = -5;
public static final int FLOAT = 6;
public static final int REAL = 7;
public static final int DOUBLE = 8;
public static final int NUMERIC = 2;
public static final int DECIMAL = 3;
public static final int CHAR = 1;
public static final int VARCHAR = 12;
public static final int LONGVARCHAR = -1;
public static final int DATE = 91;
public static final int TIME = 92;
public static final int TIMESTAMP = 93;
}

And you have one string that containg the "TINYINT" during run time, now you have to fetch what is the value of TINYINT dynamically.
string filed = "TINYINT";

String field = "TINYINT";
Class typeClass = Class.forName("java.sql.Types");
int fieldValue = (Integer) typeClass.getField(field).get(null);
System.out.println("fieldValue :: "+fieldValue);


Output:

fieldValue :: -6

Tuesday, June 8, 2010

First Struts Example with Hibernate, Hibernate and Spring first example

1. Create one MyFirstStruts Web Dynamic Project (Say C:\workspaceAll\Struts\FirstStruts)

2. Create JSP pages
a) CustomerForm.jsp (C:\workspaceAll\Struts\MyFirstStruts\WebContent)
b) Success.jsp (C:\workspaceAll\Struts\MyFirstStruts\WebContent\Success.jsp)

3. Configuration Files
a) web.xml (C:\workspaceAll\Struts\MyFirstStruts\WebContent\WEB-INF\web.xml)
b) struts-config.xml (C:\workspaceAll\Struts\MyFirstStruts\WebContent\WEB-INF\struts-config.xml)
c) hibernate.cfg.xml (C:\workspaceAll\Struts\MyFirstStruts\src\hibernate.cfg.xml)
d) Customer.hbm.xml (C:\workspaceAll\Struts\MyFirstStruts\src\Customer.hbm.xml)

4. Java Files
a) CustomerForm.java (C:\workspaceAll\Struts\MyFirstStruts\src\CustomerForm.java)
b) CustomerAction.java (C:\workspaceAll\Struts\MyFirstStruts\src\CustomerAction.java)
c)Customer.java (C:\workspaceAll\Struts\MyFirstStruts\src\Customer.java)

5. Put these jar files (C:\workspaceAll\Struts\MyFirstStruts\WebContent\WEB-INF\lib)
a) commons-beanutils.jar
b) commons-collections.jar
c) commons-digester.jar
d) commons-logging.jar
e) struts.jar
f) mysql-connector-java-3.1.12-bin.jar
g) commons-logging-1.1.jar
h) dom4j-1.6.1.jar
i) commons-collections-3.2.jar
j) log4j-1.2.15.jar
k) slf4j-1.6.0/slf4j-1.6.0/slf4j-api-1.6.0.jar
l) slf4j-1.6.0/slf4j-1.6.0/slf4j-log4j12-1.6.0.jar
m) slf4j-1.6.0/slf4j-1.6.0/slf4j-simple-1.6.0.jar
n) javassist-3.3.jar
o) jta-1.0.1B.jar
p) hibernate-commons-annotations-3.1.0.GA.jar
q) hibernate-annotations-3.1beta8.jar
r) hibernate-core-3.3.1.GA.jar
s) antlr-2.7.5H3.jar

6. Download and put struts-html.tld into C:\workspaceAll\Struts\MyFirstStruts\WebContent\WEB-INF\struts-html.tld
(If you download struts-1.2.9-lib.zip, then struts-html.tld file is there)

CustomerForm.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<html:html xhtml="true">
<body>
<html:form action="/submitCustomerForm">
Put Customer First Name <html:text property="firstName" size="16" maxlength="16"/> <BR/>
Put Customer Last Name <html:text property="lastName" size="16" maxlength="16"/> <BR/> <P/>
<html:submit>Save</html:submit>
</html:form>
</body>
</html:html>

Success.jsp
<html>
<h1> THIS IS SUCCESS PAGE </h1>
</html>

CustomerForm.java

import org.apache.struts.action.ActionForm;
public class CustomerForm extends ActionForm {
private String firstName;
private String lastName;
public CustomerForm() { firstName = ""; lastName = ""; }
public String getFirstName() { return firstName; }
public void setFirstName(String s) { this.firstName = s; }
public String getLastName() { return lastName; }
public void setLastName(String s) { this.lastName = s; }
}

Customer.java


/**
* @author Binod Suman
*/
public class Customer {

private int custId;
private String firstName;
private String lastName;
public Customer(){}
public int getCustId() {return custId;}
public void setCustId(int custId) {this.custId = custId;}
public String getFirstName() {return firstName;}
public void setFirstName(String firstName) {this.firstName = firstName;}
public String getLastName() {return lastName;}
public void setLastName(String lastName) {this.lastName = lastName;}

}



CustomerAction.java

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class CustomerAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {

ActionForward nextPage = null;
CustomerForm custForm = (CustomerForm) form;
String firstName = custForm.getFirstName();
String lastName = custForm.getLastName();
Customer customer = new Customer();
customer.setFirstName(firstName);
customer.setLastName(lastName);
saveCustomer(customer);
System.out.println("Customer First name is " + firstName);
System.out.println("Customer Last name is " + lastName);
nextPage = mapping.findForward("success");
return nextPage; }

public void saveCustomer(Customer customer){
System.out.println("Inserting new customer record ...... ");
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session =sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
session.save(customer);
transaction.commit();
session.flush();
session.close();
System.out.println("Customer record has been successfully saved ");
}

}

web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>Hello World Struts Application</display-name>
<servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-

name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>
<servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <taglib> <taglib-uri>/WEB-INF/struts-

html.tld</taglib-uri> <taglib-location>/WEB-INF/struts-html.tld</taglib-location> </taglib> </web-app>

struts-config.xml
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd"><struts-config> <form-beans> <form-bean name="myForm" type="CustomerForm" /> </form-beans>
<action-mappings> <action path="/submitCustomerForm" type="CustomerAction" name="myForm" scope="request"> <forward name="success" path="/Success.jsp" />

</action> </action-mappings>
</struts-config>


create table in mysql sumandb database.

CREATE TABLE customer (
id int(11) NOT NULL,
firstName varchar(100) default NULL,
secondName varchar(100) default NULL,
PRIMARY KEY (id)
)


Start the server after deploy your application:
http://localhost:8080/FirstStruts/CustomerForm.jsp
Put First Name: Binod
Put Second Name: Suman
Click on Save button and check the server console, you should be get
Customer First name is Binod
Customer Last name is Suman

Check your sumandb database, one new record has been inserted.
and new success page will come with message:
THIS IS SUCCESS PAGE

How to use preapredStatment using Spring JdbcOperations.

Even it is very small thing but I searched on net lot with these words on goolge but didnt get solution.

Now I am going to show here how we can use preaparedstatement with spring JdbcOperations.

Create these five file in your Eclipse project.

DaoOperation.java
IDaoOperation.java
App.java
Myconfig.xml
MyProperties.properties

DaoOperation.java

import java.sql.SQLException;
import java.util.Set;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcOperations;

public class DaoOperation implements IDaoOperation{
private JdbcOperations jdbc;
public void saveStudentData() throws SQLException{
String sql = "insert into student (id,name,marks) values (?,?,?)";
Object[] args = {5,"Suman",99};
executeUdpdateSQL(sql,args);
}

public void updateStudentData() throws SQLException{
String sql = "update student set name=?, marks = ? where id = ?";
Object[] args = {"Ayush Suman",999,5};
executeUdpdateSQL(sql,args);
}

public void executeUdpdateSQL(String sql, Object[] args) throws SQLException {
jdbc.update(sql, args);
}

public JdbcOperations getJdbc() {return jdbc;}
public void setJdbc(JdbcOperations jdbc) {this.jdbc = jdbc;}

}

IDaoOperation.java

import java.sql.SQLException;
/**
* @author Binod Suman
*/
public interface IDaoOperation {
public void saveStudentData() throws SQLException;
public void updateStudentData() throws SQLException;
}

App.java
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {
public static void main(String[] args) throws Exception {
IDaoOperation daoOperation;
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("Myconfig.xml");
daoOperation = (IDaoOperation) context.getBean("daoOperation");
daoOperation.saveStudentData();
// daoOperation.updateStudentData();
}

}


Myconfig.xml

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/lang
http://www.springframework.org/schema/lang/spring-lang-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<context:mbean-server/>
<context:property-placeholder location="classpath:/MyProperties.properties"/>

<bean id="daoOperation" class="DaoOperation"
p:jdbc-ref="jdbc" />

<bean id="jdbc" class="org.springframework.jdbc.core.JdbcTemplate"
p:dataSource-ref="dataSource" />

<bean id="dataSource" destroy-method="close"
class="org.apache.commons.dbcp.BasicDataSource" p:driverClassName="${db.driver}"
p:url="${db.url}" p:username="${db.username}" p:password="${db.password}" />

</beans>


MyProperties.properties

db.driver = com.mysql.jdbc.Driver
db.url = jdbc:mysql://localhost/sumandb
db.username = root
db.password = mysql