Fedora Linux Support Community & Resources Center

Go Back   FedoraForum.org > Fedora Resources > Guides & Solutions (No Questions)
FedoraForum Search

Forgot Password? Join Us!

Guides & Solutions (No Questions) Post your guides here (No links to Blogs accepted). You can also append your comments/questions to a guide, but don't start a new thread to ask a question. Use another forum for that.

Reply
 
Thread Tools Search this Thread Display Modes
  #1  
Old 15th March 2005, 07:10 AM
nephila Offline
Registered User
 
Join Date: Feb 2005
Posts: 121
Java Howtos

Series of howtos:

1. Install Java
2. Apache Ant
3. Apache Tomcat
4. Web Applications with Apache Torque and Apache Velocity

Last edited by nephila; 16th March 2005 at 08:11 AM.
Reply With Quote
  #2  
Old 15th March 2005, 07:16 AM
nephila Offline
Registered User
 
Join Date: Feb 2005
Posts: 121
First Howto: Install java on a red hat based distro (also works on mandrake)

1. Software Used
* Java JDK version 1.5
* Red Hat Linux version 9, Fedora Core 2&3.

2. Prerequisites and Outcomes

2.1 Prerequisites
* You should be comfortable with using the shell to navigate the file system.
* Know how to use a text editor to create and edit files.

2.2 Outcomes
* After completing this how to you should have the JDK installed on your computer.

3. Introduction
In order to develop software using the Java language you will need to install a suitable compiler and interpreter on your computer. This will enable you to compile and run Java programs that you write.

The process is relatively straight forward, run the setup program, set the JAVA_HOME and PATH variables and finally test everything with a simple program.

4. Installing the JDK
Note
This how-to assumes you have root privileges and that you are to install Java system wide so that all users can use the Java tools.

1. Start a shell. Copy the linux installer to the /usr/local directory.
Code:
cp jdk-1_5_0-linux-i586.bin /usr/local
2. Now change into the /usr/local directory and run the installer.
Code:
cd /usr/local
chmod +x jdk-1_5_0-linux-i586.bin
./jdk-1_5_0-linux-i586.bin
3. Read through the licence agreement and if you agree type yes. This will start the installer.
4. If everything goes well you should end up with output that ends with:
Code:
Done.
5. Create a symbolic link to the jdk so that its easy to upgrade later.
Code:
ln -s /usr/local/jdk1.5.0 /usr/local/java
5. Setting the Path Variable
1. Create the file named java.sh in the directory named /etc/profile.d using your favourite text editor. I used Vi.
Code:
cd /
touch /etc/profile.d/java.sh
vi /etc/profile.d/java.sh
2. Add the following to the file.
Code:
export JAVA_HOME=/usr/local/java
export PATH=${PATH}:${JAVA_HOME}/bin
3. Make the script executable.
Code:
chmod +x /etc/profile.d/java.sh
4. Log out and then log in again for the changes to take effect.

6. Compiling and Running Programs
We will now test our installation by compiling and running a simple Java Program.

1. Start your favourite text editor and type the following program in it, then save it in a file named HelloWorld.java in your home directory.
Code:
class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}
2. To compile the program you use the Java Compiler:
Code:
cd ~
javac HelloWorld.java
If you don't get any errors then everything went well. If you get errors, check firstly that you saved the program in your homw directory and that it is named HelloWorld.java.

3. To run the program, type:
Code:
java HelloWorld
you should get the following output:
Code:
Hello World!
Congratulations, you have successfully installed the Java 1.5 JDK and tested it.

7. What's Next?
Now you can use the JDK to compile and run all your Java programs! Check out some of the other howtos here

Last edited by nephila; 15th March 2005 at 07:19 AM.
Reply With Quote
  #3  
Old 15th March 2005, 07:25 AM
nephila Offline
Registered User
 
Join Date: Feb 2005
Posts: 121
Second Howto: Apache Ant

1. Software Used
* Apache Ant version 1.6.2
* Red Hat Linux version 9.0

2. Prerequisites and Outcomes
2.1 Prerequisites
* You should have sufficient programming skills using the Java Language. You probably wouldn't be reading this if you didn't! ;o)
* You should have Java installed and correctly set up, with an environment variable JAVA_HOME pointing to the location of java.
* You should be comfortable with extracting archives and copying and renaming folders.

2.2 Outcomes
* See how useful Apache Ant is and enjoy the benefits of building a project with it.

3. Introduction

Apache Ant is a Java based build tool. It is used to aid developers in compiling and building their projects, and while it might not be useful for very small projects, its use is easily recognised for medium to large scale projects.

One should be clear about what Ant is and what it is not. Ant is not a project management tool and neither is it a compiler. As has been stated, Ant is a build tool. Typically, in a java project the source code has to be compiled, the resulting byte code added to a jar file and the javadoc tool is run on the source code to generate an API. Performing these tasks separately requires a certain amount of work, which is where Ant comes in. Ant can perform these and other tasks quite easily allowing the developer to type one command and have all these tasks done.

I hope that this how to shows how easy Ant can be to use as well as the numerous benefits that can be gained: easy build process, faster build process, more productivity!

4. Installing Ant
Note
This how to assumes that you have root privileges and want to install ant system wide so that all users can use it.

1. Copy the Apache Ant package to the /usr/local directory and extract it there.
Code:
cp apache-ant-1.6.2-bin.tar.gz /usr/local/
cd /usr/local/
tar xzvf apache-ant-1.6.2-bin.tar.gz
2. Make a symbolic link to ant, so that if you install a later version all you'll have to do is update the symbolic link:
Code:
ln -s /usr/local/apache-ant-1.6.2 ant
3. If you installed Java according to my howtos you should have a file named java.sh in the /etc/profile.d directory. If not, you should create the file now.
Code:
vi /etc/profile.d/java.sh
Add the ANT_HOME variable and edit the path variable so that it contains the bin directory of the ant folder. My java.sh looks as follows:
Code:
export JAVA_HOME=/usr/local/jdk1.5.0
export ANT_HOME=/usr/local/ant
export PATH=${PATH}:${JAVA_HOME}/bin:${ANT_HOME}/bin
4. Log out and then log back in again for the changes to take effect.
5. Open a shell and type
Code:
ant
you should recieve output similar to:
Code:
Buildfile: build.xml does not exist!
Build failed
That's it, Ant is installed!

5. Creating a Simple Project
5.1 Creating the Necessary Directories.

1. Create a directory to work in, I used project.
Code:
mkdir project
cd project
2. Now create the following directories in the project directory.
Code:
mkdir bin
mkdir src
mkdir src/test
5.2 Creating the Files
1. Create the shell script that will run the program. Create a file named test in the project/bin directory, with the following content:
Code:
java -jar test.jar
Don't forget to make the script executable:
Code:
chmod +x test
2. Create the Java program. Create a file named Test.java in the project/src/test directory.
Code:
package test;
public class Test {
   public static void main(String[] args) {
      System.out.println("Test Successful!");
   }
}
3. Now create the manifest file. Create a file named manifest in the project/src directory.
Code:
Manifest-Version: 1.0
Main-Class: test.Test
4. Finally create the ant build script. Create a file named build.xml in the project directory.
Code:
<?xml version="1.0" ?>
<project name="Acme Test Project" default="all" basedir=".">

    <!--
        Perform initialization of the build process,
        this entails creating some directories.
    -->
    <target name="init">        
        <mkdir dir="build" />
        <mkdir dir="doc" />
    </target>

    <!--
        Compile the project's source code.
    -->
    <target name="compile" depends="init">
        <javac 
            srcdir="src" 
            destdir="build" 
            debug="on"
            deprecation="on"
            optimize="on" />
    </target>

    <!--
        Create the project's jar file
    -->
    <target name="jar" depends="compile">
        <jar 
            jarfile="bin/test.jar" 
            basedir="build"
            manifest="src/manifest" />
    </target>

    <!--
        Run the javadoc tool on the project's source code to generate the
        javadoc api.
    -->
    <target name="javadoc">        
        <javadoc 
            sourcepath="src" 
            destdir="doc" 
            packagenames="test.*"
            author="true" 
            protected="true" 
            version="true" 
            use="true" 
            splitindex="true"
            failonerror="True" />
    </target>
    
    <!--
        Clean out the build directory, ie: temporary files used in the 
        build process.
    -->
    <target name="clean">
        <delete dir="build" />
    </target>
    
    <!--
        Performs a standard build, ie:
        - compiling the source code
        - generating the jar file
        - performing javadoc documentation
    -->
    <target name="all" depends="jar, javadoc" />

</project>
6. See Ant Run
1. Run ant from within the project directory.
Code:
[trevor@nephila project]$ ant
Buildfile: build.xml
 
init:
    [mkdir] Created dir: /home/trevor/project/build
    [mkdir] Created dir: /home/trevor/project/doc
 
compile:
    [javac] Compiling 1 source file to /home/trevor/project/build
 
jar:
      [jar] Building jar: /home/trevor/project/bin/test.jar
 
javadoc:
  [javadoc] Generating Javadoc
  [javadoc] Javadoc execution
  [javadoc] Loading source files for package test...
  [javadoc] Constructing Javadoc information...
  [javadoc] Standard Doclet version 1.5.0
  [javadoc] Building tree for all the packages and classes...
  [javadoc] Building index for all the packages and classes...
  [javadoc] Building index for all classes...
 
all:
 
BUILD SUCCESSFUL
Total time: 9 seconds
2. Change into the bin directory and run the test shell script.
Code:
cd bin/
./test
Test Successful!
7. What's Next?
Check out the Ant manual to discover the large amount of built in tasks that Ant can perform. And if a task that you require doesn't exist you can write your own Ant tasks!

Try to integrate Ant into some of your existing projects, I'm sure you'll find it a simple process.
Reply With Quote
  #4  
Old 15th March 2005, 07:33 AM
nephila Offline
Registered User
 
Join Date: Feb 2005
Posts: 121
Third Howto: Apache Tomcat

1. Software Used
* Apache Ant version 1.6.2
* Apache Tomcat version 5.0.1
* Red Hat Linux version 9.0

2. Prerequisites and Outcomes

2.1 Prerequisites
* You should already have Java installed along with Apache Ant as we'll use these to build a simple web application to test our installation.
* You should have the Servlet API either in the servlet jar file or in the j2ee jar file. If you do not have this you should get the J2EE package and install that as well.
* You should be comfortable using the shell to move, copy, and rename files, as well as use text editor to create and edit files.

2.2 Outcomes
* You should have tomcat installed on your system.
* Have built and deployed a simple web application using Apache Ant.

3. Introduction
Apache Tomcat is the reference implementation of the Servlet Specification, this means it is a servlet and JSP container, but it can also be used as a standalone web server, although it is not really suited to that!

This how to will explain how to set up the Standard Binary Distribution and how to set up a simple web application to test it.

4. Installing Tomcat
We will first install the tomcat package.

1. Copy the Tomcat Binary package to the /usr/local directory and extract it there.
Code:
cp jakarta-tomcat-5.0.18.tar.gz /usr/local/
cd /usr/local/
tar xzvf jakarta-tomcat-5.0.18.tar.gz
2. Create a symbolic link to the tomcat package named tomcat.
Code:
 ln -s /usr/local/jakarta-tomcat-5.0.18 tomcat
3. If you installed Java according to my howtos you should have a file named java.sh in the /etc/profile.d directory. If not, you should create the file now.
Code:
vi /etc/profile.d/java.sh
4. Add the CATALINA_HOME variable with the value /usr/local/tomcat.
Code:
export CATALINA_HOME=/usr/local/tomcat
5. Edit the PATH variable to include the bin directory of the CATALINA_HOME directory.
Code:
export PATH=${PATH}:${CATALINA_HOME}/bin
My java.sh looks as follows:
Code:
export JAVA_HOME=/usr/local/jdk1.5.0
export ANT_HOME=/usr/local/ant
export CATALINA_HOME=/usr/local/tomcat
export PATH=${PATH}:${JAVA_HOME}/bin:${ANT_HOME}/bin:${CATALINA_HOME}/bin
6. Log out and then log back in again for the changes to take effect.
7. Open a shell and type startup.sh, you should get similar output to:
Code:
startup.sh
Using CATALINA_BASE:   /usr/local/tomcat
Using CATALINA_HOME:   /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JAVA_HOME:       /usr/local/jdk1.5.0
8. After a while tomcat should be up and running. You can verify this by opening your favourite web browser and browsing: http://localhost:8080. You should get the Tomcat setup successfully message.

You can always check /usr/local/tomcat/logs for any error messages. Usually tomcat will crash if a port its trying to connect to is already in use or if the user trying to run tomcat doesn't have sufficient privileges.

5. Creating a Simple Web Application
We will now create a simple web application that makes use of Java Servlet Technology.

1. Create a new directory to work in, I used test.
Code:
mkdir test
2. Now create the necessary sub directories.
Code:
mkdir test/src
mkdir test/src/html
mkdir test/src/java
mkdir test/src/web
mkdir test/src/java/test
3. Create the HTML file named index.html in the test/src/html directory:
Code:
<HTML>
    <HEAD>
        <TITLE>Say Hello</TITLE>
    </HEAD>
    <BODY>
        <P><A HREF="sayhello">Say Hello</A></P>
    </BODY>
</HTML>
4. Create the Java Servlet file named TestServlet.java in the test/src/java/test directory:
Code:
package test;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class TestServlet extends HttpServlet {

    public void doGet(
                HttpServletRequest request, 
                HttpServletResponse response) 
                throws ServletException, 
                IOException {
        PrintWriter out;
        response.setContentType("text/html");
        out = response.getWriter();
        out.println("<HTML>\n<HEAD><TITLE>Hello World!</TITLE></HEAD>\n");
        out.println("<BODY><H2>Hello World!</H2></BODY>\n</HTML>");
        out.close();
    }
    
}
5. Create the web deployment descriptor file named web.xml in the test/src/web directory:
Code:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

    <display-name>Acme Test Project</display-name>
    <description>Acme Test for JProject</description>
    
    <servlet>
        <servlet-name>TestServlet</servlet-name>
        <servlet-class>test.TestServlet</servlet-class>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>TestServlet</servlet-name>
        <url-pattern>/sayhello</url-pattern>
    </servlet-mapping>        
    
</web-app>
6. Finally, create the ant build script. If you don't have Aapche Ant, you should get it and install it now. Create the file named build.xml in the test directory:
Code:
<?xml version="1.0" ?>
<project name="Acme Test Project" default="all" basedir=".">

    <!--
        Set the classpath to include the library jars in the
        lib directory.
    -->
    <path id="classpath">
        <fileset dir="/usr/local/j2sdkee1.3.1/lib">
            <include name="**/*.jar" />
        </fileset>
    </path>

    <!--
        Perform initialization of the build process,
        this entails creating some directories.
    -->
    <target name="init">
        <mkdir dir="build" />
        <mkdir dir="build/WEB-INF" />
        <mkdir dir="build/WEB-INF/classes" />
    </target>

    <!--
        Compile the project's source code.
    -->
    <target name="compile" depends="init">
        <javac 
            srcdir="src/java" 
            destdir="build/WEB-INF/classes" 
            classpathref="classpath"
            debug="on"
            deprecation="on"
            optimize="on" />
    </target>

    <!--
        Create the project's war file
    -->
    <target name="jar" depends="compile">
        <copy file="src/web/web.xml" todir="build/WEB-INF" />
        <copy todir="build">
            <fileset dir="src/html" />
        </copy>
        <jar jarfile="test.war" basedir="build" />
    </target>

    <!--
        Run the javadoc tool on the project's source code to generate the
        javadoc api.
    -->
    <target name="javadoc">
        <javadoc 
            sourcepath="src/java" 
            destdir="doc/api" 
            packagenames="test.*"
            classpathref="classpath"
            author="true" 
            protected="true" 
            version="true" 
            use="true" 
            splitindex="true"
            failonerror="True" />
    </target>
    
    <!--
        Clean out the build directory, ie: temporary files used in the 
        build process.
    -->
    <target name="clean">
        <delete dir="build" />
    </target>

    <!--
        Performs a standard build.
    -->
    <target name="all" depends="jar, javadoc" />

</project>
Note
You will have to supply the location of the j2ee jar file or the servlet jar file so that the application will compile. This is done in the build file, my location is /usr/local/j2sdkee1.3.1/lib, but yours may differ and you should change the build.xml file accordingly.

6. Deploying and Testing the Application
1. Now run Apache Ant from within the test directory by typing:
Code:
ant
This will build the web application and package it in a web archive named test.war
2. Copy the web archive file test.war to the webapps subdirectory of the tomcat home directory:
Code:
cp test.war %CATALINA_HOME%/webapps
3. Run tomcat by typing startup.sh and once tomcat has loaded point your web browser at: http://localhost:8080/test.
4. Click the link that says Say Hello. That should load the servlet and display Hello World!

7. What's Next?
You can now use your tomcat installation to write servlets and JSP!
Reply With Quote
  #5  
Old 15th March 2005, 02:42 PM
krisnalada Offline
Registered User
 
Join Date: Jan 2005
Location: United kingdom
Age: 34
Posts: 79
many thanks ,)
__________________
Linux Registered User # 379941
Reply With Quote
  #6  
Old 16th March 2005, 08:04 AM
nephila Offline
Registered User
 
Join Date: Feb 2005
Posts: 121
Fourth Howto: Web Applications with Apache Torque and Apache Velocity

1. Software Used
* MySQL version 4.0.12 standard
* MySQL Driver version 3.0.9
* Apache Ant version 1.6.2
* Apache Torque version 3.1
* Apache Velocity version 1.4
* Apache Tomcat version 5.0.1
* Red Hat Linux version 9

2. Prerequisites and Outcomes
2.1 Prerequisites
* You should have sufficient programming skills using the Java Language. You probably wouldn't be reading this if you didn't! ;o)
* You should have already installed Apache Ant, Apache Tomcat and MySQL and be comfortable using these packages. If not, now would be a good time to go install them and get aquainted with them.
* You should be comfortable with extracting archives, copying and renaming files, creating files and using a text editor to edit files.
* We are going to use java servlet technology for the web application, you should have some general background on servlets and have the servlet API or the J2EE API.

2.2 Outcomes
* See how useful Apache Torque is and enjoy the benefits of generating an object model with it.
* See how powerful the Apache Velocity template engine is and use it to generate dynamic content in a web application.
* See how easy it is to generate dynamic content from a database using the powerful combination of Apache Torque and Apache Velocity.

3. Introduction
Most interactive web applications today use a databse on the backend. Using Java Servlets is a powerful way to get data from the database into the display and vice versa. A combination of Servlets and JDBC has one diadvantage though, you are still required to write SQL code. This is not a problem if the database is small but as soon as it becomes large and complex, it becomes a pain to write all the SQL code and even more so when that code has to be debugged. Apache Torque is a tool that maps relational databases to an object model. This eliminates the need to write SQL code, and instead you can use simple Java objects to perform complex database transactions. This has two benefits, programmers that are not fluent in SQL can simply focus on Java, and further complex SQL is avoided completly, thus only Java code needs to be debugged.

Using the Model - View - Controller pattern, developers often use Java Server Pages on the back end. While JSP is powerful and has numerous supporters, it has one fundamental flaw. It combines java code with HTML code. And while it is not possible to completely separate Java and HTML, the more separation one can achieve, the better. This is where Velocity has a major advantage: the code contained in the HTML is minimal and simplistic, this is what you need when your page designers are not programmers. The programmers focus on the Java Code, and the page designers focus on the HTML code. They never get in each other's way! A combination of Apache Velocity and Apache Torque is a very powerful but easy to use solution for developing complex dynamic web applications. I hope that this how-to will prove this!

4. MySQL
The first thing that we'll want to do is to set up a user account for Apache Torque, it really is a bad idea to use the MySQL root account. To do this, log into MySQL as root and execute the command:

Code:
GRANT alter,create,delete,drop,insert,select,update ON *.* TO torque@127.0.0.1 IDENTIFIED BY 'torque';
Log out from root and then try to log into the torque account:
Code:
mysql -u torque -p
Enter torque as the password. If you get in, everything is set, if not you probably had a typo in the commands above. Try it again.

5. Generating the OM with Torque
5.1 Extracting the packages
1. Create a directory to work in. I used howto. Also create a temporary directory for the mysql driver.
Code:
mkdir howto
mkdir howto/driver
2. Copy the torque packages and the mysql driver package to the howto directory from where you downloded them to.
Code:
cd howto
cp ~/torque-3.1.tar.gz .
cp ~/torque-gen-3.1.tar.gz .
cp ~/mysql java driver.zip .
3. Extract the torque runtime and generator packages.
Code:
tar xzvf torque-3.1.tar.gz
tar xzvf torque-gen-3.1.tar.gz
4. Now extract the mysql driver package in the driver directory.
Code:
cd driver
unzip ../mysql\ java\ driver.zip
5. Copy the MySQL driver jar file to the torque generator's lib directory.
Code:
cp mysql-connector-java-3.0.9-stable/mysql-connector-java-3.0.9-stable-bin.jar ../torque-gen-3.1/lib/
5.2 Generating the OM
1. Copy the torque runtime jar file torque.jar from the torque runtime lib directory to the torque generator lib directory.
Code:
cp ../torque-3.1/lib/torque.jar ../torque-gen-3.1/lib
2. Change into the torque generator directory and edit the build.properties file with your favourite text editor. I used vi.
Code:
cd ../torque-gen-3.1
vi build.properties
3. Change the properties in the file so that they match the ones given below. If a property is not given below, you can leave it "as is" in the file.
Code:
torque.project = bookstore
torque.database = mysql
torque.targetPackage = com.kazmier.om
torque.database.createUrl = jdbc:mysql://127.0.0.1/mysql
torque.database.buildUrl = jdbc:mysql://127.0.0.1/bookstore
torque.database.url = jdbc:mysql://127.0.0.1/bookstore
torque.database.driver = org.gjt.mm.mysql.Driver
torque.database.user = torque
torque.database.password = torque
torque.database.host = 127.0.0.1
4. Create the database schema in a file named bookstore-schema.xml in the schema subdirectory in the torque generator directory.
Code:
touch schema/bookstore-schema.xml
Add the following database schema to the file, save it and exit from your editor.
Code:
<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<!DOCTYPE database SYSTEM
 "http://db.apache.org/torque/dtd/database_3_1.dtd">

<database
  name="bookstore"
  defaultIdMethod="idbroker">

  <table name="book" description="Book Table">
    <column
      name="book_id"
      required="true"
      primaryKey="true"
      type="INTEGER"
      description="Book Id"/>
    <column
      name="title"
      required="true"
      type="VARCHAR"
      size="255"
      description="Book Title"/>
    <column
      name="isbn"
      required="true"
      type="VARCHAR"
      size="24"
      javaName="ISBN"
      description="ISBN Number"/>
    <column
      name="publisher_id"
      required="true"
      type="INTEGER"
      description="Foreign Key Publisher"/>
    <column
      name="author_id"
      required="true"
      type="INTEGER"
      description="Foreign Key Author"/>
    <foreign-key foreignTable="publisher">
      <reference
        local="publisher_id"
        foreign="publisher_id"/>
    </foreign-key>
    <foreign-key foreignTable="author">
      <reference
        local="author_id"
        foreign="author_id"/>
    </foreign-key>
  </table>
  <table name="publisher" description="Publisher Table">
    <column
      name="publisher_id"
      required="true"
      primaryKey="true"
      type="INTEGER"
      description="Publisher Id"/>
    <column
      name="name"
      required="true"
      type="VARCHAR"
      size="128"
      description="Publisher Name"/>
  </table>
  <table name="author" description="Author Table">
    <column
      name="author_id"
      required="true"
      primaryKey="true"
      type="INTEGER"
      description="Author Id"/>
    <column
      name="first_name"
      required="true"
      type="VARCHAR"
      size="128"
      description="First Name"/>
    <column
      name="last_name"
      required="true"
      type="VARCHAR"
      size="128"
      description="Last Name"/>
  </table>
</database>
5. Edit the id-table-schema.xml file in the schema directory, changing the database name to:
Code:
<database name="bookstore">
6. Now generate the object model using Apache Ant by running the following commands, one after the other from within the torque generator directory.
Code:
ant -f build-torque.xml
ant -f build-torque.xml create-db
ant -f build-torque.xml id-table-init-sql
ant -f build-torque.xml insert-sql
ant -f build-torque.xml compile
ant -f build-torque.xml javadocs
In each case above you should get a number of output messages and finally a message like:
Code:
BUILD SUCCESSFUL
Total time: 15 seconds
You should also check that all the SQL statements execute successfully, the create-db and insert-sql targets will execute SQL. You should check for a message saying something like 11 of 11 SQL statements executed successfully.
7. Open the javadoc api for your object model in your favourite web browser.
Code:
konqueror ./src/javadoc/index.html
You should have two packages: com.kazmier.om and com.kazmier.om.map, with a number of classes in each. Of importance is to note that you will have four classes for each table in the database, for example the book entity:
Code:
Book
BookPeer
BaseBook
BaseBookPeer

To be continued...
Reply With Quote
  #7  
Old 16th March 2005, 08:06 AM
nephila Offline
Registered User
 
Join Date: Feb 2005
Posts: 121
Continuation

5.3 Jarring the OM
We are going to create a library of our object model so that it may be used by other applications. This involves creating a jar file containing the class files of our object model.

1. Create a jar file containing the classes of your object model from within the torque generator directory.
Code:
cd bin/classes/
jar -cvf ../../bookstore-om.jar *
cd ../../../
6. Testing the OM
We are going to test that our object model is working correctly and add some data to the database using it.

1. Make sure you are in the howto directory and create the test directory and a subdirectory named lib in the test directory.
Code:
mkdir test
mkdir test/lib
2. Copy the MySQL driver jar file to the test/lib directory.
Code:
cp driver/mysql-connector-java-3.0.9-stable/mysql-connector-java-3.0.9-stable-bin.jar test/lib/
3. Copy all the torque runtime libraries from the torque-3.1/lib directory to the test/lib directory.
Code:
cp torque-3.1/lib/* test/lib/
4. Copy the object model jar file bookstire-om.jar that you created to the test/lib directory.
Code:
cp torque-gen-3.1/bookstore-om.jar test/lib/
5. Copy the file named Torque.properties in the torque-3.1 directory to the test directory and rename it to torque.properties
Code:
cp torque-3.1/Torque.properties test/torque.properties
6. Edit the file named torque.properties in the test directory, changing the properties as given below.
Code:
torque.defaults.connection.driver = org.gjt.mm.mysql.Driver
torque.defaults.connection.url = jdbc:mysql://localhost:3306/bookstore
torque.defaults.connection.user = torque
torque.defaults.connection.password = torque
torque.database.default=bookstore
torque.database.bookstore.adapter=mysql
torque.dsfactory.bookstore.connection.driver = org.gjt.mm.mysql.Driver
torque.dsfactory.bookstore.connection.url = jdbc:mysql://localhost:3306/bookstore
torque.dsfactory.bookstore.connection.user = torque
torque.dsfactory.bookstore.connection.password = torque
Note
The properties file contains a number of properties that are commented out using a hash symbol (#). You can ignore these properties.

7. Change into the test directory and create the following java program in that directory, save it in a file named Test.java
Code:
import com.kazmier.om.*;
import org.apache.torque.Torque;
import org.apache.torque.util.Criteria;

public class Test {

    public static void main(String[] args) {
        try {
            Torque.init("torque.properties");
            
            Publisher addison = new Publisher();
            addison.setName("Addison Wesley Professional");
            addison.save();

            Author bloch = new Author();
            bloch.setFirstName("Joshua");
            bloch.setLastName("Bloch");
            bloch.save();

            Author stevens = new Author();
            stevens.setFirstName("W.");
            stevens.setLastName("Stevens");
            AuthorPeer.doInsert(stevens);

            Book effective = new Book();
            effective.setTitle("Effective Java");
            effective.setISBN("0-618-12902-2");
            effective.setPublisher(addison);
            effective.setAuthor(bloch);
            effective.save();
            
            System.out.println("Data added to database!");
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
8. Create the following ant build script in the test directory, saving it in a file named build.xml
Code:
<?xml version="1.0" ?>
<project name="Torque" default="main" basedir=".">
    
<!-- set the classpath to include the jars in the lib dir -->
    <path id="cp">
        <fileset dir="lib">
            <include name="**/*.jar" />
            <include name="**/*.class" />
        </fileset>
    </path>
    
    <target name="compile">
        <mkdir dir="classes" />
        <javac srcdir="." destdir="classes" classpathref="cp" />
    </target>
    
    <target name="jar" depends="compile">
        <copy file="torque.properties" todir="classes" />
        <jar destfile="lib/test.jar" basedir="classes"/>
        <delete dir="classes" />
    </target>
    
    <target name="run" depends="jar">
        <java classname="Test" classpathref="cp" />
    </target>
</project>
9. Now run the ant build script which should compile the java program and run it.
Code:
ant run
Everything should run smoothly, and you should end up with output similar to:
Code:
Buildfile: build.xml
compile:
    [mkdir] Created dir: /opt/howto/test/classes
    [javac] Compiling 1 source file to /opt/howto/test/classes
 
jar:
     [copy] Copying 1 file to /opt/howto/test/classes
      [jar] Building jar: /opt/howto/test/lib/test.jar
   [delete] Deleting directory /opt/howto/test/classes
 
run:
     [java] log4j:WARN No appenders could be found for logger (org.apache.torque.TorqueInstance).
     [java] log4j:WARN Please initialize the log4j system properly.
     [java] Data added to database!
 
BUILD SUCCESSFUL
Total time: 6 seconds
10. Make sure that the database actually contains the data. Remember you will have to supply the correct password.
Code:
mysql -h 127.0.0.1 -u torque -p
Enter password:
mysql> use bookstore;
mysql> select * from book;
you should get the following output:
Code:
+---------+----------------+---------------+--------------+-----------+
| book_id | title          | isbn          | publisher_id | author_id |
+---------+----------------+---------------+--------------+-----------+
|    1000 | Effective Java | 0-618-12902-2 |         1000 |      1000 |
+---------+----------------+---------------+--------------+-----------+
1 row in set (0.00 sec)
If you got the correct output, everything is working well. You have generated an object model that works!!

7. Using the OM with Velocity
What we want to do now is to use the object model we generated, in a web application using Apache Velocity. You will see after completing this, that Velocity and Torque are a perfect match and make your life a lot easier!

7.1 Unpack Velocity
1. Copy the Apache Velocity package to the howto directory.
Code:
cp ~/velocity-1.4.tar.gz .
2. Unpack the velocity archive:
Code:
tar xzvf velocity-1.4.tar.gz
7.2 Create the Web Application
1. Create the necessary directories:
Code:
mkdir bookstore
mkdir bookstore/lib
mkdir bookstore/src
mkdir bookstore/src/java
mkdir bookstore/src/templates
mkdir bookstore/src/web
mkdir bookstore/src/web/WEB-INF
2. Copy the torque runtime libraries from the torque runtime lib directory to the bookstore/lib directory.
Code:
cp torque-3.1/lib/* bookstore/lib/
3. Copy the mysql driver jar file to the bookstore/lib directory.
Code:
cp driver/mysql-connector-java-3.0.9-stable/mysql-connector-java-3.0.9-stable-bin.jar bookstore/lib/
4. Copy the object model jar file that you created earlier from the torque generator directory to the bookstore/lib directory.
Code:
cp torque-gen-3.1/bookstore-om.jar bookstore/lib/
5. Copy the velocity jar file from the velocity directory to the bookstore/lib directory. Ensure to use the jar with the dependencies, usually denoted by "dep" in the filename.
Code:
cp velocity-1.4/velocity-dep-1.4.jar bookstore/lib/
6. Copy the torque.properties file from the test directory to the bookstore/src/templates directory.
Code:
cp test/torque.properties bookstore/src/templates/

Last edited by nephila; 16th March 2005 at 08:08 AM.
Reply With Quote
  #8  
Old 16th March 2005, 08:09 AM
nephila Offline
Registered User
 
Join Date: Feb 2005
Posts: 121
Continuation 2

7.3 Creating the Source Files
1. Create the velocity.properties file in the bookstore/src/web directory. This file tells velocity to use a class loader to load the templates, this is because we put all the templates in jar file.
Code:
resource.loader = class
class.resource.loader.class = org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
runtime.log = velocity.log
2. Create the web.xml file in the bookstore/src/web/WEB-INF directory. We simply map our servlet to the books url, and tell it to load the velocity properties.
Code:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
    "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>
    <servlet>
        <servlet-name>BookStore</servlet-name>
        <servlet-class>BookServlet</servlet-class>
        <init-param>
            <param-name>org.apache.velocity.properties</param-name>
            <param-value>/velocity.properties</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
  
    <servlet-mapping>
        <servlet-name>BookStore</servlet-name>
        <url-pattern>/books</url-pattern>
    </servlet-mapping>
</web-app>
3. Create the velocity template books.vm in the bookstore/src/templates directory. This is the HTML code that will be displayed. Notice how we directly use the classes from the object model that we generated, with a subtle mix of the velocity template language. You should see the velocity documentation for more information on the Template Language.
Code:
<HTML>
    <HEAD>
        <TITLE>BooksStore Booklisting</TITLE>
    </HEAD>
    <BODY>
        <H1>Books:</H1>
        <TABLE WIDTH="100%">
            <TR>
                <TH>ISBN</TH>
                <TH>Title</TH>
                <TH>Author</TH>
                <TH>Publisher</TH>
            </TR>
            #foreach ( $book in $books )
                <TR>
                    <TD>$book.getISBN()</TD>
                    <TD>$book.getTitle()</TD>
                    <TD>$book.getAuthor().getFirstName() $book.getAuthor().getLastName()</TD>
                    <TD>$book.getPublisher().getName()</TD>
                </TR>
            #end
        </TABLE>
    </BODY>
</HTML>
4. Now we create the servlet class. This is going to place the data from the object model into the velocity context, which will then be merged with the template file. Create the file BookServlet.java in the bookstore/src/java directory.
Code:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.Vector;

import javax.servlet.ServletConfig;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.torque.Torque;
import org.apache.torque.util.Criteria;
import org.apache.velocity.Template;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.context.Context;
import org.apache.velocity.servlet.VelocityServlet;

import com.kazmier.om.BookPeer;

/**
 * @author Trevor Miller
 * @version 1.2
 */
public class BookServlet extends VelocityServlet {
    
    /**
     * @see javax.servlet.GenericServlet#init()
     */
    public void init() throws UnavailableException {
        try {
            PropertiesConfiguration conf = new PropertiesConfiguration();
            conf.load(this.getClass().getClassLoader().getResourceAsStream("torque.properties"));
            Torque.init(conf);
        } catch (Exception e) {
            throw new UnavailableException("Error: "+e.getMessage());
        }
    }

    /**
     * @see org.apache.velocity.servlet.VelocityServlet#handleRequest(
     *   javax.servlet.http.HttpServletRequest, 
     *   javax.servlet.http.HttpServletResponse, 
     *   org.apache.velocity.context.Context)
     */
    public Template handleRequest( HttpServletRequest request, 
        	HttpServletResponse response, Context context )
    	{
        		// define a velocity template
                Template template = null;
                try
                {
                    // add the list of books to the velocity context
                    context.put("books", BookPeer.doSelect(new Criteria()));
                    template =  getTemplate("books.vm");
                }                
                catch( Exception e )
                {
                    System.out.println("Error " + e);
                }
                return template;
            }
    
    
    /**  
     *  A fancier version of loadConfiguration(), this will
     *  set the log file to be off of the webapp root, and
     *  will do the same with the file loader paths
     * @param config
     * @return
     * @throws IOException
     * @throws FileNotFoundException
     */
   protected Properties loadConfiguration(ServletConfig config )
        throws IOException, FileNotFoundException
    {
        /*
         *  get our properties file and load it
         */

        String propsFile = config.getInitParameter(INIT_PROPS_KEY);        
        Properties p = new Properties();
        if ( propsFile != null ) {
            String realPath = getServletContext().getRealPath(propsFile);
            if ( realPath != null ) {
                propsFile = realPath;
            }
            p.load( new FileInputStream(propsFile) );
        }

        /*
         *  first, normalize our velocity log file to be in the 
         *  webapp
         */

        String log = p.getProperty( Velocity.RUNTIME_LOG);
        if (log != null ) {
            log = getServletContext().getRealPath( log );            
            if (log != null) {
                p.setProperty( Velocity.RUNTIME_LOG, log );
            }
        }

        /*
         *  now, if there is a file loader resource path, treat it the
         *  same way.
         */

        String path = p.getProperty( Velocity.FILE_RESOURCE_LOADER_PATH );
        if ( path != null) {
            path = getServletContext().getRealPath(  path );
            if ( path != null) {
                p.setProperty( Velocity.FILE_RESOURCE_LOADER_PATH, path );
            }
        }
        return p;
    }  
}
5. Finally we create the ant build script that's going to build our web application archive. Create the file build.xml in the bookstore directory.
Code:
<?xml version="1.0" ?>
<project name="Web Application" default="war" basedir=".">
    
    <path id="cp">
        <fileset dir="lib">
            <include name="**/*.jar" />
        </fileset>
        <fileset dir="/usr/local/j2sdkee1.3.1/lib">
            <include name="**/j2ee.jar" />
        </fileset>
    </path>
    
    <target name="init">
        <mkdir dir="build" />
        <mkdir dir="build/WEB-INF" />
        <mkdir dir="build/WEB-INF/lib" />
       <mkdir dir="build/WEB-INF/classes" /> 
    </target>
    
    <target name="compile" depends="init">
        <javac srcdir="src/java" destdir="build/WEB-INF/classes" classpathref="cp" />
    </target>
    
    <target name="templates">
        <jar destfile="build/WEB-INF/lib/templates.jar" basedir="src/templates" />
    </target>
    
    <target name="war" depends="compile, templates">
        <copy todir="build/WEB-INF/lib">
            <fileset dir="lib" />
        </copy>
        <copy todir="build/" file="src/web/velocity.properties" />
        <copy todir="build/WEB-INF" file="src/web/WEB-INF/web.xml" />
        <jar destfile="bookstore.war" basedir="build" />
    </target>
    
</project>
Note
You will have to supply the location of the j2ee jar file or the servlet jar file so that the application will compile. This is done in the build file, my location is /usr/local/j2sdkee1.3.1/lib, but yours will surely differ. You should change the build.xml file accordingly.

You should not place this jar file in the bookstore/lib directory, as it will be copied to the web application and cause tomcat to crash on startup!

7.4 Deploy and Test the Web Application
1. Build the web application archive, from within the bookstore directory.
Code:
cd bookstore/
ant
2. Deploy the newly built bookstore.war file on tomcat by copying it into the tomcat/webapps directory.
Code:
cp bookstore.war $CATALINA_HOME/webapps/
3. Start tomcat and launch your favourite browser pionting it to the http://localhost:8080/bookstore/ location. you should get a directory listing containing two files:
Code:
velocity.log
velocity.proprties
If you have this, its all go for the application. It may be that the velocity.log file is not present, this will indicate a problem with velocity.
4. Now browse the location: http://localhost:8080/bookstore/books, and you should get a listing of the book that is in the database!

Note
If you have gotten this far and everyting is working, congratulations!!

8. What's Next?
It may seem like a lot of effort to go through this whole process just to get a little data to display on the page. But from here it will be really easy to add another servlet to the web application and another velocity template to get more functionality. You should write more servlets and templates to display the authors and publishers in the database. Don't forget to add appropriate entries to the web.xml file!
Reply With Quote
  #9  
Old 16th March 2005, 08:18 AM
imdeemvp Offline
Registered User
 
Join Date: Feb 2004
Age: 46
Posts: 8,256
Looks like crackers is not the only professional java geek.....
__________________
HELP with JAVA, MP3's, Wireless, Repo's, YUM, Partitions, System Monitors, Nvidia, ATI drivers, LIMEWIRE PRO & MORE!.

Easiest and most friendly desktop ever is PCLinuxOS! Includes all this apps. Just try it.

"The greater the struggle THE greater the achievment."

Do you know HIM?

If you are an idiot click here. NThis will test you linux skills :D
Reply With Quote
  #10  
Old 17th March 2005, 03:56 AM
crackers Offline
Retired Community Manager
 
Join Date: Feb 2004
Location: Seattle, WA, USA
Age: 57
Posts: 3,423
Well done, nephila! What poor imdeemvp fails to realize that what you explained in such a wonderfully clear and concise manner is just the beginning...

Have you thought about a career in tech writing?
__________________
Linux User #28251 (April '93)
Professional Java Geek :cool:
Reply With Quote
  #11  
Old 17th March 2005, 06:33 AM
nephila Offline
Registered User
 
Join Date: Feb 2005
Posts: 121
Thanx! Just hope it helps anyone who needs it. I plan to write a complete Java book someday, around a thousand pages or so. But that's a big project and because I want decent work its gonna take extra long.
Reply With Quote
  #12  
Old 17th March 2005, 07:49 AM
imdeemvp Offline
Registered User
 
Join Date: Feb 2004
Age: 46
Posts: 8,256
Hey, l will leave the java geek stuff to you guys....as long as I can understand I am good to go.

Now, nephila is this your creation or you have a source for such an impressive how-to?
__________________
HELP with JAVA, MP3's, Wireless, Repo's, YUM, Partitions, System Monitors, Nvidia, ATI drivers, LIMEWIRE PRO & MORE!.

Easiest and most friendly desktop ever is PCLinuxOS! Includes all this apps. Just try it.

"The greater the struggle THE greater the achievment."

Do you know HIM?

If you are an idiot click here. NThis will test you linux skills :D
Reply With Quote
  #13  
Old 18th March 2005, 07:57 AM
nephila Offline
Registered User
 
Join Date: Feb 2005
Posts: 121
This is all my work. Of course inspiration has come in a wide variety from a wide number of sources, but I wouldn't post this here if it wasn't mine, that's plagiarism and that's a moral felony!
Reply With Quote
  #14  
Old 19th May 2005, 11:13 PM
iongrey Offline
Registered User
 
Join Date: Apr 2005
Posts: 1
Thanks for the great tutorial nephila. I've tried soo many methods to install java and fail miserably. Once I messed up installing Java soo bad, i did the stupidiest thing and reinstalled Fedora. But enough rambling, i just want to say YOUR GUIDE IS AWESOME AND THANK YOU SO MUCH FOR IT!!
Reply With Quote
  #15  
Old 30th May 2005, 10:54 AM
stephanj Offline
Registered User
 
Join Date: Mar 2005
Posts: 11
I have just had a look at this WONDERFUL tutorial. I must say, PLEASE tell me where I can buy your book (when you finally write it).

Excellent job.......... I will try all stages of your tutorial in the next week and hope to give you some feedback if you don't mind.

Thanks again
Reply With Quote
Reply

Tags
howtos, java

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
General Fedora 10 Howtos michelangelo Guides & Solutions (No Questions) 3 7th December 2008 12:36 PM
Any Howtos 4 Ati and Fc7 out ? starfly Hardware & Laptops 31 10th June 2007 09:41 PM
Silly Linux HOWTOs tashirosgt Linux Chat 6 20th January 2005 09:35 AM


Current GMT-time: 12:20 (Saturday, 01-11-2014)

TopSubscribe to XML RSS for all Threads in all ForumsFedoraForumDotOrg Archive
logo

All trademarks, and forum posts in this site are property of their respective owner(s).
FedoraForum.org is privately owned and is not directly sponsored by the Fedora Project or Red Hat, Inc.

Privacy Policy | Term of Use | Posting Guidelines | Archive | Contact Us | Founding Members

Powered by vBulletin® Copyright ©2000 - 2012, vBulletin Solutions, Inc.

FedoraForum is Powered by RedHat
Alangayam Travel Photos on Instagram - Caloundra Travel Photos on Instagram - Mbanga Instagram Photos