d-h-n.de
Blog about Oracle, Linux..

Quick Start with Spring

March 19th, 2012 . by admin

1.Software

 

2.Create User Libraries:

In Eclipse you need 2 user libraries: spring-framework-3.1.1 and commons-logging

Create user library: spring-framework-3.1.1
  • Extract spring-framework-3.1.1.RELEASE.zip to C:Javalibrariesspring-framework-3.1.1.RELEASE
  • In Eclipse: Menu Windows → Preferences
  • → Click Java→Build Path→User Libraries→Click Button New…
  • → Input in field User library name: spring-framework-3.1.1
  • → Ok
  • → Click Button Add JARs..
  • → Select all JAR file from C:Javalibrariesspring-framework-3.1.1.RELEASEdist

Create user library: commons-logging-1.1.1
  • Extract spring-framework-3.1.1.RELEASE.zip to C:Javalibrariesspring-framework-3.1.1.RELEASE
  • Do the same steps like user library spring-framework-3.1.1, create the user lirary commons-logging-1.1.1,
    add only JAR file: commons-logging-1.1.1.jar

Note: Without Apache Commons Logging you get the error message:
Exception in thread “main” java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory

 

 

3. Create Project in Eclipse

  • Create a Java Project exm. Spring_QuickStart:
    Menu File → New → Java Project
  • Add User Libraries:
    Right click Project Spring_QuickStart → Build Path → Add Libraries → User Libraries →
    add the user libraries spring-framework-3.1.1 and commons-logging

 

 

4.Create a simmple Java class

package model;

public class Prompter {
	private String message;

	public void prompt() {
		System.out.println(message);
	}

	public void setMessage(String message) {
		this.message = message;
	}
}

 

 

5.Create file ..src/beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	 http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="myPrompter" class="model.Prompter">
		<property name="message" value="Here is my first Spring program!"></property>
	</bean>
</beans>

 

 

6.Create a Test Class

package model;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				"beans.xml");

		Prompter p = (Prompter) context.getBean("myPrompter");
		p.prompt();
	}

}

 

7.Run Test

Run Class App as Java Application, you see this in the Console:

19-Mar-2012 11:41:39 org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@133f1d7:
startup date [Mon Mar 19 11:41:39 CET 2012]; root of context hierarchy
19-Mar-2012 11:41:39 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans.xml]
19-Mar-2012 11:41:39 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@80fa6f:
defining beans [myPrompter]; root of factory hierarchy
Here is my first Spring program!

Quick Start with Hibernate Annotations

December 13th, 2011 . by admin

What is Annotations ?

Java Annotation: http://en.wikipedia.org/wiki/Java_annotation

Hinernate Annotations: For Mapping Java classes you can use XML files (*.hbm.xm) or use Annotation.
When using Annotation is the coding/generating of XML files unnecessary.

 

1. Software

see equivalent

 

2. Create database table Department

drop table department;
create table department (
   deptno  number        not null,
   name    varchar2(30)  not null,
  constraint department_pk primary key (deptno)
);
drop sequence department_seq;
create sequence department_seq start with 10;

 

3. Create User Libraries

see equivalent

 

4. Create Project in Eclipse

use the same project

 

5. Create a POJO class Department

package test;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

import org.hibernate.Session;

@Entity
@SequenceGenerator(name = "department_gen", sequenceName = "department_seq", initialValue = 1,
     allocationSize = 1)
@Table(name = "DEPARTMENT")
public class Department {
	@Id
	@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "department_gen")

	@Column(name = "deptno")
	private Integer departmentId = null;

	@Column(name = "NAME")
	private String name;

	public Integer getDepartmentId() {
		return departmentId;
	}

	public void setDepartmentId(Integer departmentId) {
		this.departmentId = departmentId;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}
Annotation means..
@Entity say this class is as an Hibernate entity
@Tables pecify the table associated with the class
@Id specify the entity’s primary key
@GeneratedValue specify the primary key generation
@Column specify the column associated with the property

more about other Annotations
 

6. Create mapping file

the coding/generating of XML-Mapping ist unnecessary.

 

7. Create a Helper Class HibernateUtil

use the equivalent

 

8. Configuration file hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
        <session-factory>
                <!-- Connect Oracle via JDBC -->
                <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
                <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
                <property name="hibernate.connection.url">jdbc:oracle:thin:@192.168.72.129:1521:orcl</property>
                <property name="hibernate.connection.username">hib</property>
                <property name="hibernate.connection.password">hib</property>
                <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
                <property name="current_session_context_class">thread</property>

                <!-- Print all generated SQL to the console -->
                <property name="show_sql">true</property>
                <property name="format_sql">true</property>

                <!-- Mapped entities -->
                <mapping resource="resources/Employee.hbm.xml" />
                <mapping class="test.Department" />
        </session-factory>
</hibernate-configuration>

 

9. Test Class

package test;

import org.hibernate.Session;

public class TestDepartment {
	public static void main(String[] args) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();

		Department dep = new Department();
		dep.setName("Software");

		int id = (Integer) session.save(dep);
		System.out.println("ID: " + id);
		session.getTransaction().commit();

		HibernateUtil.shutdown();
	}
}

 

Run the class as Java Application and the result is:

SQL> select * from department;

    DEPTNO NAME
---------- ------------------------------
        10 Software

Quick Start with Hibernate (XML Mapping)

December 13th, 2011 . by admin

1. Software

      • Eclipse Helios
      • Java 1.6
      • Oracle Database 11g (run on localhost or on a VM machine)
      • Oracle JDBC – ojdbc5.jar download
      • Hibernate 3.6.8.Final – hibernate-distribution-3.6.8.Final-dist.zip download

 

2. Create Database Table

connect as sys and create a new user hib

SQL> create user hib identified by hib account unlock;
SQL> grant connect, resource to hib;

connect as hib and create the table and sequences

SQL> drop table emp;
SQL> create table emp (
   empno        number        not null,
   name         varchar2(30)  not null,
   deptno number,
  constraint emp_pk primary key (empno)
);

SQL> drop sequence emp_seq;
SQL> create sequence emp_seq start with 100;

 

3. Create User Libraries in Eclipse

Create User Library: oracle_jdbc
      • Menu Windows → Preferences
      • → Click Java→Build Path→User Libraries→Click Button New…
      • → Input in field User library name: orcl_jdbc
      • → Ok
      • → Click Button Add JARs
      • → Select the Oracle JDBC ojdbc5.jar

more: connect-oracle-database-via-jdbc

Create User Library Hibernate 3.6.8

First create a directory exm. C:Javahibernate-3.6.8> and extract following JARs from hibernate-distribution-3.6.8.Final-dist.zip:

antlr-2.7.6.jar				found in lib/requires
commons-collections-3.1.jar		         found in lib/requires
dom4j-1.6.1.jar				found in lib/requires
javassist-3.12.0.GA.jar			found in lib/requires
jta-1.1.jar				found in lib/requires
slf4j-api-1.6.1.jar			found in lib/requires
hibernate-jpa-2.0-api-1.0.1.Final.jar 	found in jpa
hibernate3.jar				found in root directory

In Eclipse, analog like oracle_jdbc create a User Library Hibernate 3.6.8 with all above JARS.

User Libraries oracle_jdbc and Hibernate 3.6.8

User Libraries oracle_jdbc and Hibernate 3.6.8

 

4. Create Project in Eclipse

  • Create a Java Project exm. Hibernate_QuickStartMenu File → New → Java Project
  • .Add LibrariesRight click Project Hibernate_QuickStart → Build Path → Add Libraries → User Libraries →
    add the 2 user libraries orcl_jdbc and Hibernate 3.6.8

 

5. Create a POJO class Employee

package test;

public class Employee {
	private Integer empId = null;
	private String name;
	private Integer deptNo;

	public Integer getEmpId() {
		return empId;
	}

	public void setEmpId(Integer empId) {
		this.empId = empId;
	}

	public String getName() {
		return name;
	}

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

	public Integer getDeptNo() {
		return deptNo;
	}

	public void setDeptNo(Integer deptNo) {
		this.deptNo = deptNo;
	}
}

 

6. Create mapping file Employee.hbm.xml

<?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">
<hibernate-mapping>
        <class name="test.Employee" table="EMP">
                <id name="empId" type="int" column="EMPNO">
                        <generator class="sequence">
                                <param name="sequence">EMP_SEQ</param>
                        </generator>
                </id>
                <property name="name" type="java.lang.String" column="NAME"
                        update="true" insert="true"></property>
                <property name="deptNo" type="java.lang.Integer" column="DEPTNO"
                        update="true" insert="true"></property>
        </class>
</hibernate-mapping>

 

7. Create a Helper Class HibernateUtil

package test;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
	private static SessionFactory sessionFactory;
	static {
		try {
			sessionFactory = new Configuration().configure(
					"resources/hibernate.cfg.xml").buildSessionFactory();
		} catch (Throwable e) {
			System.err.println("Initial SessionFactory creation failed." + e);
			throw new ExceptionInInitializerError(e);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public static void shutdown() {
		getSessionFactory().close();
	}
}

 

8. Configuration file hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
        <session-factory>
                <!-- Connect Oracle via JDBC -->
                <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
                <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
                <property name="hibernate.connection.url">jdbc:oracle:thin:@192.168.72.129:1521:orcl</property>
                <property name="hibernate.connection.username">hib</property>
                <property name="hibernate.connection.password">hib</property>
                <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
                <property name="current_session_context_class">thread</property>

                <!-- Print all generated SQL to the console -->
                <property name="show_sql">true</property>
                <property name="format_sql">true</property>

                <!-- Mapped entities -->
                <mapping resource="resources/Employee.hbm.xml" />
        </session-factory>
</hibernate-configuration>

 

9. Test Class

package test;

import org.hibernate.Session;

public class TestEmp {
	public static void main(String[] args) {

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();

		Employee p = new Employee();
		p.setName("Hugo Schmidt");
		p.setDeptNo(10);

		int id = (Integer) session.save(p);
		System.out.println("ID: " + id);
		session.getTransaction().commit();

		HibernateUtil.shutdown();
	}
}

Run the class as Java Application and the result is:

SQL> select * from emp;

     EMPNO NAME                               DEPTNO
---------- ------------------------------ ----------
       100 Hugo Schmidt                           10

Project Structur with Hibernate in Eclipse

Project Structur with Hibernate in Eclipse

The type AnnotationConfiguration is deprecated

December 6th, 2011 . by admin

You got the message The type AnnotationConfiguration is deprecated when working with Hibernate > 3.6

...
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {

...
 sessionFactory =
	        new AnnotationConfiguration()
	            .configure()
	            .buildSessionFactory();
...

}

Solution:

1. use SuppressWarnings

place @SuppressWarnings(“deprecation”) before the class declaration

..
import org.hibernate.cfg.AnnotationConfiguration;
@SuppressWarnings("deprecation")"
public class HibernateUtil {

...
 sessionFactory =
	        new AnnotationConfiguration()
	            .configure()
	            .buildSessionFactory();
...

}
2. or use Configuration instead of AnnotationConfiguration
..
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

...
 sessionFactory =
	        new Configuration()
	            .configure()
	            .buildSessionFactory();
...

}

Connect Oracle database via JDBC

November 29th, 2011 . by admin

JDBC Thin Driver

  • communicate directly with the data source using a standard Java socket
  • is written 100% in Java and hence is platform independent
  • does not require any additional Oracle software on the client
  • driver supports only TCP/IP-based communication

 

Connect using Oracle Think Driver (via OracleDataSource)
String connectURL = "jdbc:oracle:thin:scott/tiger@//192.168.72.129:1521/orcl.mydom.com";
OracleDataSource ds = new OracleDataSource();
ds.setURL(connectURL);
Connection conn = ds.getConnection();

 

Connect using Oracle Think Driver (via DriverManager)
Class.forName("oracle.jdbc.OracleDriver");
String connectURL = "jdbc:oracle:thin:scott/tiger@192.168.72.129:1521:orcl";
Connection conn = DriverManager.getConnection(connectURL);

 

JDBC OCI Driver

  • OCI stands for Oracle Call Interface
  • called a thick driver
  • allows access Oracle database using a 3GL-Language such as C/C++
  • requires the OCI C libraries, Oracle Net libraries
  • until 9i Release 2 required the entire Oracle client installation
  • since 10g optional reqired just Oracle Instant Client

 

Connect using Oracle OCI Driver
String connectURL = "jdbc:oracle:oci:@myorcl";
Connection conn = DriverManager.getConnection (connectURL, "scott", "tiger" );

 

use OCI Driver when:
  • connect to Oracle other than TCP/IP
  • use OCI connection pooling
  • use TAF – Transparent Application Failover
  • when code run in middle tier, application server
  • OCI is faster before 9i, performance is no relevant since 9i verus thin driver

 

use Thin Driver when:
  • too many clients
  • portability

 

Install

Oracle JDBC Driver kann download from:

10g: http://www.oracle.com/technetwork/database/enterprise-edition/jdbc-10201-088211.html

11g: http://www.oracle.com/technetwork/database/enterprise-edition/jdbc-112010-090769.html

or you can find it direct in Oracle installation $ORACLE_HOME/jdbc/lib

exm: ojdbc5.jar is nessesary for connetion to Oracle Database 11g and must be in the LIBPATH

- for connection using OCI Driver, Oracle Client or minimal Oracle Instant Client must installed

 

Test Code

package test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import oracle.jdbc.pool.OracleDataSource;

public class TestOJDBCConnect {
	static void doShowEmp(Connection conn) throws SQLException {
		ResultSet rset = null;
		Statement stmt = null;
		stmt = conn.createStatement();
		rset = stmt.executeQuery("select empno, ename, job from emp");

		final int COL_EMPNO = 1;
		final int COL_ENAME = 2;
		final int COL_JOB = 3;

		while (rset.next()) {
			int empNo = rset.getInt(COL_EMPNO);
			String empName = rset.getString(COL_ENAME);
			String empJob = rset.getString(COL_JOB);
			System.out.println(empNo + " " + empName + " " + empJob);
		}
		rset.close();
		stmt.close();
	}

	static void doSelect(Connection conn, String sql) throws SQLException{
		Statement stmt = conn.createStatement();
		ResultSet rset = stmt.executeQuery(sql);
		if (rset.next())
			System.out.println(rset.getString(1));
		rset.close();
		stmt.close();
	}

	public static Connection getConnectionByDataSource() throws SQLException {
		String connectURL = "jdbc:oracle:thin:scott/tiger@//192.168.72.129:1521/orcl.mydom.com";
		OracleDataSource ds = new OracleDataSource();
		ds.setURL(connectURL);
		Connection conn = ds.getConnection();
		doSelect(conn, "select 'Connecting via DataSource..User is '|| initcap(USER) from dual");
		return conn;
	}

	public static Connection getConnectionByDriverManager() throws SQLException, ClassNotFoundException {
		Class.forName("oracle.jdbc.OracleDriver");
		String connectURL = "jdbc:oracle:thin:scott/tiger@192.168.72.129:1521:orcl";
		Connection conn = DriverManager.getConnection(connectURL);
		doSelect(conn, "select 'Connecting via DriverManager..User is '|| initcap(USER) from dual");
		return conn;
	}

	public static Connection getConnectionOCI() throws SQLException {
		String connectURL = "jdbc:oracle:oci:@myorcl";
		Connection conn = DriverManager.getConnection (connectURL, "scott", "tiger" );
		doSelect(conn, "select 'Connecting via OCI..User is '|| initcap(USER) from dual");
		return conn;
	}

	public static void main(String args[]) throws SQLException, ClassNotFoundException {
		Connection conn = null;

		conn = getConnectionByDataSource();
		conn.close();

		conn = getConnectionByDriverManager();
		conn.close();

		conn = getConnectionOCI();
		doShowEmp(conn);
		conn.close();
	}
}
  • jdbc:oracle:thin: is the prefix when connect using Thin driver
  • jdbc:oracle:oci: is the prefix when connect using OCI driver
  • scott is username
  • tiger is password
  • 192.168.72.129 is the ip of the database server (or hostname)
  • 1521 ist the port number
  • orcl.mydom.com is the service name
  • orcl is the SID
  • myorcl is the net service name from tnsnames.ora

 
.. the output in Eclipse console is:

Connecting via DataSource..User is Scott
Connecting via DriverManager..User is Scott
Connecting via OCI..User is Scott
7369 SMITH CLERK
7499 ALLEN SALESMAN
7521 WARD SALESMAN
7566 JONES MANAGER
7654 MARTIN SALESMAN
7698 BLAKE MANAGER
7782 CLARK MANAGER
7788 SCOTT ANALYST
7839 KING PRESIDENT
7844 TURNER SALESMAN
7876 ADAMS CLERK
7900 JAMES CLERK
7902 FORD ANALYST
7934 MILLER CLERK

build.xml – No grammar constraints (DTD or XML schema) detected for the document

January 5th, 2011 . by admin

When create file Ant build file build.xml in Eclipse , you get the message/warning:

No grammar constraints (DTD or XML schema) detected for the document.

build.xml

<?xml version="1.0" encoding="UTF-8"?>
<project name="project" default="default">

...

</project>

Solution:

Turn off validation for file build.xml
 

  • Windows->References->Validation->XML Validator(click button …)
     
  • -In Dialog Validation Filters for XML Validator
    .choice Exlude Group
    .click Button Add Rule..
     
  • -On Dialog New Filter Rule Wizard
    .choice Folder or file name
    .click Button Next
    .Input build.xml in field File or folder
    .Click button Finish
    .CLick button Ok in Dialog Validation Filters for XML Validator
    .CLick button Ok in Dialog References
    .Confirm Yes by Message The validation settings have changed. Afull rebuild is required..

Now the message No grammar constraints (DTD or XML schema detected for the document must now disappear


Ant, JavaDoc: package javax.servlet.http does not exist

January 4th, 2011 . by admin

When i generate JavaDoc per Ant task
 

<target name="javadoc" depends="compile">
		<mkdir dir="out/javadoc"/>
		<javadoc packagenames="*"
			sourcepath="src"
			defaultexcludes="yes"
			destdir="out/javadoc"
			author="true"
			version="true"
		    use="true"
			windowtitle="SecurID" />
	</target>

i get the error:

..
  [javadoc] T:\eclipse_ws\sid\src\action\AbmeldenAction.java:3: package javax.servlet.http does not exist
  [javadoc] import javax.servlet.http.HttpServletRequest;
  [javadoc]                          ^
  [javadoc] T:\eclipse_ws\sid\src\action\AbmeldenAction.java:4: package javax.servlet.http does not exist
  [javadoc] import javax.servlet.http.HttpServletResponse;
  [javadoc]                          ^
  [javadoc] T:\eclipse_ws\sid\src\action\AbmeldenAction.java:6: package org.apache.struts.action does not exist
  [javadoc] import org.apache.struts.action.Action;
  [javadoc]                                ^
  [javadoc] T:\eclipse_ws\sid\src\action\AbmeldenAction.java:7: package org.apache.struts.action does not exist
  [javadoc] import org.apache.struts.action.ActionForm;
  [javadoc]                                ^
..

Solution:

you must specify the classpath when run Javadoc

Define property myclasspath

<project name="sid" default="all" basedir=".">
	<property file="build/version.properties" />
	<property name="tomcat-home" value="T:\Tomcat 6.0" />
	<path id="myclasspath">
		<fileset dir="WebContent/WEB-INF/lib">
			<include name="**/*.jar" />
		</fileset>
		<fileset dir="${tomcat-home}/lib" includes="*.jar" />
	</path>
 

Compiling task:

<target name="compile" depends="init">
		<mkdir dir="out/tmp/classes"/>
		<javac classpathref="myclasspath" srcdir="src" destdir="out/tmp/classes">
		</javac>
	</target>

Doc generating task:

	<target name="javadoc" depends="compile">
		<mkdir dir="out/javadoc"/>
		<javadoc packagenames="*"
			classpathref="myclasspath"
			sourcepath="src"
			defaultexcludes="yes"
			destdir="out/javadoc"
			author="true"
			version="true"
		    use="true"
			windowtitle="SecurID" />
	</target>

 


Apache XML-RPC 3.1.3 step by step

December 11th, 2010 . by admin

Here is my first test with XML-RPC 3.1.3
- Server is Java XmlRpcServlet.
- Client is a simple Java client
The example come from Apache http://ws.apache.org/xmlrpc/server.html

 

1. Create a new Project in Eclipse

for example in Eclipse Helios click File->New->Dynamic Web Project
Project name: xmlrpctest
Target runtime is Apache Tomcat v6.0
Click Finish

 

2. Download the software

From page http://ws.apache.org/xmlrpc/download.html click distribution directory and choice a mirror which apache suggest
exm http://apache.myamplifiers.com//ws/xmlrpc/
Choice apache-xmlrpc-current-bin.zip. The current version is XML-RPC 3.1.3

 

3. Copy lib files

Unpack the file apache-xmlrpc-current-bin.zip
copy all following files to the lib directory of project xmlrpctest,
which you can find it in workspace directory of Eclipse

 Directory of C:\Java\ws\xmlrpctest\WebContent\WEB-INF\lib

12/10/2010  09:47 AM    <DIR>          .
12/10/2010  09:47 AM    <DIR>          ..
09/11/2009  02:43 PM            52,915 commons-logging-1.1.jar
09/11/2009  02:43 PM            34,407 ws-commons-util-1.0.2.jar
02/06/2010  05:13 PM            58,573 xmlrpc-client-3.1.3.jar
02/06/2010  05:12 PM           109,131 xmlrpc-common-3.1.3.jar
02/06/2010  05:14 PM            81,555 xmlrpc-server-3.1.3.jar

in Eclipse right click the project xmlrpctest->Refresh or press F5.
you will see the 5 jar files in xmlrpctest.WebContent.Web-INF.lib
and in xmlrpctest.Java Resources src.Web App Libraries

 

Eclipse Project Explorer
project structur xml-rpc

 

4. Create class Calculator

Create package: org.apache.xmlrpc.demo
-Righ click project xmlrpctest->New->Package
-Dialog New Java Package->name: org.apache.xmlrpc.demo
-Finish

Create class Calculator
-Right click package org.apache.xmlrpc.demo->New->Class
-Dialog New Java Class->name: org.apache.xmlrpc.demo
-Finish

Source of Calculator.java:

 package org.apache.xmlrpc.demo;
    public class Calculator {
                public int add(int i1, int i2) {
                        return i1 + i2;
                }
                public int subtract(int i1, int i2) {
                        return i1 - i2;
                }
    }

 

5. Create properties file XmlRpcServlet.properties

The property file must be called XmlRpcServlet.properties, and it must be located in the package org.apache.xmlrpc.webserver

Create package: org.apache.xmlrpc.webserver
-Righ click project xmlrpctest->New->Package
-Dialog New Java Package
package name: org.apache.xmlrpc.webserver
-Finish

Create file XmlRpcServlet.properties
-Right click src->New->Other..->File->Next
-File name: XmlRpcServlet.properties
-Finish

File XmlRpcServlet.properties:

Calculator=org.apache.xmlrpc.demo.Calculator

 

6. Edit file web.xml

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>xmlrpctest_run</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
	<servlet>
		<servlet-name>XmlRpcServlet</servlet-name>
		<servlet-class>org.apache.xmlrpc.webserver.XmlRpcServlet</servlet-class>
		<init-param>
			<param-name>enabledForExtensions</param-name>
			<param-value>true</param-value>
		</init-param>
	</servlet>
	<servlet-mapping>
		<servlet-name>XmlRpcServlet</servlet-name>
		<url-pattern>/xmlrpc</url-pattern>
	</servlet-mapping>
</web-app>

 

7. Create a client program

Right click package org.apache.xml.rpc.demo->New Class
Class name: SimpleClient

SimpleClient.java

package org.apache.xmlrpc.demo;

import java.net.URL;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;

public class SimpleClient {

	public SimpleClient() {
		try {
			System.out.println("Try to add 2 + 3 via XML-RPC...");
			XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
			config.setServerURL(new URL(
					"http://127.0.0.1:8080/xmlrpctest/xmlrpc"));
			XmlRpcClient client = new XmlRpcClient();
			client.setConfig(config);
			Object[] params = new Object[] { new Integer(2), new Integer(3) };
			Integer result = (Integer) client.execute("Calculator.add", params);
			System.out.println("The returned values is: " + result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		new SimpleClient();
	}
}

 

8. Run Test

-Open server view Window->Show Views->Servers

-Add project xmltest to Tomcat Sever
.Right click Tomcat v6.0 at localhost"->Add and Remove..
.Choice/Add xmlrpctest
.Finish

-Start Tomcat Sever
.Right click Tomcat v6.0 at localhost->Start

-Run Simple Client
Right click SimpleClient.java->Run As->Java Application

Output in Console View:

Try to add 2 + 3 via XML-RPC...
The returned values is: 5

 


Install Java, Tomcat, Eclipse

August 2nd, 2009 . by admin

Install Java SE JDK 6 Update 14

java - Download Page: http://java.sun.com/javase/downloads/index.jsp
– Downloaded File: jdk-6u14-windows-i586.exe (size 75.242 KB)
– Double click file jdk-6u14-windows-i586.exe
– Follow the instructions for installation, accepting all defaults
– This installation installs both the JDK and JRE
C:\Program Files\Java>dir
 Volume in drive C has no label.
 Volume Serial Number is B4E6-78AA
Directory of C:\Program Files\Java
07/23/2009  12:36 PM    <DIR>          .
07/23/2009  12:36 PM    <DIR>          ..
07/23/2009  12:37 PM    <DIR>          jdk1.6.0_14
07/23/2009  12:36 PM    <DIR>          jre6
 0 File(s)              0 bytes
 4 Dir(s)  15,862,722,560 bytes free

Set Environment Variable, Path
Right click Computer -> Properties -> Advanced -> Environment Variable

- Set new Variable:

JAVA_HOME=C:\Program Files\Java\jdk1.6.0_14

- Chang the new PATH to:

%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;
C:\Program Files\Java\jdk1.6.0_14\bin

Test
 

C:\>java -version
java version "1.6.0_14"
Java(TM) SE Runtime Environment (build 1.6.0_14-b08)
Java HotSpot(TM) Client VM (build 14.0-b16, mixed mode, sharing)
C:\>javac -version
javac 1.6.0_14

 

Install Tomcat Version 6

tomcat.apache.org - Prerequisite to install Tomcat : Java Runtime Environment (JRE)
– Download from http://tomcat.apache.org/download-60.cgi
– Choose Windows Service Installer
– Downloaded File: apache-tomcat-6.0.20.exe
– Double click the exe file to run install Tomcat

 

Steps to install Tomcat
Welcome to to Apache Tomcat Setup Wizard Click Next
License Agreement Click I Agree
Choose Components Select Example
Click Next
Choose Install Location Accept default Deatination Folder
C:\Program Files\Apache Software Foundation\Tomcat 6.0
or specify C:\Tomcat6
Click Next
Configuaration Accept default path C:\Program Files\Java\jre6
Click Install
Finish Click Finish to quit setup

 

Install Eclipse 3.5 Galileo

eclipse.org - Download Eclipse: http://www.eclipse.org/downloads/
– Choose Eclipse IDE for Java EE Developers (189 MB)
File: eclipse-jee-galileo-win32.zip
– Unzip to c:\eclipse
– Create a shortcut for C:\eclipse\eclipse.exe
– Prerequisite to run Eclipse: Java Runtime Environment (JRE)
 

 


The import javax.servlet cannot be resolved

August 1st, 2009 . by admin

For the first time when you try to write your first HelloWord Servlet on your beautiful environment (Java 6, Eclipse 3.5, 3.4 Gallileo or Granymede, Tomcat6.. ) for example:

package com.example.web;

import com.example.model.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class BeerSelect extends HttpServlet {
...

it can happen tha the Editor is full with red error:
The import javax.servlet cannot be resolved
HttpServlet cannot be resolved to a type

Problem: The path to the Tomcat libraries is missing in "Java Build Path"

TODO:
1. Server Runtime Environments:
Check Menu Windows -References -> Server -> Runtime Environments
It must be a entry ‘Apache Tomcat v 6.0′ on the list

2. Check path to the Tomcat libraries in Java Build Path:
- Right click the Project -> Properties -> Java Build Path – Tab Libraries
It must be a entry Apache Tomcat v6.0[Apache Tomcat v6.0] on the list
 If it is not the case:
- Click Project Facets in the properties list
- Click Tab Runtime. Select checkbox "Apache Tomcat v6.0". Click Apply.
- Goback to "Java Build Path", tab Liberaries, you must see that
"Apache Tomcat v6.0[Apache Tomcat v6.0]" is now on the list
-Click Ok to finish the change
 


« Previous Entries