tag:blogger.com,1999:blog-79130683053012255662024-03-07T21:06:54.262-08:00Ayush Java SolutionMaking java as fun with simple exampleAyush Java Solutionhttp://www.blogger.com/profile/06285300908312833165noreply@blogger.comBlogger20125tag:blogger.com,1999:blog-7913068305301225566.post-83676162363944754712010-08-15T10:28:00.000-07:002010-08-15T10:28:48.696-07:00Rhino JavaScript Tutorial, Rhino js using java code, JavaScript interfaceDownload js-1.6R7.jar from net. Or you can use this pom.xml to download this jar file<br />
<dependency><br />
<groupId>rhino</groupId><br />
<artifactId>js</artifactId><br />
<version>1.6R7 </version><br />
</dependency><br />
<br />
How to setup rhino js in console:<br />
<br />
I have put my this above jar into D:\.m2\repository\rhino\js\1.6R7\js-1.6R7.jar<br />
<br />
creat one bat file like rhino.bat and put this command<br />
java -classpath .;D:\.m2\repository\rhino\js\1.6R7\js-1.6R7.jar org.mozilla.javascript.tools.shell.Main<br />
<br />
save it.<br />
<br />
Now double click on that batch file you will get<br />
js> prompt.<br />
<br />
now you can check bit code here<br />
js> print('Binod')<br />
Binod<br />
js> 37+57<br />
94<br />
js><br />
<br />
for quiting:<br />
<br />
quit();<br />
<br />
js> quit();<br />
<br />
<br />
You can open windows application using js<br />
js> runCommand("notepad"); // It will open notepad<br />
0<br />
js> runCommand("mspaint");<br />
0<br />
js> runCommand("calc");<br />
0<br />
js> runCommand("cmd", "/C", "date /T")<br />
Fri 08/13/2010<br />
<br />
create one java script like abc.js<br />
function check(name) { <br />
for(i=0;i<10;i++){<br />
print(name);<br />
}<br />
<br />
}<br />
<br />
<br />
js> load("abc.js");<br />
js> check("Binod");<br />
Binod<br />
Binod<br />
Binod<br />
Binod<br />
Binod<br />
Binod<br />
Binod<br />
Binod<br />
Binod<br />
Binod<br />
js><br />
<br />
<b>How to use the Rhino javascript embedded into java code<br />
</b><br />
<br />
<br />
import java.io.InputStream;<br />
import java.io.InputStreamReader;<br />
import java.io.Reader;<br />
<br />
import javax.script.Invocable;<br />
import javax.script.ScriptEngine;<br />
import javax.script.ScriptEngineManager;<br />
import javax.script.ScriptException;<br />
<br />
/**<br />
* @author Binod Suman<br />
*/<br />
public class Demo {<br />
<br />
<br />
public static void main(String[] args) {<br />
new Demo().check();<br />
}<br />
<br />
public void check(){<br />
ScriptEngineManager engineMgr = new ScriptEngineManager();<br />
ScriptEngine engine = engineMgr.getEngineByName("JavaScript");<br />
try {<br />
engine.eval("function sayHello(s,c) {" +" println('Hello, world! '+s+' '+c);" +"}");<br />
Invocable invocableEngine = (Invocable) engine;<br />
invocableEngine.invokeFunction("sayHello","Binod","Tecnotree");<br />
} catch (ScriptException ex) { ex.printStackTrace();}<br />
catch(Exception e){e.printStackTrace();}<br />
}<br />
<br />
}<br />
<br />
Useful link:<br />
http://www.mozilla.org/rhino/tutorial.html<br />
Good Tutorial : http://www.mozilla.org/rhino/ScriptingJava.html<br />
http://java.sun.com/developer/technicalArticles/J2SE/Desktop/scripting/Ayush Java Solutionhttp://www.blogger.com/profile/06285300908312833165noreply@blogger.com24tag:blogger.com,1999:blog-7913068305301225566.post-90561387136008779522010-07-13T04:54:00.000-07:002010-07-13T04:54:06.652-07:00Null value was assigned to a property of primitive type setter ofWhile fetching data from database using jpa and hibernate I got one error and this is <br />
<br />
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<br />
<br />
My Address.java was like this:<br />
<br />
@Entity<br />
@Table(name="address")<br />
public class Address {<br />
<br />
@Id<br />
private long id;<br />
private String address;<br />
@Column(name="country_code")<br />
private String countryCode;<br />
@Column(name="address_type")<br />
private String addressType;<br />
<br />
private int trusted;<br />
<br />
with getter and setter methods<br />
<br />
}<br />
<br />
<b>Solution:<br />
</b><br />
Just change int to Integer simple ....... :)<br />
<br />
Now updated Address.java<br />
<br />
@Table(name="address")<br />
public class Address {<br />
<br />
@Id<br />
private long id;<br />
private String address;<br />
@Column(name="country_code")<br />
private String countryCode;<br />
@Column(name="address_type")<br />
private String addressType;<br />
<br />
private Integer trusted;<br />
<br />
with getter and setter methods<br />
<br />
}<br />
<br />
Dont forgate to change int to Integer in setter and getter method of trusted field.Ayush Java Solutionhttp://www.blogger.com/profile/06285300908312833165noreply@blogger.com33tag:blogger.com,1999:blog-7913068305301225566.post-27874841588692970012010-07-13T01:55:00.000-07:002010-07-13T01:55:03.264-07:00Turning off hibernate logging console output, How to hide/disable Hibernate log to console<span style="font-family: inherit;">Just sharing my experiance with Hibernate 3.0.</span><br />
<br />
<span style="font-family: inherit;">Even after using the log4j.xml with </span><br />
<br />
<logger name="org.hibernate"> <br />
<level value="info"/> <br />
</logger> <br />
<br />
<span style="font-family: inherit;"></span><br />
<span style="font-family: inherit;">I could not able to trun off the huge hibernate log on console, it was coming like this:</span><br />
<br />
<span style="font-family: inherit;">7 [main] INFO org.hibernate.cfg.annotations.Version - Hibernate Annotations 3.4.0.GA</span><br />
<span style="font-family: inherit;">37 [main] INFO org.hibernate.cfg.Environment - Hibernate 3.3.0.SP1</span><br />
<span style="font-family: inherit;">43 [main] INFO org.hibernate.cfg.Environment - hibernate.properties not found</span><br />
<span style="font-family: inherit;">48 [main] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist</span><br />
<span style="font-family: inherit;">52 [main] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling</span><br />
<span style="font-family: inherit;">163 [main] INFO org.hibernate.annotations.common.Version - Hibernate Commons Annotations 3.1.0.GA</span><br />
<span style="font-family: inherit;">168 [main] INFO org.hibernate.ejb.Version - Hibernate EntityManager 3.4.0.GA</span><br />
<span style="font-family: inherit;">202 [main] INFO org.hibernate.ejb.Ejb3Configuration - Processing PersistenceUnitInfo [</span><br />
<br />
<span style="font-family: inherit;">name: VMSPersistenceUnit</span><br />
<br />
<span style="font-family: inherit;">...]</span><br />
<br />
<span style="font-family: inherit;"></span><br />
<br />
<strong><span style="color: blue; font-family: inherit;">Finally I got solution and that is here:</span></strong><br />
<br />
<span style="font-family: inherit;">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.</span><br />
<br />
<span style="font-family: inherit;"></span><br />
<br />
<span style="font-family: inherit;">In my case, I have these jar files in my project classpath:</span><br />
<br />
<span style="font-family: inherit;"></span><br />
<span style="font-family: inherit;">slf4j-api-1.5.6.jar</span><br />
<span style="font-family: inherit;">slf4j-log4j12-1.5.6.jar</span><br />
<span style="font-family: inherit;">slf4j-simple-1.4.2.jar</span><br />
<br />
<span style="font-family: inherit;"></span><br />
<span style="font-family: inherit;">Thats it ...... :)</span>Ayush Java Solutionhttp://www.blogger.com/profile/06285300908312833165noreply@blogger.com0tag:blogger.com,1999:blog-7913068305301225566.post-8248576724572454532010-06-14T06:32:00.000-07:002010-06-14T06:32:50.028-07:00Check small java code on groovy consoleFor this tutorial, Groovy should be installed to your pc.<br />
For how to install Groovy and fundamental of Groovy, check <a href="http://ayushsuman.blogspot.com/2010/04/groovy-getting-started-how-use-groovy.html">here</a>.<br />
http://ayushsuman.blogspot.com/2010/04/groovy-getting-started-how-use-groovy.html<br />
<br />
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.<br />
<br />
If you have already configured your groovy bin folder with path then<br />
c:\>groovyConsole.bat<br />
It will open one window then you can paste your code<br />
<br />
String name = "BINOD KUMAR SUMAN";<br />
System.out.println("Name :: "+name);<br />
System.out.println("Now :: "+new Date());<br />
<br />
and press <strong>Ctrl+R</strong> and see your code result on below screen.<br />
Name :: BINOD KUMAR SUMAN<br />
Now :: Sat Jun 12 11:28:02 EEST 2010<br />
<br />
<strong>Ctrl+W</strong> for clear the output. Again you can check your some code. :)Ayush Java Solutionhttp://www.blogger.com/profile/06285300908312833165noreply@blogger.com0tag:blogger.com,1999:blog-7913068305301225566.post-70477799856803682812010-06-14T06:29:00.000-07:002010-06-14T06:29:19.831-07:00Get the fild value from java class during run time using reflectionGet the fild value from java class during run time using reflection.<br />
<br />
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.<br />
Like,<br />
<br />
public class Types<br />
{<br />
public static final int BIT = -7;<br />
public static final int TINYINT = -6;<br />
public static final int SMALLINT = 5;<br />
public static final int INTEGER = 4;<br />
public static final int BIGINT = -5;<br />
public static final int FLOAT = 6;<br />
public static final int REAL = 7;<br />
public static final int DOUBLE = 8;<br />
public static final int NUMERIC = 2;<br />
public static final int DECIMAL = 3;<br />
public static final int CHAR = 1;<br />
public static final int VARCHAR = 12;<br />
public static final int LONGVARCHAR = -1;<br />
public static final int DATE = 91;<br />
public static final int TIME = 92;<br />
public static final int TIMESTAMP = 93;<br />
}<br />
<br />
And you have one string that containg the "TINYINT" during run time, now you have to fetch what is the value of TINYINT dynamically.<br />
string filed = "TINYINT";<br />
<br />
String field = "TINYINT";<br />
Class typeClass = Class.forName("java.sql.Types");<br />
int fieldValue = (Integer) typeClass.getField(field).get(null);<br />
System.out.println("fieldValue :: "+fieldValue);<br />
<br />
<br />
Output:<br />
<br />
fieldValue :: -6Ayush Java Solutionhttp://www.blogger.com/profile/06285300908312833165noreply@blogger.com0tag:blogger.com,1999:blog-7913068305301225566.post-83103706925512788662010-06-08T13:23:00.000-07:002010-06-08T13:26:01.765-07:00First Struts Example with Hibernate, Hibernate and Spring first example1. Create one MyFirstStruts Web Dynamic Project (Say C:\workspaceAll\Struts\FirstStruts)<br />
<br />
2. Create JSP pages <br />
a) CustomerForm.jsp (C:\workspaceAll\Struts\MyFirstStruts\WebContent) <br />
b) Success.jsp (C:\workspaceAll\Struts\MyFirstStruts\WebContent\Success.jsp) <br />
<br />
3. Configuration Files <br />
a) web.xml (C:\workspaceAll\Struts\MyFirstStruts\WebContent\WEB-INF\web.xml) <br />
b) struts-config.xml (C:\workspaceAll\Struts\MyFirstStruts\WebContent\WEB-INF\struts-config.xml)<br />
c) hibernate.cfg.xml (C:\workspaceAll\Struts\MyFirstStruts\src\hibernate.cfg.xml)<br />
d) Customer.hbm.xml (C:\workspaceAll\Struts\MyFirstStruts\src\Customer.hbm.xml)<br />
<br />
4. Java Files <br />
a) CustomerForm.java (C:\workspaceAll\Struts\MyFirstStruts\src\CustomerForm.java) <br />
b) CustomerAction.java (C:\workspaceAll\Struts\MyFirstStruts\src\CustomerAction.java)<br />
c)Customer.java (C:\workspaceAll\Struts\MyFirstStruts\src\Customer.java)<br />
<br />
5. Put these jar files (C:\workspaceAll\Struts\MyFirstStruts\WebContent\WEB-INF\lib) <br />
a) commons-beanutils.jar <br />
b) commons-collections.jar <br />
c) commons-digester.jar<br />
d) commons-logging.jar <br />
e) struts.jar<br />
f) mysql-connector-java-3.1.12-bin.jar<br />
g) commons-logging-1.1.jar<br />
h) dom4j-1.6.1.jar<br />
i) commons-collections-3.2.jar<br />
j) log4j-1.2.15.jar<br />
k) slf4j-1.6.0/slf4j-1.6.0/slf4j-api-1.6.0.jar<br />
l) slf4j-1.6.0/slf4j-1.6.0/slf4j-log4j12-1.6.0.jar<br />
m) slf4j-1.6.0/slf4j-1.6.0/slf4j-simple-1.6.0.jar<br />
n) javassist-3.3.jar<br />
o) jta-1.0.1B.jar<br />
p) hibernate-commons-annotations-3.1.0.GA.jar<br />
q) hibernate-annotations-3.1beta8.jar<br />
r) hibernate-core-3.3.1.GA.jar<br />
s) antlr-2.7.5H3.jar<br />
<br />
6. Download and put struts-html.tld into C:\workspaceAll\Struts\MyFirstStruts\WebContent\WEB-INF\struts-html.tld<br />
(If you download struts-1.2.9-lib.zip, then struts-html.tld file is there)<br />
<br />
CustomerForm.jsp<br />
<%@ page contentType="text/html;charset=UTF-8" language="java" %><br />
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %><br />
<html:html xhtml="true"><br />
<body><br />
<html:form action="/submitCustomerForm"><br />
Put Customer First Name <html:text property="firstName" size="16" maxlength="16"/> <BR/><br />
Put Customer Last Name <html:text property="lastName" size="16" maxlength="16"/> <BR/> <P/><br />
<html:submit>Save</html:submit><br />
</html:form><br />
</body><br />
</html:html><br />
<br />
Success.jsp<br />
<html><br />
<h1> THIS IS SUCCESS PAGE </h1><br />
</html><br />
<br />
CustomerForm.java<br />
<br />
import org.apache.struts.action.ActionForm;<br />
public class CustomerForm extends ActionForm { <br />
private String firstName; <br />
private String lastName; <br />
public CustomerForm() { firstName = ""; lastName = ""; }<br />
public String getFirstName() { return firstName; }<br />
public void setFirstName(String s) { this.firstName = s; }<br />
public String getLastName() { return lastName; }<br />
public void setLastName(String s) { this.lastName = s; }<br />
}<br />
<br />
Customer.java<br />
<br />
<br />
/**<br />
* @author Binod Suman<br />
*/<br />
public class Customer {<br />
<br />
private int custId;<br />
private String firstName;<br />
private String lastName;<br />
public Customer(){}<br />
public int getCustId() {return custId;}<br />
public void setCustId(int custId) {this.custId = custId;}<br />
public String getFirstName() {return firstName;}<br />
public void setFirstName(String firstName) {this.firstName = firstName;}<br />
public String getLastName() {return lastName;}<br />
public void setLastName(String lastName) {this.lastName = lastName;}<br />
<br />
}<br />
<br />
<br />
<br />
CustomerAction.java<br />
<br />
import javax.servlet.http.HttpServletRequest;<br />
import javax.servlet.http.HttpServletResponse;<br />
import org.apache.struts.action.Action;<br />
import org.apache.struts.action.ActionForm;<br />
import org.apache.struts.action.ActionForward;<br />
import org.apache.struts.action.ActionMapping;<br />
<br />
public class CustomerAction extends Action {<br />
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { <br />
<br />
ActionForward nextPage = null;<br />
CustomerForm custForm = (CustomerForm) form;<br />
String firstName = custForm.getFirstName(); <br />
String lastName = custForm.getLastName();<br />
Customer customer = new Customer();<br />
customer.setFirstName(firstName);<br />
customer.setLastName(lastName);<br />
saveCustomer(customer);<br />
System.out.println("Customer First name is " + firstName); <br />
System.out.println("Customer Last name is " + lastName);<br />
nextPage = mapping.findForward("success");<br />
return nextPage; }<br />
<br />
public void saveCustomer(Customer customer){<br />
System.out.println("Inserting new customer record ...... ");<br />
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();<br />
Session session =sessionFactory.openSession();<br />
Transaction transaction = session.beginTransaction();<br />
session.save(customer);<br />
transaction.commit();<br />
session.flush();<br />
session.close();<br />
System.out.println("Customer record has been successfully saved ");<br />
}<br />
<br />
}<br />
<br />
web.xml<br />
<?xml version="1.0" encoding="ISO-8859-1"?><br />
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"><br />
<web-app><br />
<display-name>Hello World Struts Application</display-name><br />
<servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-<br />
<br />
name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet><br />
<servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <taglib> <taglib-uri>/WEB-INF/struts-<br />
<br />
html.tld</taglib-uri> <taglib-location>/WEB-INF/struts-html.tld</taglib-location> </taglib> </web-app><br />
<br />
struts-config.xml<br />
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"<br />
"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd"><struts-config> <form-beans> <form-bean name="myForm" type="CustomerForm" /> </form-beans><br />
<action-mappings> <action path="/submitCustomerForm" type="CustomerAction" name="myForm" scope="request"> <forward name="success" path="/Success.jsp" /> <br />
<br />
</action> </action-mappings><br />
</struts-config><br />
<br />
<br />
create table in mysql sumandb database.<br />
<br />
CREATE TABLE customer (<br />
id int(11) NOT NULL,<br />
firstName varchar(100) default NULL,<br />
secondName varchar(100) default NULL,<br />
PRIMARY KEY (id)<br />
)<br />
<br />
<br />
Start the server after deploy your application:<br />
<a href="http://localhost:8080/FirstStruts/CustomerForm.jsp">http://localhost:8080/FirstStruts/CustomerForm.jsp</a><br />
Put First Name: Binod<br />
Put Second Name: Suman<br />
Click on Save button and check the server console, you should be get<br />
Customer First name is Binod<br />
Customer Last name is Suman<br />
<br />
Check your sumandb database, one new record has been inserted. <br />
and new success page will come with message:<br />
THIS IS SUCCESS PAGEAyush Java Solutionhttp://www.blogger.com/profile/06285300908312833165noreply@blogger.com1tag:blogger.com,1999:blog-7913068305301225566.post-58364982467014206432010-06-08T06:21:00.000-07:002010-06-08T06:39:17.443-07:00How 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.<br />
<br />
Now I am going to show here how we can use preaparedstatement with spring JdbcOperations.<br />
<br />
<strong>Create these five file in your Eclipse project.</strong><br />
<br />
DaoOperation.java<br />
IDaoOperation.java<br />
App.java<br />
Myconfig.xml<br />
MyProperties.properties<br />
<br />
<strong>DaoOperation.java</strong><br />
<br />
import java.sql.SQLException;<br />
import java.util.Set;<br />
import javax.sql.DataSource;<br />
import org.springframework.jdbc.core.JdbcOperations;<br />
<br />
public class DaoOperation implements IDaoOperation{<br />
private JdbcOperations jdbc;<br />
public void saveStudentData() throws SQLException{<br />
String sql = "insert into student (id,name,marks) values (?,?,?)";<br />
Object[] args = {5,"Suman",99};<br />
executeUdpdateSQL(sql,args);<br />
}<br />
<br />
public void updateStudentData() throws SQLException{<br />
String sql = "update student set name=?, marks = ? where id = ?";<br />
Object[] args = {"Ayush Suman",999,5};<br />
executeUdpdateSQL(sql,args);<br />
}<br />
<br />
public void executeUdpdateSQL(String sql, Object[] args) throws SQLException {<br />
jdbc.update(sql, args);<br />
}<br />
<br />
public JdbcOperations getJdbc() {return jdbc;}<br />
public void setJdbc(JdbcOperations jdbc) {this.jdbc = jdbc;}<br />
<br />
}<br />
<br />
<strong>IDaoOperation.java</strong><br />
<br />
import java.sql.SQLException;<br />
/**<br />
* @author Binod Suman<br />
*/<br />
public interface IDaoOperation {<br />
public void saveStudentData() throws SQLException;<br />
public void updateStudentData() throws SQLException;<br />
}<br />
<br />
<strong>App.java</strong><br />
import org.springframework.context.ConfigurableApplicationContext;<br />
import org.springframework.context.support.ClassPathXmlApplicationContext;<br />
<br />
public class App {<br />
public static void main(String[] args) throws Exception {<br />
IDaoOperation daoOperation;<br />
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("Myconfig.xml");<br />
daoOperation = (IDaoOperation) context.getBean("daoOperation");<br />
daoOperation.saveStudentData();<br />
// daoOperation.updateStudentData();<br />
}<br />
<br />
}<br />
<br />
<br />
<strong>Myconfig.xml</strong><br />
<br />
<?xml version="1.0" encoding="utf-8"?><br />
<beans xmlns="http://www.springframework.org/schema/beans"<br />
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"<br />
xmlns:aop="http://www.springframework.org/schema/aop"<br />
xmlns:p="http://www.springframework.org/schema/p" <br />
xmlns:tx="http://www.springframework.org/schema/tx"<br />
xmlns:lang="http://www.springframework.org/schema/lang" <br />
xmlns:context="http://www.springframework.org/schema/context"<br />
xsi:schemaLocation="http://www.springframework.org/schema/beans<br />
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd<br />
http://www.springframework.org/schema/tx <br />
http://www.springframework.org/schema/tx/spring-tx-2.0.xsd<br />
http://www.springframework.org/schema/lang <br />
http://www.springframework.org/schema/lang/spring-lang-2.5.xsd<br />
http://www.springframework.org/schema/context <br />
http://www.springframework.org/schema/context/spring-context-2.5.xsd<br />
http://www.springframework.org/schema/aop <br />
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"> <br />
<context:mbean-server/><br />
<context:property-placeholder location="classpath:/MyProperties.properties"/><br />
<br />
<bean id="daoOperation" class="DaoOperation"<br />
p:jdbc-ref="jdbc" /><br />
<br />
<bean id="jdbc" class="org.springframework.jdbc.core.JdbcTemplate"<br />
p:dataSource-ref="dataSource" /><br />
<br />
<bean id="dataSource" destroy-method="close"<br />
class="org.apache.commons.dbcp.BasicDataSource" p:driverClassName="${db.driver}"<br />
p:url="${db.url}" p:username="${db.username}" p:password="${db.password}" /><br />
<br />
</beans><br />
<br />
<br />
<strong>MyProperties.properties</strong><br />
<br />
db.driver = com.mysql.jdbc.Driver<br />
db.url = jdbc:mysql://localhost/sumandb<br />
db.username = root<br />
db.password = mysqlAyush Java Solutionhttp://www.blogger.com/profile/06285300908312833165noreply@blogger.com3tag:blogger.com,1999:blog-7913068305301225566.post-67952951547280679382010-06-06T07:40:00.000-07:002012-10-19T05:50:08.977-07:00First Hibernate example, Hibernate getting started<div dir="ltr" style="text-align: left;" trbidi="on">
<span style="font-family: "Trebuchet MS", sans-serif;"></span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">No need to explain about Hibernate as it is well known ORM tool.</span> <br />
<br />
<span style="font-family: "Trebuchet MS", sans-serif;">One simple running example I am going to explain here. Just you follow step by step you would be able to run </span><span style="font-family: "Trebuchet MS", sans-serif;">your first Hibernate example. This example will contect mysql database.</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;"><br />
</span><br />
<span style="color: blue; font-family: "Trebuchet MS", sans-serif;"><strong>1. Download all below jar file.</strong></span><br />
<br />
<span style="font-family: "Trebuchet MS", sans-serif;">mysql-connector-java-3.1.12-bin.jar</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">commons-logging-1.1.jar</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">dom4j-1.6.1.jar</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">commons-collections-3.2.jar</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">log4j-1.2.15.jar</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">slf4j-api-1.6.0.jar</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">slf4j-log4j12-1.6.0.jar</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">slf4j-simple-1.6.0.jar</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">javassist-3.3.jar</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">jta-1.0.1B.jar</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">hibernate-commons-annotations-3.1.0.GA.jar</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">hibernate-annotations-3.1beta8.jar</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">hibernate-core-3.3.1.GA.jar</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">antlr-2.7.5H3.jar</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">javassist-3.3.jar</span><br />
<br />
<span style="font-family: "Trebuchet MS", sans-serif;">2. First create one project in Eclipse say <strong>FirstHibernate</strong> and add these jar file into that project.</span><br />
<br />
<span style="color: blue; font-family: "Trebuchet MS", sans-serif;"><strong>3. Create these below three file into your project src folder.</strong></span><br />
<br />
<span style="font-family: "Trebuchet MS", sans-serif;">hibernate.cfg.xml</span><br />
<br />
<span style="font-family: "Trebuchet MS", sans-serif;">Student.hbm.xml</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">Student.java</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">Client.java</span><br />
<br />
<span style="color: blue; font-family: "Trebuchet MS", sans-serif;"><strong>create one student table in database. In our example database name is sumandb.</strong></span><br />
<span style="font-family: "Trebuchet MS", sans-serif;"><br />
</span><br />
<span style="color: blue; font-family: "Trebuchet MS", sans-serif;"><em>CREATE TABLE student (</em></span><br />
<span style="color: blue; font-family: "Trebuchet MS", sans-serif;"><em>id int(11) NOT NULL,</em></span><br />
<span style="color: blue; font-family: "Trebuchet MS", sans-serif;"><em>name varchar(90) default NULL,</em></span><br />
<span style="color: blue; font-family: "Trebuchet MS", sans-serif;"><em>marks int(11) default NULL,</em></span><br />
<span style="color: blue; font-family: "Trebuchet MS", sans-serif;"><em>PRIMARY KEY (id)</em></span><br />
<span style="color: blue; font-family: "Trebuchet MS", sans-serif;"><em>)</em></span><br />
<br />
<span style="color: blue; font-family: "Trebuchet MS", sans-serif;"><strong>hibernate.cfg.xml</strong></span><br />
<br />
<?xml version='1.0' encoding='UTF-8'?><br />
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"><br />
<hibernate-configuration><br />
<session-factory><br />
<property name="connection.url">jdbc:mysql://localhost/sumandb</property><br />
<property name="connection.driver_class">com.mysql.jdbc.Driver</property><br />
<property name="dialect">org.hibernate.dialect.MySQLDialect</property><br />
<property name="connection.username">root</property><br />
<property name="connection.password">mysql</property><br />
<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property><br />
<!-- this will show us all sql statements --><br />
<property name="hibernate.show_sql">true</property> <br />
<!-- mapping files --><br />
<mapping resource="Student.hbm.xml" /><br />
</session-factory><br />
</hibernate-configuration><br />
<br />
<strong><span style="color: blue;">Student.hbm.xml</span></strong><br />
<span style="font-family: "Trebuchet MS", sans-serif;"></span><br />
<span style="font-family: "Trebuchet MS", sans-serif;"><mapping resource="Student.hbm.xml"></mapping></span><br />
<br />
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" ><br />
<hibernate-mapping><br />
<class name="Student" table="student"><br />
<id name="studentId" column="id"><br />
<generator class="increment" /><br />
</id><br />
<!-- Both property are optional here as property name and column name are same --><br />
<property name="name" column="name" /><br />
<property name="marks" column="marks" /><br />
</class><br />
</hibernate-mapping><br />
<br />
<span style="color: blue; font-family: "Trebuchet MS", sans-serif;"><strong>Student.java</strong></span> <br />
<span style="font-family: "Trebuchet MS", sans-serif;">/**</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">* @author Binod Suman</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">*/</span><br />
<br />
<span style="font-family: "Trebuchet MS", sans-serif;">public class Student {</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">private int studentId;</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">private String name;</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">private int marks;</span><br />
<br />
<span style="font-family: "Trebuchet MS", sans-serif;">public Student() { }</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;"><br />
</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">public Student(int studentId, String name, int marks) {</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">this.studentId = studentId;</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">this.name = name;</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">this.marks = marks;</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">}</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;"><br />
</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">public Student(String name, int marks) {</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">this.name = name;</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">this.marks = marks;</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">}</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;"><br />
</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;"><br />
</span><br />
<br />
<span style="font-family: "Trebuchet MS", sans-serif;"></span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">public int getStudentId() {</span><span style="font-family: "Trebuchet MS", sans-serif;">return studentId;</span><span style="font-family: "Trebuchet MS", sans-serif;">}</span> <br />
<span style="font-family: "Trebuchet MS", sans-serif;">public void setStudentId(int studentId) {</span><span style="font-family: "Trebuchet MS", sans-serif;">this.studentId = studentId;</span><span style="font-family: "Trebuchet MS", sans-serif;">}</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">public String getName() {</span><span style="font-family: "Trebuchet MS", sans-serif;">return name;</span><span style="font-family: "Trebuchet MS", sans-serif;">}</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">public void setName(String name) {</span><span style="font-family: "Trebuchet MS", sans-serif;">this.name = name;</span><span style="font-family: "Trebuchet MS", sans-serif;">}</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">public int getMarks() {</span><span style="font-family: "Trebuchet MS", sans-serif;">return marks;</span><span style="font-family: "Trebuchet MS", sans-serif;">}</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">public void setMarks(int marks) {</span><span style="font-family: "Trebuchet MS", sans-serif;">this.marks = marks;</span><span style="font-family: "Trebuchet MS", sans-serif;">}</span><br />
<br />
<span style="font-family: "Trebuchet MS", sans-serif;">}</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;"><br />
</span><br />
<span style="color: blue; font-family: "Trebuchet MS", sans-serif;"><strong>Client.java</strong></span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">import java.util.List;</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">import org.hibernate.Session;</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">import org.hibernate.SessionFactory;</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">import org.hibernate.Transaction;</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">import org.hibernate.cfg.AnnotationConfiguration;</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">/*</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">* @author Binod Suman</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">*/</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;"><br />
</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">public class Client {</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">public static void main(String[] args) {</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">Client test = new Client();</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">test.saveStudent();</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">// test.showAllStudent();</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">// test.searchStudent(2);</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">}</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;"><br />
</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">public void saveStudent(){</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">System.out.println("Inserting new Student record ...... ");</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">Session session =sessionFactory.openSession();</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">Transaction transaction = session.beginTransaction();</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">Student student = new Student("Binod Suman",99);</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">session.save(student);</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">transaction.commit();</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">session.flush();</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">session.close();</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">System.out.println("Student record has been successfully saved ");</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">}</span><br />
<br />
<span style="font-family: "Trebuchet MS", sans-serif;">public void showAllStudent(){</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">Session session =sessionFactory.openSession();</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">List<student> students = session.createQuery("from Student").list(); </student></span><br />
<br />
<span style="font-family: "Trebuchet MS", sans-serif;">for(Student student : students){</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">System.out.println("Student Name :: "+student.getName());</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">System.out.println("Student Roll :: "+student.getStudentId());</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">System.out.println("Student Marks :: "+student.getMarks());</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">System.out.println("************************");</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">}</span><br />
<br />
<span style="font-family: "Trebuchet MS", sans-serif;">}</span><br />
<br />
<span style="font-family: "Trebuchet MS", sans-serif;">public void searchStudent(int id){</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">Session session =sessionFactory.openSession();</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">Student student = (Student)session.load(Student.class, id);</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">System.out.println("Student Name :: "+student.getName());</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">System.out.println("Student Roll :: "+student.getStudentId());</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">System.out.println("Student Marks :: "+student.getMarks());</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">}</span><br />
<br />
<span style="font-family: "Trebuchet MS", sans-serif;">}</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;"></span><br />
<br />
<span style="font-family: Trebuchet MS;">Even if you are getting below exceptions, just you follow the above steps and add proper version of jar file, all your below exception be removed.</span><br />
<br />
Exception in thread "main" java.lang.NoSuchMethodError: org.slf4j.Logger.isTraceEnabled()Z<br />
<br />
<br />
Exception in thread "main" java.lang.IllegalAccessError: tried to access field org.hibernate.cfg.Configuration.xmlHelper from class org.hibernate.cfg.AnnotationConfiguration<br />
<br />
Exception in thread "main" java.lang.NoSuchFieldError: sqlResultSetMappings<br />
<br />
<span style="font-family: "Trebuchet MS", sans-serif;">That's it ........... :)</span><br />
<br />
<span style="font-family: Trebuchet MS;">Thanks ..... :)</span></div>
Ayush Java Solutionhttp://www.blogger.com/profile/06285300908312833165noreply@blogger.com121tag:blogger.com,1999:blog-7913068305301225566.post-1205909920483527392010-06-05T10:25:00.000-07:002010-06-05T11:04:58.472-07:00How to install Eclipse on Linux. Eclipse Galileo on Linux<span style="font-family: "Trebuchet MS", sans-serif;"></span><br />
<br />
<span style="font-family: "Trebuchet MS", sans-serif;">java should be installed before install the Eclipse. Just check</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">java -version</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;"><br />
</span><br />
<span style="color: blue; font-family: "Trebuchet MS", sans-serif;"><strong>Follow these steps to install Eclipse Galileo on linux.</strong></span><br />
<br />
<span style="font-family: "Trebuchet MS", sans-serif;">1. Download Eclipse for Linux from <a href="http://www.eclipse.org/downloads/">here</a>. </span><br />
<br />
<span style="font-family: "Trebuchet MS", sans-serif;">Choose Eclipse IDE for Java EE Developers (190 MB) Linux 32 bit. You will get eclipse-jee-galileo-SR2-linux-gtk.tar.gz is being save.</span><br />
<br />
<span style="font-family: "Trebuchet MS", sans-serif;">2. Save this file in your favorite location. In my case /home/binod</span><br />
<br />
<span style="font-family: "Trebuchet MS", sans-serif;">3. Run this below command</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">[root@localhost binod]# tar -xzvf eclipse-jee-galileo-SR2-linux-gtk.tar.gz</span><br />
<br />
<span style="font-family: "Trebuchet MS", sans-serif;">It will create directory eclipse in /home/binod</span><br />
<br />
<span style="font-family: "Trebuchet MS", sans-serif;">4. cd eclipse</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">[root@localhost binod]# cd eclipse</span><br />
<br />
<span style="font-family: "Trebuchet MS", sans-serif;">5. and start eclipse</span><br />
<strong>./eclipse</strong><br />
<br />
<br />
<span style="font-family: "Trebuchet MS", sans-serif;">If everything fine then you will get eclipse window and you can start the work</span><br />
<br />
<span style="font-family: "Trebuchet MS", sans-serif;"><strong>If you are getting below error:</strong></span><br />
<br />
<span style="font-family: "Trebuchet MS", sans-serif;">Warning: -XX:MaxPermSize=256m not understood. Ignoring.</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">Warning: -Xms40m not understood. Ignoring.</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">Warning: -Xmx512m not understood. Ignoring.</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">Warning: -jar not understood. Ignoring.</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">Exception in thread "main" java.lang.NoClassDefFoundError: </span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">.home.binod.eclipse.plugins.org.eclipse.equinox.launcher_1.0.201.R35x_v20090715.jar</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">at gnu.gcj.runtime.FirstThread.run() (/usr/lib/libgcj.so.5.0.0)</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">at _Jv_ThreadRun(java.lang.Thread) (/usr/lib/libgcj.so.5.0.0)</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">at _Jv_RunMain(java.lang.Class, byte const, int, byte const, boolean) (/usr/lib/libgcj.so.5.0.0)</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">at __gcj_personality_v0 (/home/binod/eclipse/java.version=1.4.2)</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">at __libc_start_main (/lib/tls/libc-2.3.4.so)</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">at _Jv_RegisterClasses (/home/binod/eclipse/java.version=1.4.2)</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;"><br />
</span><br />
<span style="color: blue; font-family: "Trebuchet MS", sans-serif;"><strong>SOLUTION here:</strong></span><br />
<br />
<span style="font-family: "Trebuchet MS", sans-serif;">check your JAVA_HOME using this below command</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">[root@localhost eclipse]# echo $JAVA_HOME</span><br />
<br />
<span style="font-family: "Trebuchet MS", sans-serif;">If you do not get result means your path does not set.</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">Then use this command to set JAVA_HOME path</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;"><br />
</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">[root@localhost eclipse]# export PATH=$PATH:/usr/java/jdk1.6.0_20/bin/</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">[root@localhost eclipse]# export JAVA_HOME=/usr/java/jdk1.6.0_20</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">In my case Java has been installed at /usr/java/jdk1.6.0_20</span><br />
<br />
<span style="font-family: "Trebuchet MS", sans-serif;">Now run this command to verify whether your path and JAVA_HOME is set proplery</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;"><br />
</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">echo $PATH</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">echo $JAVA_HOME</span><br />
<br />
<span style="font-family: "Trebuchet MS", sans-serif;">Now you can open eclipse using this below command</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;">[root@localhost eclipse]# <strong>./eclipse -vm /usr/java/jre1.6.0_20/bin</strong></span><br />
<br />
<span style="font-family: "Trebuchet MS", sans-serif;">That's it .......... :)</span><br />
<br />
<span style="font-family: "Trebuchet MS", sans-serif;">Thanks ...... :)</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;"><br />
</span><br />
<span style="font-family: "Trebuchet MS", sans-serif;"></span>Ayush Java Solutionhttp://www.blogger.com/profile/06285300908312833165noreply@blogger.com5tag:blogger.com,1999:blog-7913068305301225566.post-64108401108134593662010-06-04T01:24:00.000-07:002010-06-04T01:24:37.148-07:00Best waty to thread implementation in Java, Threads pools with the Executor FrameworkThreads were the first approach in Java to support concurrency. The usage of the threads has the following disadvantages. <br />
<br />
1. Creating a new thread causes some performance overhead <br />
2. Too many threads can lead to reduced performance, as the CPU needs to switch between these threads.<br />
3.You cannot easily control the number of threads, therefore you may run into out of memory errors due to too many threads. <br />
<br />
The java.util.concurrent package offers improved support for concurrency compared to threads. The java.util.concurrent package helps solving several of the isues with threads.<br />
<br />
<strong><span style="color: purple;">Threads pools with the Executor Framework</span></strong><br />
<br />
Thread pools manage a pool of worker threads. The thread pools contains a work queue which holds tasks waiting to get executed. A thread pool can be described as a collection of runnables (work queue) and a connections of running threads. These threads are constantly running and are checking the work query for new work. If there is new work to be done they execute this Runnable. The Thread class itself provides a method, e.g. execute (Runnable r) to add runnables to the work queue.<br />
<br />
The Executor framework provides example implementation of the java.util.concurrent.Executor interface, e.g. Executors.newFixedThreadPool(int n) which will create n worker threads. The ExecutorService adds lifecycle methods to the Executor, which allows to shutdown the Executor and to wait for termination.<br />
<br />
If you want to use one thread pool with one thread which executes several runnables you can use Executors.newSingleThreadExecutor();<br />
<br />
<strong>Create two java files:</strong><br />
<br />
<strong>MyRunnable.java</strong><br />
<br />
package com.suman;<br />
<br />
/**<br />
* @author Binod Suman<br />
*/<br />
public class MyRunnable implements Runnable {<br />
private final String sql;<br />
<br />
MyRunnable(String sql) {this.sql = sql;}<br />
<br />
@Override<br />
public void run() {<br />
long sum = 0;<br />
for (long i = 1; i < 5; i++) {<br />
System.out.println(sql);<br />
try {<br />
Thread.sleep(200);<br />
} catch (InterruptedException e) {<br />
e.printStackTrace();<br />
}<br />
}<br />
}<br />
}<br />
<br />
<strong>App.java</strong><br />
<br />
package com.suman;<br />
<br />
import java.util.ArrayList;<br />
import java.util.List;<br />
import java.util.concurrent.Callable;<br />
import java.util.concurrent.ExecutionException;<br />
import java.util.concurrent.ExecutorService;<br />
import java.util.concurrent.Executors;<br />
import java.util.concurrent.Future;<br />
<br />
public class App <br />
{<br />
private static final int noOfThreadInPool = 10;<br />
public static void main( String[] args )<br />
{<br />
ExecutorService executor = Executors.newFixedThreadPool(noOfThreadInPool);<br />
String sql="sql";<br />
List<future<list>> list = new ArrayList<future<list>>();<br />
for (int i = 1; i <=5; i++) {<br />
if(i==1)sql="FIRST";<br />
if(i==2)sql="SECOND";<br />
if(i==3)sql="THIRD";<br />
if(i==4)sql="FOURTH";<br />
if(i==5)sql="FIFTH";<br />
<br />
<strong>Runnable worker = new MyRunnable(sql);</strong><br />
<strong>executor.execute(worker);</strong><br />
}<br />
<br />
// This will make the executor accept no new threads<br />
// and finish all existing threads in the queue<br />
<br />
<strong>executor.shutdown(); // Very Important</strong><br />
<br />
// Wait until all threads are finish<br />
<br />
while (!executor.isTerminated()) {}<br />
<br />
System.out.println("Finished all threads");<br />
}<br />
}<br />
<br />
<br />
The main benefit of Executors Framework that you no need to manage thread yourself. Here you can give how many thread maximum do you want to generate in threadpool.<br />
<br />
private static final int noOfThreadInPool= 10;<br />
ExecutorService executor = Executors.newFixedThreadPoolnoOfThreadInPool<br />
<br />
If you give noOfThreadInPool=5 then it will only create 5 thread to threadpool and you request for 6th thread to call executor.execute(worker); then it has to finish until one thread will free.<br />
<br />
How you will use this in your project.<br />
<br />
Suppose if you have one fixed work that you have to execute 10 times then make that method inside the MyRunnbale.java and put that method in run() method and call <br />
<br />
Runnable worker = new MyRunnable(sql);<br />
executor.execute(worker);<br />
<br />
10 times.<br />
<br />
But you can not return any value from MyRunnable class as run() method return type is void. <br />
<br />
In case you expect your threads to return a computed result you can use java.util.concurrent.Callable. Callables allow to return values after competition. Callable uses generic to define the type of object which is returned.<br />
If you submit a callable to an executor the framework returns a java.util.concurrent.Future. This futures can be used to check the status of a callable and to retrieve the result from the callable. <br />
<br />
On the executor you can use the method submit to submit a Callable and to get a future. To retrieve the result of the future use the get() method.<br />
<br />
<strong>Future and Collable Example </strong><br />
Create one more java file <br />
<br />
<strong>MyCallable.java</strong><br />
<br />
package com.suman;<br />
<br />
import java.util.ArrayList;<br />
import java.util.List;<br />
import java.util.concurrent.Callable;<br />
<br />
/**<br />
* @author Binod Suman<br />
*/<br />
<br />
public class MyCallable implements Callable<list> {<br />
private final String sql;<br />
<br />
MyCallable(String sql) {this.sql = sql;}<br />
<br />
@Override<br />
public List call() throws Exception {<br />
long sum = 0;<br />
List<string> list = new ArrayList<string>();<br />
for (long i = 1; i < 6; i++) {<br />
System.out.println(sql);<br />
list.add(sql+i);<br />
try {<br />
Thread.sleep(200);<br />
} catch (InterruptedException e) {<br />
e.printStackTrace();<br />
}<br />
}<br />
return list;<br />
}<br />
}<br />
<br />
<br />
And do some change in <strong>App.java</strong><br />
<br />
package com.suman;<br />
<br />
import java.util.ArrayList;<br />
import java.util.List;<br />
import java.util.concurrent.Callable;<br />
import java.util.concurrent.ExecutionException;<br />
import java.util.concurrent.ExecutorService;<br />
import java.util.concurrent.Executors;<br />
import java.util.concurrent.Future;<br />
<br />
public class App <br />
{<br />
private static final int noOfThreadInThreadPool = 10;<br />
<br />
public static void main( String[] args )<br />
{<br />
ExecutorService executor = Executors.newFixedThreadPool(noOfThreadInThreadPool);<br />
String sql="sql";<br />
List<future<list>> list = new ArrayList<future<list>>();<br />
for (int i = 1; i <=5; i++) {<br />
if(i==1)sql="FIRST";<br />
if(i==2)sql="SECOND";<br />
if(i==3)sql="THIRD";<br />
if(i==4)sql="FOURTH";<br />
if(i==5)sql="FIFTH";<br />
<br />
// Runnable worker = new MyRunnable(sql);<br />
// executor.execute(worker);<br />
<br />
Callable<list> worker = new MyCallable(sql);<br />
Future<list> submit = executor.submit(worker);<br />
list.add(submit);<br />
}<br />
<br />
<br />
// To see the result<br />
for (Future<list> future : list) {<br />
try {<br />
List list2 = future.get();<br />
System.out.println("ALL LIST:: "+list2);<br />
} catch (InterruptedException e) {<br />
e.printStackTrace();<br />
} catch (ExecutionException e) {<br />
e.printStackTrace();<br />
}<br />
<br />
}<br />
<br />
<br />
<br />
// This will make the executor accept no new threads<br />
// and finish all existing threads in the queue<br />
executor.shutdown();<br />
// Wait until all threads are finish<br />
while (!executor.isTerminated()) {}<br />
<br />
System.out.println("Finished all threads");<br />
}<br />
}<br />
<br />
I think, it is best way to use the thread. Your suggestions or question is always most welcom. :)<br />
<br />
Thanks ........... :)<br />
<br />
source: http://www.vogella.de/articles/JavaConcurrency/article.html#threadpools<br />
<br />
<br />
<br />
<br />
<br />
Ayush Java Solutionhttp://www.blogger.com/profile/06285300908312833165noreply@blogger.com0tag:blogger.com,1999:blog-7913068305301225566.post-79917844543806855012010-06-04T00:00:00.000-07:002010-06-04T00:14:34.188-07:00JPA One to Many and Many to One easy examplePlease follow two previous posting on JPA for basic start<br />
1. <a href="http://www.blogger.com/">JPA getting started, easy example of JPA, JPA annotation example, JPA with Hibernate</a><br />
2. <a href="http://ayushsuman.blogspot.com/2010/06/configure-jpa-during-run-time-dynamic.html">Configure JPA during run time, dynamic JPA Configuration using Spring context</a><br />
<br />
<strong>Now OnetoMany and ManytoOne Example.</strong><br />
<br />
<br />
Suppose company has many employee. So during saving of company we can save employee also and during fetching company record we can fetch employee records also.<br />
<br />
Create one <strong>Employee.java</strong><br />
<br />
package com.suman;<br />
import javax.persistence.Column;<br />
import javax.persistence.Entity;<br />
import javax.persistence.Id;<br />
import javax.persistence.JoinColumn;<br />
import javax.persistence.ManyToOne;<br />
import javax.persistence.Table;<br />
<br />
/**<br />
* @author Binod Suman<br />
*/<br />
<br />
@Entity<br />
@Table(name="blogemployee")<br />
public class Employee {<br />
<br />
@Id<br />
private int id;<br />
@Column(name="cid")<br />
private int companyId;<br />
private String name;<br />
private String designation;<br />
<br />
@ManyToOne<br />
@JoinColumn(name="cid",nullable=false, insertable=false, updatable=false)<br />
private Company company;<br />
// cid column should be there in company table.<br />
public Employee() { }<br />
public Employee(int companyId, String name, String designation) {<br />
super();<br />
this.companyId = companyId;<br />
this.name = name;<br />
this.designation = designation;<br />
}<br />
<br />
public Employee(int id, int companyId, String name, String designation) {<br />
super();<br />
this.id = id;<br />
this.companyId = companyId;<br />
this.name = name;<br />
this.designation = designation;<br />
}<br />
<br />
public int getId() {return id;}<br />
public void setId(int id) {this.id = id;}<br />
public int getCompanyId() {return companyId;}<br />
public void setCompanyId(int companyId) {this.companyId = companyId;}<br />
public String getName() {return name;}<br />
public void setName(String name) {this.name = name;}<br />
public String getDesignation() {return designation;}<br />
public void setDesignation(String designation) {this.designation = designation;}<br />
public Company getCompany() {return company;}<br />
public void setCompany(Company company) {this.company = company;}<br />
}<br />
<br />
<br />
<strong>Company.java</strong><br />
<br />
package com.suman;<br />
import java.util.List;<br />
import javax.persistence.CascadeType;<br />
import javax.persistence.Column;<br />
import javax.persistence.Entity;<br />
import javax.persistence.FetchType;<br />
import javax.persistence.Id;<br />
import javax.persistence.JoinColumn;<br />
import javax.persistence.OneToMany;<br />
import javax.persistence.Table;<br />
import javax.persistence.Transient;<br />
import org.apache.log4j.Logger;<br />
import org.hibernate.annotations.LazyCollection;<br />
import org.hibernate.annotations.LazyCollectionOption;<br />
import org.hibernate.annotations.OptimisticLock;<br />
<br />
/**<br />
* @author Binod Suman<br />
*/<br />
<br />
@Entity<br />
@Table(name="blogcompany")<br />
public class Company {<br />
<br />
@Id<br />
private int id;<br />
@Column(name="cname")<br />
private String name;<br />
private String city;<br />
<br />
@OneToMany(cascade = CascadeType.PERSIST, mappedBy = "company") <br />
private List<employee> employees;<br />
@Transient<br />
Logger log = Logger.getLogger(Company.class);<br />
// Use Transient if you dont want to mapping your java bean to database table column.<br />
public Company(){};<br />
public Company(String name, String city) {<br />
super();<br />
this.name = name;<br />
this.city = city;<br />
}<br />
<br />
public Company(int id, String name, String city) {<br />
super();<br />
this.id = id;<br />
this.name = name;<br />
this.city = city;<br />
}<br />
<br />
public int getId() {return id;}<br />
public void setId(int id) {this.id = id;}<br />
public String getName() {return name;}<br />
public void setName(String name) {this.name = name;}<br />
public String getCity() {return city;}<br />
public void setCity(String city) {this.city = city;}<br />
public List<employee> getEmployees() {return employees;}<br />
public void setEmployees(List<employee> employees) {this.employees = employees;}<br />
}<br />
<br />
<br />
<strong>TestApplication.java</strong><br />
<br />
<br />
package com.suman;<br />
import java.util.ArrayList;<br />
import java.util.HashMap;<br />
import java.util.List;<br />
import java.util.Map;<br />
import javax.persistence.EntityManager;<br />
import javax.persistence.EntityManagerFactory;<br />
import javax.persistence.Persistence;<br />
import javax.persistence.Query;<br />
import org.apache.log4j.Logger;<br />
<br />
/**<br />
* @author Binod Suman<br />
*/<br />
<br />
public class TestApplication {<br />
Logger log = Logger.getLogger(TestApplication.class);<br />
EntityManagerFactory emf;<br />
EntityManager em;<br />
<br />
public static void main(String[] args) {<br />
TestApplication test = new TestApplication();<br />
test.configureEntityManager();<br />
// test.saveCompany();<br />
// test.fetchCompanyData();<br />
// test.saveCompanyAndEmployee();<br />
test.fetchCompanyAndEmployee();<br />
}<br />
<br />
public void configureEntityManager(){<br />
Map properties = new HashMap();<br />
properties.put("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");<br />
properties.put("hibernate.connection.url", "jdbc:mysql://localhost:3306/sumandb");<br />
properties.put("hibernate.connection.username", "root");<br />
properties.put("hibernate.connection.password", "mysql");<br />
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");<br />
properties.put("hibernate.show-sql", "true");<br />
properties.put("hibernate.format_sql", "true");<br />
//emf = Persistence.createEntityManagerFactory("jpablogPUnit");<br />
emf = Persistence.createEntityManagerFactory("jpablogPUnit",properties);<br />
em = emf.createEntityManager();<br />
}<br />
<br />
public void saveCompany(){<br />
log.info("Company data is going to save");<br />
EntityManager entityManager = (EntityManager) emf.createEntityManager();<br />
entityManager.getTransaction().begin();<br />
Company company = new Company(120,"TecnoTree","Espoo, Finland");<br />
entityManager.persist(company);<br />
entityManager.getTransaction().commit();<br />
log.info("Company data has been saved");<br />
}<br />
<br />
public void saveCompanyAndEmployee(){<br />
log.info("Company and Employee data are going to save");<br />
EntityManager entityManager = (EntityManager) emf.createEntityManager();<br />
entityManager.getTransaction().begin();<br />
Company company = new Company(145,"TecnoTree","Finland");<br />
List<employee> employees = new ArrayList<employee>();<br />
Employee employee = new Employee(10,145,"Binod","Project Manager");<br />
// entityManager.persist(employee);<br />
employees.add(employee);<br />
employee = new Employee(11,145,"Binod Suman","Team Leader");<br />
employees.add(employee);<br />
company.setEmployees(employees);<br />
entityManager.persist(company);<br />
entityManager.getTransaction().commit();<br />
log.info("Company and Employee data have been saved");<br />
}<br />
<br />
public void fetchCompanyData(){<br />
Query query = em.createQuery("SELECT c FROM Company c");<br />
List<company> list = (List<company>) query.getResultList();<br />
log.info(list);<br />
for (Company company : list) {<br />
log.info("Company Name :: "+company.getName());<br />
log.info("Company City :: "+company.getCity());<br />
log.info("***************************");<br />
}<br />
}<br />
<br />
<br />
public void fetchCompanyAndEmployee(){<br />
Query query = em.createQuery("SELECT c FROM Company c");<br />
List<company> list = (List<company>) query.getResultList();<br />
log.info(list);<br />
for (Company company : list) {<br />
log.info("Company Name :: "+company.getName());<br />
log.info("Company City :: "+company.getCity());<br />
log.info("Company Id :: "+company.getId());<br />
List<employee> employees = company.getEmployees();<br />
log.info("Employees.size() :: "+employees.size());<br />
for(Employee employee : employees){<br />
log.info("Employee Name :: "+employee.getName());<br />
log.info("Employee Designation :: "+employee.getDesignation());<br />
}<br />
log.info("***************************");<br />
}<br />
}<br />
<br />
}<br />
<br />
<strong>Some time if you have father -> child -> child mapping then it doest not work properly then use this below mapping in father and his child java bean.</strong><br />
<br />
@OneToMany(cascade = CascadeType.PERSIST, mappedBy = "company") <br />
<strong>@LazyCollection(LazyCollectionOption.FALSE) </strong><br />
private List<employee> employees;<br />
<br />
If you have question and doubt then please give your comment or if you have any feedback.<br />
<br />
<br />
Thanks .......... :)Ayush Java Solutionhttp://www.blogger.com/profile/06285300908312833165noreply@blogger.com18tag:blogger.com,1999:blog-7913068305301225566.post-65779886593955157232010-06-03T10:15:00.000-07:002010-06-03T10:35:02.297-07:00Configure JPA during run time, dynamic JPA Configuration using Spring contextYou can set the database information during run time. Then remove all the database specific stuff<br />
from persistance.xml and use Hash properties in your java class.<br />
<br />
1. Removed all your database properties from persistance.xml<br />
<persistence><br />
<persistence-unit name="jpablogPUnit" transaction-type="RESOURCE_LOCAL"><br />
<class>com.suman.Company</class><br />
</persistence-unit><br />
</persistence><br />
<br />
2. Changed your java file where you are configuring entityManager, in our case TestApplication.java<br />
<br />
<br />
package com.suman;<br />
<br />
import java.util.HashMap;<br />
import java.util.Map;<br />
import javax.persistence.EntityManager;<br />
import javax.persistence.EntityManagerFactory;<br />
import javax.persistence.Persistence;<br />
import org.apache.log4j.Logger;<br />
<br />
/**<br />
* @author Binod Suman<br />
*/<br />
public class TestApplication {<br />
<br />
Logger log = Logger.getLogger(TestApplication.class);<br />
public static void main(String[] args) {<br />
TestApplication test = new TestApplication();<br />
test.saveCompany();<br />
}<br />
<br />
public void saveCompany(){<br />
log.info("Company data is going to save");<br />
EntityManagerFactory emf;<br />
Map properties = new HashMap();<br />
properties.put("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");<br />
properties.put("hibernate.connection.url", "jdbc:mysql://localhost:3306/sumandb");<br />
properties.put("hibernate.connection.username", "root");<br />
properties.put("hibernate.connection.password", "mysql");<br />
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");<br />
properties.put("hibernate.show-sql", "true");<br />
//emf = Persistence.createEntityManagerFactory("jpablogPUnit");<br />
emf = Persistence.createEntityManagerFactory("jpablogPUnit",properties);<br />
EntityManager entityManager = (EntityManager) emf.createEntityManager();<br />
entityManager.getTransaction().begin();<br />
Company company = new Company(120,"TecnoTree","Espoo, Finland");<br />
entityManager.persist(company);<br />
entityManager.getTransaction().commit();<br />
log.info("Company data has been saved");<br />
}<br />
<br />
}<br />
<br />
<strong>Now run the application.</strong><br />
One more record has been inserted.<br />
<br />
How to fetch data using JPA<br />
<br />
Change the code of <strong>TestApplcation.java</strong><br />
<br />
package com.suman;<br />
<br />
import java.util.HashMap;<br />
import java.util.List;<br />
import java.util.Map;<br />
<br />
import javax.persistence.EntityManager;<br />
import javax.persistence.EntityManagerFactory;<br />
import javax.persistence.Persistence;<br />
import javax.persistence.Query;<br />
<br />
import org.apache.log4j.Logger;<br />
<br />
/**<br />
* @author Binod Suman<br />
*/<br />
public class TestApplication {<br />
<br />
Logger log = Logger.getLogger(TestApplication.class);<br />
EntityManagerFactory emf;<br />
EntityManager em;<br />
<br />
public static void main(String[] args) {<br />
TestApplication test = new TestApplication();<br />
test.configureEntityManager();<br />
// test.saveCompany();<br />
test.fetchCompanyData();<br />
}<br />
<br />
public void configureEntityManager(){<br />
Map properties = new HashMap();<br />
properties.put("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");<br />
properties.put("hibernate.connection.url", "jdbc:mysql://localhost:3306/sumandb");<br />
properties.put("hibernate.connection.username", "root");<br />
properties.put("hibernate.connection.password", "mysql");<br />
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");<br />
properties.put("hibernate.show-sql", "true");<br />
//emf = Persistence.createEntityManagerFactory("jpablogPUnit");<br />
emf = Persistence.createEntityManagerFactory("jpablogPUnit",properties);<br />
em = emf.createEntityManager();<br />
}<br />
<br />
public void saveCompany(){<br />
log.info("Company data is going to save");<br />
EntityManager entityManager = (EntityManager) emf.createEntityManager();<br />
entityManager.getTransaction().begin();<br />
Company company = new Company(120,"TecnoTree","Espoo, Finland");<br />
entityManager.persist(company);<br />
entityManager.getTransaction().commit();<br />
log.info("Company data has been saved");<br />
}<br />
<br />
public void fetchCompanyData(){<br />
Query query = em.createQuery("SELECT c FROM Company c");<br />
List<Company> list = (List<Company>) query.getResultList();<br />
log.info(list);<br />
<br />
for (Company company : list) {<br />
log.info("Company Name :: "+company.getName());<br />
log.info("Company City :: "+company.getCity());<br />
log.info("***************************");<br />
}<br />
}<br />
}<br />
<br />
<br />
<strong><span style="color: purple;">You can configure the EntityManagerFactory from spring configuration file also.</span></strong><br />
<br />
<bean id="entityManagerFactory"<br />
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"<br />
lazy-init="false"><br />
<property name="persistenceUnitName" value="VMSPersistenceUnit" /><br />
<property name="dataSource" ref="sourceDataSource" /><br />
<property name="loadTimeWeaver"><br />
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" /><br />
</property><br />
</bean><br />
<br />
<strong><span style="color: purple;">If you want to configure entityManagerFactory during runt time then use these code. As if you dont have database name and information then you can not use the spring context for entityManagerFactory.</span></strong><br />
<br />
<br />
private EntityManagerFactory entityManagerFactory;<br />
private JpaTemplate jpaTemplate;<br />
<br />
<br />
LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean();<br />
bean.setDataSource(sourceDataSource);<br />
bean.afterPropertiesSet();<br />
entityManagerFactory = bean.getObject();<br />
log.info("entityManagerFactory :: " + entityManagerFactory);<br />
this.jpaTemplate = new JpaTemplate(this.entityManagerFactory);<br />
<br />
<strong>Even you can fetch record in batch wise manner also. </strong><br />
Use this below code:<br />
public Collection fetchQueryListFromSourceDatabaseForSubscriber(final String sql,final int firstPosition, final int numberOfRecords) throws DataAccessException {<br />
return (Collection) this.jpaTemplate.execute(new JpaCallback() {<br />
public Object doInJpa(EntityManager em) throws PersistenceException {<br />
Query query = em.createQuery(sql);<br />
query.setFirstResult(firstPosition); <br />
query.setMaxResults(numberOfRecords);<br />
List result = query.getResultList(); <br />
return result;<br />
}<br />
});<br />
}<br />
<br />
If will fetch record from firstPosition and number of record will be numberOfRecords.<br />
A persistence provider may or may not optimize access to database using database specific limit clause, like select * from table limit 10,<br />
<br />
Then in TestApplication.java<br />
<br />
public Collection fetchQueryListFromSourceDatabase(final String sql) throws DataAccessException {<br />
return (Collection) this.jpaTemplate.execute(new JpaCallback() {<br />
public Object doInJpa(EntityManager em) throws PersistenceException {<br />
Query query = em.createQuery(sql);<br />
List result = query.getResultList(); <br />
log.info("FINALLY JPA WORKING :: "+result.size());<br />
return result;<br />
}<br />
});<br />
}<br />
<br />
Please feedback to improve this tutorial ....... :)<br />
<br />
Thanks :)Ayush Java Solutionhttp://www.blogger.com/profile/06285300908312833165noreply@blogger.com26tag:blogger.com,1999:blog-7913068305301225566.post-23221702980446548942010-05-22T06:36:00.000-07:002010-06-04T00:01:58.624-07:00JPA getting started, easy example of JPA, JPA annotation example, JPA with Hibernate<strong><span style="color: #990000;">Very basic example of how to implement JPA using hibernate provider for mysql database.</span></strong><br />
<br />
Create one project in Eclipse (say JPABlogTestHibernate) add these jar files.<br />
<br />
1. log4j-1.2.15.jar<br />
2. mysql-connector-java-3.1.12-bin.jar<br />
3. persistence-api-1.0.jar<br />
4. slf4j-simple-1.4.2.jar<br />
5. cglib-2.1_3.jar<br />
6. cglib-asm-1.0.jar<br />
7. commons-collections-3.2.jar<br />
8. commons-logging-1.1.jar<br />
9. hibernate-core-3.3.1.GA.jar<br />
10. hibernate-entitymanager-3.3.1.ga.jar<br />
11. javassist-3.3.jar<br />
12. jta-1.0.1B.jar<br />
13. jboss-archive-browsing-5.0.0alpha-200607201-119.jar<br />
14. dom4j-1.6.1.jar<br />
15. slf4j-api-1.4.2.jar<br />
16. hibernate-tools-3.2.0.beta9a.jar<br />
17. hibernate-annotations-3.4.0.GA.jar<br />
18. hibernate-commons-annotations-3.1.0.GA.jar<br />
19. antlr-2.7.7.jar<br />
<br />
Create one persistence.xml inside src\META-INF folder.<br />
create one package inside src say com.suman<br />
Add these files<br />
<br />
Company.java<br />
TestApplication.java<br />
<span style="color: black;">persistence.xml</span><br />
<class><br />
log4j.xml inside src folder<br />
<br />
<strong><span style="color: #990000;">Company.java (src\com\suman)</span></strong><br />
<br />
package com.suman;<br />
import javax.annotation.Generated;<br />
import javax.persistence.Column;<br />
import javax.persistence.Entity;<br />
import javax.persistence.GeneratedValue;<br />
import javax.persistence.Id;<br />
import javax.persistence.Table;<br />
import javax.persistence.Transient;<br />
import org.apache.log4j.Logger;<br />
<br />
/**<br />
* @author Binod Suman<br />
*/<br />
<br />
@Entity<br />
@Table(name="blogcompany")<br />
public class Company {<br />
@Id<br />
private int id;<br />
@Column(name="cname")<br />
private String name;<br />
private String city;<br />
<br />
@Transient<br />
Logger log = Logger.getLogger(Company.class);<br />
<br />
public Company(){};<br />
<br />
public Company(String name, String city) {<br />
super();<br />
this.name = name;<br />
this.city = city;<br />
}<br />
<br />
public Company(int id, String name, String city) {<br />
super();<br />
this.id = id;<br />
this.name = name;<br />
this.city = city;<br />
}<br />
<br />
public int getId() {<br />
return id;<br />
}<br />
<br />
public void setId(int id) {<br />
this.id = id;<br />
}<br />
<br />
public String getName() {<br />
return name;<br />
}<br />
<br />
public void setName(String name) {<br />
this.name = name;<br />
}<br />
<br />
public String getCity() {<br />
return city;<br />
}<br />
<br />
<br />
public void setCity(String city) {<br />
this.city = city;<br />
}<br />
<br />
}<br />
<br />
<br />
<strong><span style="color: #990000;">TestApplication.java (src\com\suman)</span></strong><br />
package com.suman;<br />
import javax.persistence.EntityManager;<br />
import javax.persistence.EntityManagerFactory;<br />
import javax.persistence.Persistence;<br />
import org.apache.log4j.Logger;<br />
<br />
/**<br />
* @author Binod Suman<br />
*/<br />
<br />
public class TestApplication {<br />
Logger log = Logger.getLogger(TestApplication.class);<br />
public static void main(String[] args) {<br />
TestApplication test = new TestApplication();<br />
test.saveCompany();<br />
}<br />
<br />
public void saveCompany(){<br />
log.info("Company data is going to save");<br />
EntityManagerFactory emf;<br />
emf = Persistence.createEntityManagerFactory("jpablogPUnit");<br />
EntityManager entityManager = (EntityManager) emf.createEntityManager();<br />
entityManager.getTransaction().begin();<br />
Company company = new Company(110,"TecnoTree","Bangalore");<br />
entityManager.persist(company);<br />
entityManager.getTransaction().commit();<br />
log.info("Company data has been saved");<br />
}<br />
}<br />
<br />
<br />
<strong>Create database table blogcompany inside the sumandb database.</strong><br />
CREATE TABLE blogcompany (<br />
id int(11) NOT NULL,<br />
cname varchar(100) default NULL,<br />
city varchar(100) default NULL,<br />
PRIMARY KEY (id)<br />
)<br />
<br />
Now you can run the TestApplication.java and see the log on console<br />
One record has been inserted into blogcompany table.<br />
<br />
That's easy ............ :)<br />
<br />
If you have question and doubt then please give your comment or if you have any feedback.<br />
<br />
Thanks .......... :)Ayush Java Solutionhttp://www.blogger.com/profile/06285300908312833165noreply@blogger.com23tag:blogger.com,1999:blog-7913068305301225566.post-66235092331504878452010-05-15T10:29:00.000-07:002010-05-15T10:29:37.589-07:00Spring Transaction using JDBCTemplate, Spring Transaction easy exampleHere I am going to show very easy example of Spring jdbcTemplate transaction. First I will write one small example to save data into mysql database without handling any transaction then we will solve problem with use of Spring transation.<br />
<br />
Create one project (JDBCTemplateTransaction) in eclipse and add these below mentioned external jar:<br />
<br />
1. spring-2.5.6.jar<br />
2. mysql-connector-java-5.1.9.jar<br />
3. log4j-1.2.15.jar<br />
4. commons-logging-1.0.4.jar<br />
5. commons-dbcp-1.2.2.jar<br />
6. commons-pool-1.3.jar<br />
<br />
Create one package in src folder say com.suman and add these java files.<br />
1. App.java<br />
2. IDaoOperation.java (Interface)<br />
3. DaoOperation.java <br />
<br />
All the code are below.<br />
<br />
Create three file inside the src folder<br />
1. project-config.properties<br />
2. project-config.xml<br />
3. log4j.xml<br />
<br />
******** code section ************<br />
<b>App.java</b><br />
<br />
package com.suman;<br />
<br />
import org.apache.log4j.Logger;<br />
import org.springframework.context.ConfigurableApplicationContext;<br />
import org.springframework.context.support.ClassPathXmlApplicationContext;<br />
<br />
public class App <br />
{<br />
public static void main( String[] args )<br />
{<br />
Logger log = Logger.getLogger(App.class);<br />
IDaoOperation daoOperation;<br />
log.info( "Check Spring Transaction using jdbcTemplate" );<br />
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("project-config.xml");<br />
daoOperation = (IDaoOperation) context.getBean("daoOperation");<br />
daoOperation.saveStudent();<br />
log.info("THIS IS MAIN METHOD OF SPRING TEST");<br />
}<br />
}<br />
<br />
<strong>IDaoOperation.java</strong> <br />
<br />
package com.suman;<br />
/**<br />
* @author Binod Suman<br />
*/<br />
public interface IDaoOperation {<br />
<br />
public void saveStudent();<br />
<br />
}<br />
<br />
<br />
<strong>DaoOperation.java </strong><br />
<br />
package com.suman;<br />
<br />
import java.io.IOException;<br />
import java.sql.SQLException;<br />
import java.util.Collection;<br />
<br />
import javax.sql.DataSource;<br />
<br />
import org.apache.log4j.Logger;<br />
import org.springframework.jdbc.core.JdbcOperations;<br />
<br />
/**<br />
* @author Binod Suman<br />
*/<br />
public class DaoOperation implements IDaoOperation{<br />
<br />
private DataSource dataSource;<br />
private Logger log;<br />
private JdbcOperations jdbc;<br />
<br />
public void saveStudent(){<br />
String sql = "insert into student (id,name,roll) values (1,'Binod',110)";<br />
executeSQL(sql);<br />
saveHostel();<br />
}<br />
<br />
public void saveHostel(){<br />
String sql = "insert into hostel (id,name,roll) values (1,'Yamuna',1)";<br />
executeSQL(sql);<br />
}<br />
<br />
<br />
public DataSource getDataSource() {<br />
return dataSource;<br />
}<br />
<br />
public void setDataSource(DataSource dataSource) {<br />
this.dataSource = dataSource;<br />
}<br />
<br />
public JdbcOperations getJdbc() {<br />
return jdbc;<br />
}<br />
<br />
public void setJdbc(JdbcOperations jdbc) {<br />
this.jdbc = jdbc;<br />
}<br />
<br />
<br />
public void init(){<br />
log = Logger.getLogger(DaoOperation.class);<br />
setDatabase();<br />
}<br />
<br />
<br />
public void executeSQL(String sql) {<br />
try{<br />
log.debug("exec SQL: " + sql);<br />
jdbc.execute(sql);<br />
}catch(Exception e){<br />
log.error("some problem during executing sql");<br />
}<br />
}<br />
<br />
public void executeSQL(Collection<String> sqlList) throws IOException,<br />
SQLException {<br />
for (String sql : sqlList) {<br />
executeSQL(sql);<br />
}<br />
}<br />
public void setDatabase(){<br />
executeSQL("USE sumandb");<br />
}<br />
<br />
<br />
}<br />
<br />
<br />
<strong>project-config.properties</strong><br />
db.driver = com.mysql.jdbc.Driver<br />
db.url = jdbc:mysql://localhost<br />
db.username = root<br />
db.password = mysql<br />
<br />
<strong>project-config.xml</strong><br />
<br />
<?xml version="1.0" encoding="utf-8"?><br />
<beans xmlns="http://www.springframework.org/schema/beans"<br />
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"<br />
xmlns:aop="http://www.springframework.org/schema/aop"<br />
xmlns:p="http://www.springframework.org/schema/p" <br />
xmlns:tx="http://www.springframework.org/schema/tx"<br />
xmlns:lang="http://www.springframework.org/schema/lang" <br />
xmlns:context="http://www.springframework.org/schema/context"<br />
xsi:schemaLocation="http://www.springframework.org/schema/beans<br />
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd<br />
http://www.springframework.org/schema/tx <br />
http://www.springframework.org/schema/tx/spring-tx-2.0.xsd<br />
http://www.springframework.org/schema/lang <br />
http://www.springframework.org/schema/lang/spring-lang-2.5.xsd<br />
http://www.springframework.org/schema/context <br />
http://www.springframework.org/schema/context/spring-context-2.5.xsd<br />
http://www.springframework.org/schema/aop <br />
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"> <br />
<context:mbean-server/><br />
<context:property-placeholder location="classpath:/project-config.properties" /><br />
<br />
<bean id="daoOperation"<br />
class="com.suman.DaoOperation"<br />
init-method="init" p:dataSource-ref="dataSource" <br />
p:jdbc-ref="jdbc" /><br />
<br />
<bean id="jdbc" class="org.springframework.jdbc.core.JdbcTemplate"<br />
p:dataSource-ref="dataSource" /><br />
<br />
<!--Infrastructure setup --><br />
<br />
<bean id="dataSource" destroy-method="close"<br />
class="org.apache.commons.dbcp.BasicDataSource" p:driverClassName="${db.driver}"<br />
p:url="${db.url}" p:username="${db.username}" p:password="${db.password}" /><br />
<br />
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"<br />
p:dataSource-ref="dataSource"/><br />
<br />
<tx:annotation-driven transaction-manager="transactionManager"/><br />
<br />
</beans><br />
<br />
<strong>log4j.xml</strong><br />
<br />
<?xml version="1.0" encoding="UTF-8"?><br />
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"><br />
<br />
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false"><br />
<br />
<!-- logs to system console --><br />
<appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender"><br />
<param name="Target" value="System.out" /><br />
<param name="Threshold" value="ALL" /><br />
<layout class="org.apache.log4j.PatternLayout"><br />
<param name="ConversionPattern" value="%d{ABSOLUTE} %-5p [%c{1}] %m%n" /><br />
</layout><br />
</appender><br />
<br />
<logger name="org.springframework" additivity="false"><br />
<level value="WARN" /><br />
<appender-ref ref="CONSOLE"/><br />
</logger><br />
<br />
<root><br />
<level value="ALL" /><br />
<appender-ref ref="CONSOLE" /><br />
</root><br />
<br />
</log4j:configuration><br />
<br />
<br />
<strong>Create database with name sumandb in mysql in localhost at 3306 port.</strong><br />
Then create the two table<br />
<br />
create table<br />
CREATE TABLE `student` (<br />
`id` int(11) NOT NULL,<br />
`name` varchar(90) default NULL,<br />
`roll` int(11) default NULL,<br />
PRIMARY KEY (`id`)<br />
) ENGINE=InnoDB DEFAULT CHARSET=latin1<br />
<br />
<br />
<br />
create table<br />
CREATE TABLE `hostel` (<br />
`id` int(11) NOT NULL,<br />
`name` varchar(200) default NULL,<br />
`roll` int(11) default NULL,<br />
PRIMARY KEY (`id`),<br />
KEY `FK_hostel` (`roll`),<br />
CONSTRAINT `FK_hostel` FOREIGN KEY (`roll`) REFERENCES `student` (`id`)<br />
) ENGINE=InnoDB DEFAULT CHARSET=latin1<br />
<br />
<br />
<br />
<strong>RUN THE APPLICATION :</strong><br />
<br />
Now run App.java<br />
you will see one record has been inserted into student table and one record into hostel table.<br />
<br />
Here student.id is the foreign key for hostel.roll. So without having id (say x) exist in student table you can not save any record into hostel table with roll x. <br />
<strong>** IMP **</strong>. But I am going to save into both table. I will give id 2 in student table and roll 9 in hostel table.<br />
String sql = "insert into student (id,name,roll) values (2,'Pramod',110)";<br />
String sql = "insert into hostel (id,name,roll) values (1,'Yamuna',9)";<br />
See what is going to happen.<br />
<br />
One recrod has been inserted in student table but no new record into hostel table. BUT in student table record should not have been inserted if we will use TRANSACTION.<br />
<br />
delete that recrod from student table.<br />
DELETE FROM student WHERE id = 2 <br />
<br />
<strong>NOW I AM GOING TO IMPLEMENT SPRING TRANSACTION. </strong><br />
<br />
<strong>FIRST WAY TO IMPLEMENT SPRING TRANSACTION.</strong><br />
<br />
Change saveStudetn() of DaoOperation.java method and change import:<br />
<br />
public void saveStudent(){<br />
<em>TransactionTemplate tt = new TransactionTemplate();</em><br />
<em>tt.setTransactionManager(new DataSourceTransactionManager(getDataSource()));</em><br />
<em>tt.execute(new TransactionCallbackWithoutResult() {</em><br />
<em>protected void doInTransactionWithoutResult(TransactionStatus status) {</em><br />
<em>String sql = "insert into student (id,name,roll) values (2,'Pramod',110)";</em><br />
executeSQL(sql);<br />
saveHostel();<br />
<em>}</em><br />
<em>});</em><br />
}<br />
<br />
<em>Change import</em><br />
<br />
import java.io.IOException;<br />
import java.sql.SQLException;<br />
import java.util.Collection;<br />
<br />
import javax.sql.DataSource;<br />
<br />
import org.apache.log4j.Logger;<br />
import org.springframework.jdbc.core.JdbcOperations;<br />
import org.springframework.jdbc.datasource.DataSourceTransactionManager;<br />
import org.springframework.transaction.TransactionStatus;<br />
import org.springframework.transaction.support.TransactionCallbackWithoutResult;<br />
import org.springframework.transaction.support.TransactionTemplate;<br />
<br />
<br />
<br />
Now you run App.java, there will NOT be any record will get inserted either in Student or hostel table. Transaction has rolled back all the database opeartion if any operation gets fail.<br />
<br />
<em>Now change sql:</em><br />
<em>String sql = "insert into student (id,name,roll) values (2,'Pramod',110)";</em><br />
<em>String sql = "insert into hostel (id,name,roll) values (2,'Yamuna',2)";</em><br />
<br />
Now run the application.<br />
Both record have been saved successfully.<br />
<br />
<br />
<strong>SECON WAY TO IMPLEMENT SPRING TRANSACTION.</strong><br />
<br />
Change saveStudetn() of DaoOperation.java method and change import:<br />
<br />
<strong>@Transactional (propagation=Propagation.REQUIRED, rollbackFor=Exception.class)</strong><br />
public void saveStudent(){<br />
String sql = "insert into student (id,name,roll) values (2,'Pramod',110)";<br />
executeSQL(sql);<br />
saveHostel();<br />
}<br />
<br />
<br />
<br />
Change sql to check whether transaction is working correctly:<br />
<br />
String sql = "insert into student (id,name,roll) values (3,'Ayush',120)";<br />
String sql = "insert into hostel (id,name,roll) values (3,'Ganga',9)";<br />
<br />
no any record should be inserterd.<br />
<br />
Now change sql, and both record should be inserted.<br />
String sql = "insert into student (id,name,roll) values (3,'Ayush',120)";<br />
String sql = "insert into hostel (id,name,roll) values (3,'Ganga',3)";<br />
<br />
Thats easy ............... :)<br />
<br />
<br />
Now I checked with huge data. If any record will not be able to insert then all the previouse record will rolled back.<br />
<br />
Changed both method of DaoOpeartion.java<br />
<br />
public void saveStudent(){<br />
for(int i=0;i<10;i++){<br />
String sqlStudetn = "insert into student (id,name,roll) values ("+i+",'Ayush',120)";<br />
String sqlHostel = "insert into hostel (id,name,roll) values ("+i+",'Ganga',"+i+")";<br />
executeSQL(sqlStudetn);<br />
saveHostel(sqlHostel);<br />
}<br />
<br />
}<br />
<br />
public void saveHostel(String sql){<br />
executeSQL(sql);<br />
}<br />
<br />
<br />
Run the App.java<br />
<br />
10 record should be inserted into Student table and 10 records should be inserted into hostel table.<br />
<br />
Now add last recrod that should not be insert to avoid foreign key constraints. Then all the previous 10 record will be rolled back;<br />
<br />
DELETE FROM hostel;<br />
DELETE FROM student;<br />
@Transactional (propagation=Propagation.REQUIRED, rollbackFor=Exception.class)<br />
public void saveStudent(){<br />
for(int i=0;i<10;i++){<br />
String sqlStudetn = "insert into student (id,name,roll) values ("+i+",'Ayush',120)";<br />
String sqlHostel = "insert into hostel (id,name,roll) values ("+i+",'Ganga',"+i+")";<br />
executeSQL(sqlStudetn);<br />
saveHostel(sqlHostel);<br />
}<br />
String sqlHostel = "insert into hostel (id,name,roll) values (10,'Ganga',10)";<br />
saveHostel(sqlHostel);<br />
}<br />
<br />
<br />
Now run the App.java<br />
and check database, there is no any record has been inserted either in student table or Hostel table.<br />
<br />
<strong>That's easy .............. :) </strong>Ayush Java Solutionhttp://www.blogger.com/profile/06285300908312833165noreply@blogger.com3tag:blogger.com,1999:blog-7913068305301225566.post-41291015071136720582010-04-11T11:26:00.000-07:002010-04-11T11:31:53.833-07:00Process the command line with CLI in Java, common CLI example<span style="color:#cc0000;"><strong>CLI (=Command Line Interface)</strong> </span><br /><span style="color:#cc0000;"><br /></span>How many times have you written a Java application and had had to rewrite a new way of specifying the input parameters to your application? Wouldn't it be nice if there were one single interface to the way you define the input parameters (mandatory vs. numbers vs. Boolean, etc.), parse these parameters (according to a set of rules), interrogate, and decide the path that your application will take? CLI is the answer.<br /><br />To run this example, needs commons-cli-1.0.jar in the CLASSPATH. YOu can download from <a href="http://commons.apache.org/cli/introduction.html">here<br /></a><br /><a href="http://onjava.com/pub/a/onjava/2003/06/25/commons.html">Refer of this tutorial. </a><br /><br />In CLI, each parameter that you want to specify on the command line is an Option. Create an Options object, add individual Option objects to it, then use the CLI-supplied methods to parse the user's input parameters. An Option might require the user to input a value as well; for example, if the name of a file is required. In such a case, the Option must be created where this is explicitly specified.<br /><br /><strong>Create your Options:<br /></strong><br />Options options = new Options();<br />options.addOption("n", true, "[name] your name");<br /><br />2nd way is by creating an Option and then adding it<br />Option timeOption = new Option("t", false, "current time");<br />options.addOption(timeOption);<br /><br /><em>The addOption() method has three parameters.<br /></em><br />1. The first parameter is a java.lang.String that represents the option (That would be given by user with - like -t or -n during execution of code).<br /><br />2. The second parameter is a boolean that specifies whether the option requires an argument or not. For example -n Nik, here I gave Nik with -n because n is defined as true, if I will not give name then it would not be accept. For -t, no need to supply any argument as it is false. Even though if you give any argument, it would not be accept means it would be ignore that extra argument. In the case of a boolean option (sometimes referred to as a flag) an argument value is not present so false is passed.<br /><br />3. The third parameter is the description of the option. This description will be used in the usage text of the application. When you will not give proper argument that time it will show like help command.<br /><br />CommandLineParser parser = new PosixParser();<br />CommandLine cmd = parser.parse( options, args);<br /><br />The parse methods of CommandLineParser are used to parse the command line arguments. The PosixPaser is great when you need to handle options that are one character long, like the t option in this example. Else use BasicParser for more than one character input.<br /><br />Now we need to check if the t option is present. To do this we will interrogate the CommandLine object. The hasOption method takes a java.lang.String parameter and returns true if the option represented by the java.lang.String is present, otherwise it returns false.<br /><br /><br />if(cmd.hasOption("t")) {<br />// print the date and time<br />}<br />else {<br />// print the some thing else;<br />}<br /><br /><br /><strong>One complete example on CLI :<br /></strong><br />import org.apache.commons.cli.*;<br /><br /><br />public class CLIDemo{<br /><br />public static void main(String args[]){<br />Options options = new Options();<br />options.addOption("n", true, "[name] your name");<br />Option timeOption = new Option("t", false, "current time");<br />options.addOption(timeOption);<br /><br />// ** now lets parse the input<br />CommandLineParser parser = new BasicParser();<br />CommandLine cmd;<br />try{<br />cmd = parser.parse(options, args);<br />}catch (ParseException pe){ usage(options); return; }<br /><br />// ** now lets interrogate the options and execute the relevant parts<br /><br />if(cmd.hasOption("t")){<br /><br />System.out.println("You have given argument is t");<br />System.err.println("Date/Time: " + new java.util.Date());<br />}<br /><br />if(cmd.hasOption("n")){<br />System.out.println("You have given argument is n");<br />System.err.println("Nice to meet you: " + cmd.getOptionValue('n'));<br />}<br /><br />}<br /><br />private static void usage(Options options){<br /><br />// Use the inbuilt formatter class<br />HelpFormatter formatter = new HelpFormatter();<br />formatter.printHelp( "CLIDemo", options );<br />}<br />}<br /><br /><br /><br />In the above code, there is no any use to use cmd.getOptionValue('t') with t condition, as t has been setup false and it would be never get any extra argument as n.<br /><br /><strong>How to run CLI example:<br /></strong><br />D:\JavaTest>javac CLIDemo.java<br /><br />D:\JavaTest>java CLIDemo<br /><br />D:\JavaTest>java CLIDemo -t<br />You have given argument is t<br />Date/Time: Sun Apr 11 21:19:50 EEST 2010<br /><br />D:\JavaTest>java CLIDemo -n<br />usage: CLIDemo<br />-n [name] your name<br />-t current time<br /><br />D:\JavaTest>java CLIDemo -n Nik<br />You have given argument is n<br />Nice to meet you: Nik<br /><br />D:\JavaTest>java CLIDemo -n "Nik Suman"<br />You have given argument is n<br />Nice to meet you: Nik Suman<br /><br />D:\JavaTest><br /><br />First time I did not give any argument, so there is no any output.<br />Second time I gave -t as argument then we got output as per our expectation.<br />Third time I gave -n. This time, durint parsing the input it got error so execute catch part. Actually -n has been setup with true so we have to have some<br /><br />extra argument with -n. In catch block we are printing the help format.<br />Forth time I gave -n With some name, so it worked perfectly.Ayush Java Solutionhttp://www.blogger.com/profile/06285300908312833165noreply@blogger.com0tag:blogger.com,1999:blog-7913068305301225566.post-36091918112711123332010-04-10T12:56:00.000-07:002010-04-10T13:14:37.323-07:00MAVEN getting started, Maven in 10 MinutesDownload<br />apache-maven-3.0-alpha-7-bin.zip and unzip into any where (In my case it is D:\Software\apache-maven-3.0-alpha-7)<br />set path D:\Software\apache-maven-3.0-alpha-7\bin<br /><br />open dos console and type mvn -v<br />To check for sucessfully install.<br /><br />Create one folder to practice for maven project say D:\binod\Maven_Practice<br />Now execute command from dos console<br />D:\binod\Maven_Practice>mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=com.tecnotree.bds -DartifactId=CheckMaven<br /><br />CheckMaven is the project name<br />command exectued from D:\binod\Maven_Practice<br />it create one folder CheckMaven inside D:\binod\Maven_PracticeInside CheckMaven : src folder and pom.xml file<br />pom.xml<br /><project xmlns="<a href="http://maven.apache.org/POM/4.0.0">http://maven.apache.org/POM/4.0.0</a>" xmlns:xsi="<a href="http://www.w3.org/2001/XMLSchema-instance">http://www.w3.org/2001/XMLSchema-instance</a>" xsi:schemaLocation="<a href="http://maven.apache.org/POM/4.0.0">http://maven.apache.org/POM/4.0.0</a> <a href="http://maven.apache.org/maven-v4_0_0.xsd%22&gt">http://maven.apache.org/maven-v4_0_0.xsd"&gt</a>; <modelVersion>4.0.0</modelVersion> <groupId>com.tecnotree.bds</groupId> <artifactId>CheckMaven</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>CheckMaven</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies></project><br />src -> main and test. main -> java -> com -> tecnotree -> bds -> App.javatest -> java -> com -> tecnotree -> bds -> AppTest.java<br /><br />App.java<br /><br />package com.tecnotree.bds;<br />public class App { <br />public static void main( String[] args ) { <br />System.out.println( "Hello World!" ); <br /> }<br />}<br /><br />AppTest.java<br /><br />package com.tecnotree.bds;<br />import junit.framework.Test;<br />import junit.framework.TestCase;<br />import junit.framework.TestSuite;<br /><br />/** * Unit test for simple App. */<br /><br />public class AppTest extends TestCase{ <br />/** * Create the test case * * @param testName name of the test case */ <br />public AppTest( String testName ) { super( testName ); }<br /> /** * @return the suite of tests being tested */ <br />public static Test suite() { return new TestSuite( AppTest.class ); }<br /> /** * Rigourous Test :-) */ <br />public void testApp() { assertTrue( true ); }<br />}<br /><br />D:\Binod\Maven_Practice\CheckMaven> mvn compile<br />It compile App.java and create new folder target and App.class put into D:\Binod\Maven_Practice\CheckMaven\target\classes\com\tecnotree\bds<br /><br /><br />without running above commannd<br />D:\Binod\Maven_Practice\CheckMaven>mvn test-compile then it will compile App.java and AppTest.java and put App.class into D:\Binod\Maven_Practice\CheckMaven\target\classes\com\tecnotree\bdsand AppTest.java into D:\Binod\Maven_Practice\CheckMaven\target\test-classes\com\tecnotree\bds<br /><br />without running any above command<br />D:\Binod\Maven_Practice\CheckMaven> mvn test<br />It will do mvn test-compile and extra test. Means in target there would be create three folderlike about classes and test-classes and new is surefire-report.<br /><br />Actually mvn test it runs the compiled unit tests and make report (txt & xml) and put into surefire-report folder.<br />This command will also show test result on console.<br /><br />D:\Binod\Maven_Practice\CheckMaven> mvn package<br />It would be work of mvn test and extra create one folder maven-archiver and put one jar file CheckMaven-1.0-SNAPSHOT.jar into target folder.<br />Inside the maven-archiver one pom.properties file would be come with these details:<br />#Generated by Maven#Sat Apr 10 10:34:57 EEST 2010version=1.0-SNAPSHOTgroupId=com.tecnotree.bdsartifactId=CheckMaven<br /><br />D:\Binod\Maven_Practice\CheckMaven>mvn integration-test<br />It will execute all above command internally and carries out acutal integartion tests. Right now no any differences from above command. We will see later.<br /><br />Without running any above command<br />D:\Binod\Maven_Practice\CheckMaven> mvn install<br />It will run above command interally and adds the archive to the local Maven directory. This makes it available for any other modules that may depend on it.<br /><br />My local repository set up into D:\.m2 folder.<br />(How to set up custome local maven repository:<br />I have install or unzip Maven file here D:\Software\apache-maven-3.0-alpha-7. Go into D:\Software\apache-maven-3.0-alpha-7\conf and change settings.xml<br />uncommented <localRepository> and changed to <localRepository>D:\.m2\repository</localRepository><br />so, CheckMaven-1.0-SNAPSHOT.jar put into D:\.m2\repository\com\tecnotree\bds\CheckMaven\1.0-SNAPSHOT<br /><br />Without running any above command<br />D:\Binod\Maven_Practice\CheckMaven> mvn deploy<br />It will run above command interally and adds the archive to the remote Maven directory. But here it wont work.<br />Because we dont have set up the repository element was not specified in the pom inside distributionManagement element or in -DaltDeploymentRepository=id::layout::url parameter -> [Help 1]<br /><br />How to set remote maven repository.<br /><br />open pom.xml (D:\Binod\Maven_Practice\CheckMaven\pom.xml)<br />Add <distributionManagement> like this<br /><project xmlns="<a href="http://maven.apache.org/POM/4.0.0">http://maven.apache.org/POM/4.0.0</a>" xmlns:xsi="<a href="http://www.w3.org/2001/XMLSchema-instance">http://www.w3.org/2001/XMLSchema-instance</a>" xsi:schemaLocation="<a href="http://maven.apache.org/POM/4.0.0">http://maven.apache.org/POM/4.0.0</a> <a href="http://maven.apache.org/maven-v4_0_0.xsd%22&gt">http://maven.apache.org/maven-v4_0_0.xsd"&gt</a>; <modelVersion>4.0.0</modelVersion> <groupId>com.tecnotree.bds</groupId> <artifactId>CheckMaven</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>CheckMaven</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> <distributionManagement> <repository> <id>BinodprojectRepository</id> <name>Binod Maven Repository Name</name> <url>file:///d:/MyRemoteMavenRepository</url><br /> </repository> <!-- site> <id>sample-project.website</id> <url>dav:https://dav.sample.com/sites/sample-project</url> </site --> </distributionManagement><br /></project><br /><br />Now you will see after run mvn deploy.<br />one target file will be created as usual and archieve file will go to d:/MyRemoteMavenRepository (no need to createthis folder, it create automatically).<br />D:\Binod\Maven_Practice\CheckMaven> mvn cleanIt will delete the target forlder.<br /><br /><br />************************ CONCLUSION ********************<br />There are phases of the default life cycle of Maven<br />1. validate : Ensures that the current configuration and the content of the POM is valid. This includes validation of the tress of pom.xml files.<br />2. compile : Compiles the source code. The compiled classes are places into a target directory tree.<br />3. test-compile : Compile the source code of the unit tests.<br />4. test: Runs the compiled unit tests and showing the result on the console.<br />5. package: Bundles the exectable binaries into a distribution archive, such as a JAR or WAR.<br />6. integration-test : Carries out actual integration tests.<br />7. install : Adds the archive to the local Maven directory. This markes it available for any other modules that may depends on it.<br />8. deploy : Adds the archive to a remote Maven directory. This can make the artifact available to a larger audience.<br /><br />Concept is here that if you run 3 then it will run 1, 2 and 3.<br />if you run 6 then it will run 1,2,3,4,5 and 6.<br />That is because if you call a build phase, it will execute not only that build phase, but also every build phase prior to the called build phase.<br /><br />It should also be noted that the same command can be used in a multi-module scenario (i.e. a project with one or more subprojects). For example:mvn clean install (from root directory), this command will traverse into all of the subprojects and run clean, then install (including all of the prior steps).<br /><br />mvn install -Dmaven.test.skip=true : it will do install but except test execution.<br /><br /><br /><strong>How to integrate with Eclipse<br /></strong>Now if you want to import this project into eclipse, it will not work. In eclipse you would not be able to import this project.<br />D:\Binod\Maven_Practice\CheckMaven> mvn eclipse:eclipse<br />It will create two file inside D:\Binod\Maven_Practice\CheckMaven folder. 1. .classpath and 2. .project. Now you can import into eclispe.<br /><br />Open eclipse and set workplace is D:\Binod\Maven_Practice. File -> Import -> Import -> General -> Existing Projects into Workspace -> Browse (Select root directory, D:\Binod\Maven_Practice)then check CheckMaven -> Finish<br /><br />Your project would be imported into workspace.<br />D:\Binod\Maven_Practice\CheckMaven> mvn eclipse:cleanIt will delete both generated file 1. .classpath and 2. .project.<br /><br />D:\Binod\Maven_Practice\CheckMaven>mvn eclipse:clean eclipse:eclipse<br />Now we ensured that all previous eclipse resources are removed and generated again.<br />To let eclipse know where the local Maven 2 repository is located you should know where it is located. By default the Maven 2 repository is located at<br />/home/[USERNAME]/.m2/repositoryC:\Documents and Settings\sumankbi\.m2\repository<br />We should avoid avoid space in maven repository class path. Refer above settign to change local repository.<br /><br />In Eclipse -> window -> Preferences -> Maven -> Installation -> User setting -> Browse -> D:\Software\apache-maven-3.0-alpha-7\conf\settings.xml then Local repository will be change as per the setting.xml and it become D:\.m2\repository.<br /><br />Now check, In Eclipse -> window -> Preferences -> Java -> Build Path -> Classpath Variable -> M2_REPO shold be D:\.m2\repository.<br /><br />mvn clean eclipse:clean eclipse:eclipse<br /><br /><strong>Dependencies</strong><br />Some dependencies often are needed to write your applications. Commonly we are using some open source libraries and frameworks (e.g. the spring application framework or apache commons-logging,...). Sometimes own libraries should be referenced by a java project. To solve this problem Maven delivers a very good dependency mechanism that manages the dependencies of your project transitivly.<br /><br />How the maven download new jar file, if our project is needed for that jar file.<br />Maven will download all dependencies referenced by your pom.xml from the central Maven 2 repository automatically to local reposity (In my case D:\.m2\repository). Suppose my project is needed commons-logging jar file then put this jar info into pom.xml and run mvn package and watch console, maven will downloading this jar into your local repository.<br />You have to add commons-logging into pom.xml<br /><br /><dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.1</version> </dependency><br /><br />Now complete pom.xml<br /><br /><project xmlns="<a href="http://maven.apache.org/POM/4.0.0">http://maven.apache.org/POM/4.0.0</a>" xmlns:xsi="<a href="http://www.w3.org/2001/XMLSchema-instance">http://www.w3.org/2001/XMLSchema-instance</a>" xsi:schemaLocation="<a href="http://maven.apache.org/POM/4.0.0">http://maven.apache.org/POM/4.0.0</a> <a href="http://maven.apache.org/maven-v4_0_0.xsd%22&gt">http://maven.apache.org/maven-v4_0_0.xsd"&gt</a>; <modelVersion>4.0.0</modelVersion> <groupId>com.tecnotree.bds</groupId> <artifactId>CheckMaven</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>CheckMaven</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.5</version> <scope>test</scope> </dependency> </dependencies> <distributionManagement> <repository> <id>BinodprojectRepository</id> <name>Binod Maven Repository Name</name> <url>file:///d:/MyRemoteMavenRepository</url><br /> </repository> <!-- site> <id>sample-project.website</id> <url>dav:https://dav.sample.com/sites/sample-project</url> </site --> </distributionManagement><br /><br /></project><br /><br />Even I changed junit from 3.1 to 4.5. Now if I run mvn command (mvn clean package), it will download both jar file. You can watch d:\.m2\repository and console both.<br /><br />Some more example<br /><br /><dependency> <br /><groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>2.5.5</version> </dependency> <dependency> <br /><br /><groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>2.5.5</version> <br /></dependency> <br /><br /><dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>2.5.5</version> </dependency> <br /><br /><dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>2.5.5</version> </dependency><br /><br /><dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> <br /></dependencies><br /><br /><dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.1.2</version> </dependency><br /><br /><strong>Properties :</strong> Same as Ant, we can set up any variable and use in the xml file.<br />In above example we are repeating same version number of all the spring jar file, so better put one place all the version number and use references. Use the properties tag.<br /><br /><properties> <br /><spring-version>2.5.5</spring-version> <br /><junit-version>4.5</junit-version> <br /><commons-dbcp-version>1.2.2</commons-dbcp-version> <br /><commons-logging-version>1.1.1</commons-logging-version> <br /><mysql-version>5.1.6</mysql-version> <br /><servlet-version>1.1.2</servlet-version> <br /></properties><br /><br /><dependencies> <br /><!-- Spring Framework --> <br /><dependency> <br /><groupId>org.springframework</groupId> <br /><artifactId>spring-core</artifactId> <br /><version>${spring-version}</version> <br /></dependency> <br /><br /><dependency> <br /><groupId>org.springframework</groupId> <br /><artifactId>spring-webmvc</artifactId> <br /><version>${spring-version}</version> <br /></dependency> <br /> <br /><dependency> <br /><groupId>org.springframework</groupId> <br /><artifactId>spring-web</artifactId> <br /><version>${spring-version}</version> <br /></dependency> <br /><br /><dependency> <br /><groupId>mysql</groupId> <br /><artifactId>mysql-connector-java</artifactId> <br /><version>${mysql-version}</version> <br /></dependency> <br /><br /></dependencies><br /><dependency> <br /><groupId>javax.servlet</groupId> <br /><artifactId>jstl</artifactId> <br /><version>${servlet-version}</version> <br /></dependency><br /><br /><strong>Scopes:</strong> The dependency scope defines to which part of the project's lifecycle the dependency is attached. For example the JUnit dependency is only added while running the tests. So i defined that this dependency is attached to the target "test".<br /><br /> <dependency> <br /><groupId>junit</groupId> <br /><artifactId>junit</artifactId> <br /><version>4.5</version> <br /><scope>test</scope> <br /></dependency> <br /></dependencies><br /><br /><strong>There are at least 6 different scopes:<br /></strong>compile: This scope indicates the Maven compilation phase. It is the default scope that will be used if no scope is defined. provided: This scope defines that this dependency is provided by the container (e.g. Apache Tomcat) at runtime. runtime: This scope indicates that this Dependency isn't required in the compilation phase but it is needed at runtime. test: "test"-dependencies are only while compiling and running the tests. system: This scope indicates that the dependency is provided by the system.<br /><br /><strong>ABOUT POM.XML<br /></strong>you must always think of a Maven POM in terms of the combinationof the Super POM, plus any parent POMs, and finally the current project’s POM. Maven starts with theSuper POM and then overrides default configuration with one or more parent POMs. Then it overridesthe resulting configuration with the current project’s POM.<br /><br />Build element: it that handles things like declaring your project's directory structure and managing plugins; and the reporting element, that largely mirrors the build element for reporting purposes.<br /><br /><strong>MultiProject in Maven</strong><br /><br />Create one folder say (MultiProjectCheck) D:\Binod\Maven_Practice\MultiProjectCheck<br />execute this command:<br />D:\Binod\Maven_Practice\MultiProjectCheck>mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=com.tecnotree.mp -DartifactId=MultiProject<br /><br />It will create MultiProject and put src and pom.xml.<br /><br />Now go to pom.xml in D:\Binod\Maven_Practice\MultiProjectCheck\MultiProject\pom.xmland change <packaging>jar</packaging> to <packaging>pom</packaging>.<br /><br />By setting the packaging type to “pom”, any projects you generate from the root of the project directory will insert itself into the project by creating an entry into the modules section of the pom.xml for the site.<br /><br />Now execute this below both command from MultiProject folder.<br /><br />D:\Binod\Maven_Practice\MultiProjectCheck\MultiProject>mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=com.tecnotree.mp -DartifactId=FirstSubModule<br /><br />D:\Binod\Maven_Practice\MultiProjectCheck\MultiProject>mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=com.tecnotree.mp -DartifactId=SecondModule<br /><br />Now come to D:\Binod\Maven_Practice\MultiProjectCheck\MultiProject\pom.xml (parent pom.xml), you will automatically added two module like this:<br /><br /><modules> <br /><module>FirstSubModule</module> <module>SecondModule</module><br /></modules><br /><br />You will see new tag in submodule pom.xml files.<br /><br /><parent> <br /><artifactId>MultiProject</artifactId> <groupId>com.tecnotree.mp</groupId> <br /><version>1.0-SNAPSHOT</version><br /></parent><br /><br />Now if you run mvn test from parent folder<br /><br />D:\Binod\Maven_Practice\MultiProjectCheck\MultiProject<br />then it will create target forlder in both module. But if you run mvn test from insidet FirstSubModule folder then it will be creating only in this module, it wont effect on second module SecondModule.<br /><br />How to import into Eclispe:<br /><br />D:\Binod\Maven_Practice\MultiProjectCheck\MultiProject>mvn eclipse:eclipse<br /><br />Create workspace in eclipse D:\Binod\Maven_Practice\MultiProjectCheck\MultiProjectand import -> browse -> select D:\Binod\Maven_Practice\MultiProjectCheck\MultiProject -> It will show both project, select both project and it will come to eclipse.<br /><br /><strong>How to develop Maven site.</strong><br /><strong>Maven site example.</strong><br /><strong><br /></strong>come to D:\Binod\Maven_Practice<br />D:\Binod\Maven_Practice>mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=com.mycompany.app -DartifactId=MavenSiteCheckand<br />execute this command to generate site folder inside src<br /><br />D:\Binod\Maven_Practice>mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-site -DgroupId=com.mycompany.app -DartifactId=MavenSiteCheck<br /><br />go to D:\Binod\Maven_Practice\MavenSiteCheck\src\site\xdoc\xdoc.xml<br />Here you can write about your project.<br />Now,<br />D:\Binod\Maven_Practice\MavenSiteCheck>mvn site:site<br /><br />It will create one target folder in D:\Binod\Maven_Practice\MavenSiteCheck.<br />One html file generate D:\Binod\Maven_Practice\MavenSiteCheck\target\site\xdoc.htmlyou can open this html file.<br /><br />You can also run this page as web site using jetty<br />D:\Binod\Maven_Practice\MavenSiteCheck>mvn site:runURL: <a href="http://localhost:8080/xdoc.html">http://localhost:8080/xdoc.html</a><br /><br />How you can put some picture here in documentcreate one resources inside the site folder (D:\Binod\Maven_Practice\MavenSiteCheck\src\site\resources) and put all your picutre here say suman.jpg<br /><br />now come to xdoc.xml (D:\Binod\Maven_Practice\MavenSiteCheck\src\site\xdoc\xdoc.xml)<br />and write here <img src="suman.jpg"></img><br />Now,<br />D:\Binod\Maven_Practice\MavenSiteCheck>mvn site:site<br /><br />It will move all the images from D:\Binod\Maven_Practice\MavenSiteCheck\src\site\resources to D:\Binod\Maven_Practice\MavenSiteCheck\target\site.<br /><br />now open D:\Binod\Maven_Practice\MavenSiteCheck\target\site\xdoc.htmlAyush Java Solutionhttp://www.blogger.com/profile/06285300908312833165noreply@blogger.com3tag:blogger.com,1999:blog-7913068305301225566.post-31266232114955403982010-04-04T14:39:00.000-07:002010-04-04T14:45:19.731-07:00XML Handling in Groovy, XML with Groovy<p><strong><span style="color:#cc0000;">Info.xml</span></strong></p><p><?xml version="1.0" ?><br /><customers><br /><corporate><br /><customer name="Nik Kumar Suman" company="TecnoTree" /><br /><customer name="Pramod Kumar Modi" company="efi" /><br /><customer name="Mika" company="TecnoTree" /><br /></corporate><br /><br /><consumer><br /><customer name="Nik" /><br /><customer name="Pramod" /><br /></consumer><br /><br /></customers><br /><br /><strong><span style="color:#990000;">ReadXML.gy<br /></span></strong><br />def customers = new XmlSlurper().parse(new File('Info.xml'))<br />for (customer in customers.corporate.customer){<br />println "<a href="mailto:$%7Bcustomer.@name">${customer.@name</a>} works for <a href="mailto:$%7Bcustomer.@company">${customer.@company</a>}"<br />}<br /><br /><strong><span style="color:#990000;">output: </span></strong></p><p>D:\Nik\Groovy_Example>groovy ReadXML.gy<br />Nik Kumar Suman works for TecnoTree<br />Pramod Kumar Modi works for efi<br />Mika works for TecnoTree<br />D:\Nik\Groovy_Example></p>Ayush Java Solutionhttp://www.blogger.com/profile/06285300908312833165noreply@blogger.com0tag:blogger.com,1999:blog-7913068305301225566.post-1496756981137996382010-04-03T04:44:00.000-07:002010-04-03T04:47:28.732-07:00File Handling in Groovy<strong><span style="color:#990000;">File Handling in Groovy</span></strong><br /><br />File handling in Groovy is made significantly easier with the addition of variousmethods to classes in the java.io package. A great example is the File.eachLine method.<br /><br /><strong>FileHandle.gy</strong><br /><br />def number=0new File ('Nik.txt').eachLine { <br />line -> number++<br />println "$number: $line"<br />}<br /><br /><strong>Nik.txt</strong><br /><br />My name is Ayush.<br />But you can call me Nik.<br />I am fully devoted to Java and want to something extra for java<br /><br /><strong>Now run groovy file</strong><br /><br />D:\Nik\Groovy_Example>groovy FileHandle.gy<br />1: My name is Ayush.<br />2: But you can call me Nik.<br />3: I am fully devoted to Java and want to something extra for java<br /><br />D:\Nik\Groovy_Example>Ayush Java Solutionhttp://www.blogger.com/profile/06285300908312833165noreply@blogger.com0tag:blogger.com,1999:blog-7913068305301225566.post-46591639733072227862010-04-02T08:06:00.000-07:002010-04-02T13:52:00.889-07:00javax.script how to use, groovy with java, java ScriptEngineManager, java ScriptEngine<span style="font-size:85%;">Browse this </span><a href="http://ayushsuman.blogspot.com/2010/04/groovy-getting-started-how-use-groovy.html"><span style="font-size:85%;">URL</span></a><span style="font-size:85%;"> for groove fundamental and getting started with groovy<br /><br />Java 6 includes built-in support for JSR 223: Scripting for the Java Platform API classes. This framework can be used to host Script Engines in Java Applications.<br /><br />Here is the code to how to use groovy script inside the java code<br /><br /></span><span style="font-size:85%;"><strong><span style="font-family:verdana;color:#990000;">EvalScriptFile.java<br /></span></strong><br />import javax.script.ScriptEngineManager;<br />import javax.script.ScriptEngine;<br />import javax.script.ScriptException;<br />import java.io.File;<br />import java.io.Reader;<br />import java.io.FileReader;<br />import java.io.FileNotFoundException;<br /><br />public class EvalScriptFile {<br /><br />public static void main(String[] args) {<br />ScriptEngineManager manager = new ScriptEngineManager();<br />ScriptEngine engine = manager.getEngineByName("groovy");<br /><br /><br />try {<br />File script = new File("D:\\Nik\\Groovy_Example\\Second.gy");<br />Reader reader = new FileReader(script);<br />engine.eval(reader);<br />} catch (FileNotFoundException e) {<br />System.out.println("SOME ERROR 1 :: "+e);<br />e.printStackTrace();<br />} catch (ScriptException e) {<br />System.out.println("SOME ERROR 2 :: "+e);<br />e.printStackTrace();<br />}<br /><br />}<br />}<br /><br />Second.gy<br /><br />class HelloWorld {<br /><br />def name<br /><br />def greet() { "Hello ${name}" }<br />}<br />def helloWorld = new HelloWorld()<br />helloWorld.name = "My name is groovy TEST "<br />println helloWorld.greet()<br /><br /><br /><strong><span style="color:#990000;">This below example is showing calling an invokable function:<br /></span></strong><br /><br />import javax.script.ScriptEngine;<br />import javax.script.ScriptEngineManager;<br />import javax.script.Invocable;<br /><br />public class Factorial {<br />public static void main(String[] args) throws Exception {<br />ScriptEngineManager factory = new ScriptEngineManager();<br />ScriptEngine engine = factory.getEngineByName("groovy");<br />String fact = "def factorialFun(n) { n == 1 ? 1 : n * factorialFun(n - 1) }";<br />engine.eval(fact);<br />Invocable inv = (Invocable) engine;<br />Object[] params = { new Integer(6) };<br />Object result = inv.invokeFunction("factorialFun", params);<br />System.out.println("The factorial of 6 is "result);<br />}<br />}<br /><br /><span style="color:#990000;">You will get result after run is<br /></span>The factorial of 6 is 720<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /></span>Ayush Java Solutionhttp://www.blogger.com/profile/06285300908312833165noreply@blogger.com0tag:blogger.com,1999:blog-7913068305301225566.post-71099527216395051772010-04-02T07:23:00.000-07:002010-04-04T14:38:12.613-07:00Groovy Getting started, How use groovy in Java, Groovy easy example, Groovy fundamental<p><span style="font-family:verdana;font-size:85%;"></span></p><p><strong><span style="color:#990000;">What is Groovy?</span></strong></p><p>The Groovy web site (<a href="http://groovy.codehaus.org/">http://groovy.codehaus.org/</a>) gives one of the best definitionsof Groovy: “<span style="color:#000066;">Groovy is an agile dynamic language for the Java Platform with manyfeatures that are inspired by languages like Python, Ruby and Smalltalk, makingthem available to Java developers using a Java-like syntax.</span>”</p><p>Everything you do in Groovy could be done in Java, it would be madness to writethe Java code required to work Groovy’s magic. Groovy performs a lot of workbehind the scenes to achieve its agility and dynamic nature. </p><p>The Groovy solution is short, precise, and more compact than normal Java. Groovy does not need to import the java.util package or specify the Date type;moreover, Groovy doesn’t require semicolons when it can understand the code without them.</p><p><br />import java.util.*; // Java<br />Date today = new Date(); // Java<br /><br />today = new Date() // Groovy<br /><br /></p><span style="font-family:verdana;font-size:85%;"><strong><span style="color:#cc0000;">How to install Groovy.</span></strong></span><br /><span style="font-family:verdana;font-size:85%;"><br />1. Download groovy-src-1.7.0.zip from </span><a href="http://dist.codehaus.org/groovy/distributions/"><span style="font-family:verdana;font-size:85%;">http://dist.codehaus.org/groovy/distributions/</span></a><br /><span style="font-family:verdana;font-size:85%;">2. Unzip this file and put any where in your pc. I have put at D:\Software\Groovy\groovy-1.7.0</span><br /><span style="font-family:verdana;font-size:85%;">3. Add a new System variable with the name GROOVY_HOME and the value of the directory groovy was installed in (In my case it is D:\Software\Groovy\groovy-1.7.0</span><br /><span style="font-family:verdana;font-size:85%;">4. add %GROOVY_HOME%\bin to your system path </span><br /><span style="font-family:verdana;font-size:85%;">5. Now open any dos window and type groovy. If every this is correct then you will get some opetion otherwise you will get error message like 'groovy' is not recognized as an internal or external command,operable program or batch file.</span><br /><span style="font-family:verdana;font-size:85%;"><br />REF: </span><a href="http://groovy.codehaus.org/Tutorial+1+-+Getting+started"><span style="font-family:verdana;font-size:85%;">http://groovy.codehaus.org/Tutorial+1+-+Getting+started</span></a><br /><br /><span style="font-family:verdana;font-size:85%;">Make one directory to put your all example code. In my case D:\Nik\Groovy_Example</span><br /><span style="font-family:verdana;font-size:85%;"><br /><strong>FIRST GROOY CODE</strong><br /><strong><br /></strong>HelloWorld.groovy<br /><br />class HelloWorld<br />{<br />static main( args )<br />{ println "Hello World!" }<br />}<br /><br /><strong>How to compile groovy file<br /></strong>Open dos window and navigate to D:\Nik\Groovy_Example<br />D:\Nik\Groovy_Example>groovyc HelloWorld.groovy<br />D:\Nik\Groovy_Example><br /><br />Now you will check one new class file (HelloWorld.class) has been generate in this folder (D:\Nik\Groovy_Example).<br /><br /><strong>How to run the groovy class<br /></strong>D:\Nik\Groovy_Example>groovy HelloWorldHello World!<br />D:\Nil\Groovy_Example><br />Even without compile the code you can direct use groovy command to run the code Like<br /><br />D:\Nik\Groovy_Example>groovy HelloWorldor<br />D:\Nik\Groovy_Example>groovy HelloWorld.groovy<br /><br /><span style="color:#990000;">you can also use extension like gv or groovy</span><br /><br /><strong><span style="color:#990000;">Here below, I am giving one java code and after that will convert same java code to Groovy</span></strong><br /><br /><strong>Second.java</strong><br /><br />public class Second {<br />private String name;<br />public void setName(String name) {<br />this.name = name;<br />}<br />public String getName() { return name; }<br />public String greet() { return "Hello " + name; }<br /><br />public static void main(String[] args) {<br />Second second = new Second();<br />second.setName("My name is groovy");<br />System.out.println(second.greet());<br />}<br />}<br /><br /><strong>Second.gy</strong><br /><strong></strong><br />class HelloWorld {<br />def name<br />def greet() { "Hello ${name}" }<br />}<br />def helloWorld = new HelloWorld()<br />helloWorld.name = "My name is groovy"<br />println helloWorld.greet()<br /><br /><br />NOTE: Groovy is an Object-Oriented language (a real one where numbers are also objects), and it supports the same programming model as Java. However, it's also a scripting language as it allows you to write some free form programs that don't require you to define a class structure. So in the last step of this tutorial, we're going to get rid of the main method altogether.<br /><br />Both will give the same output.<br /><br />D:\Nik\Groovy_Example>javac Second.java<br />D:\Nik\Groovy_Example>java SecondHello My name is groovy<br /><br />D:\Nik\Groovy_Example>groovy Second.gyHello My name is groovy<br />D:\Nik\Groovy_Example><br /><br />Ref: </span><a href="http://groovy.dzone.com/news/java-groovy-few-easy-steps"><span style="font-family:verdana;font-size:85%;">http://groovy.dzone.com/news/java-groovy-few-easy-steps</span></a><br /><br /><span style="font-family:verdana;font-size:85%;color:#990000;"><strong>How to run groovy script using java program</strong></span><br /><span style="font-family:verdana;font-size:85%;"><br /><strong>Secong.gy </strong><br /><strong></strong><br />class HelloWorld {<br />def name<br />def greet() { "Hello ${name}" }<br />}<br /><br />def helloWorld = new HelloWorld()<br />helloWorld.name = "My name is groovy TEST "<br />println helloWorld.greet()<br /><br /><strong>GroovyTest.java</strong><br /><br />import groovy.lang.GroovyClassLoader;<br />import groovy.lang.GroovyObject;<br />import java.io.File;<br /><br />public class GroovyTest {<br /><br />public static void main(String[] args) throws Exception{<br />System.out.println("THIS IS FIRST GROOVY PROGRAM");<br />new GroovyTest().GroovyRun();<br />}<br /><br />public void GroovyRun()throws Exception{<br />ClassLoader parent = getClass().getClassLoader();<br />GroovyClassLoader loader = new GroovyClassLoader(parent);<br />Class groovyClass = loader.parseClass(new File("D:\\Nik\\Groovy_Example\\Second.gy"));<br />// let's call some method on an instance<br />GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance();<br />Object[] args = {}; groovyObject.invokeMethod("main", args);<br />}<br />}<br /><br />D:\Nik\Groovy_Example>javac GroovyTest.java<br />D:\Nik\Groovy_Example>java GroovyTest<br />THIS IS FIRST GROOVY PROGRAMHello My name is groovy TEST<br /><br />D:\Nik\Groovy_Example><br /><br /><br /><br /><br /><br /><br /><br /></span><span style="font-family:verdana;font-size:85%;"></span>Ayush Java Solutionhttp://www.blogger.com/profile/06285300908312833165noreply@blogger.com3