Powered by SmartDoc
ENGLISHJAPANESE

Program Codes

proServ

build.xml
<!-- A "project" describes a set of targets that may be requested
     when Ant is executed.  The "default" attribute defines the
     target which is executed if no specific target is requested,
     and the "basedir" attribute defines the current working directory
     from which Ant executes the requested task.  This is normally
     set to the current working directory.
-->


<project name="Calling prolog from Servlet" default="compile" basedir=".">


<!-- Property Definitions

     Each of the following properties are used by convention in this
     build file.  The values specified can be overridden at run time by
     adding a "-Dname=value" argument to the command line that invokes Ant.
     This technique is normally used to copy the values of the ANT_HOME
     and TOMCAT_HOME environment variables into the "ant.home" and
     "tomcat.home" properties, which are normally not defined explicitly.

     app.name          Base name of this application, used to
                       construct filenames and directories.

     deploy.home       The name of the directory into which the
                       deployment hierarchy will be created.
                       Normally, this will be the name of a
                       subdirectory under $TOMCAT_HOME/webapps.

     dist.home	       The name of the base directory in which
                       distribution files are created.

     dist.src          The name of the distribution JAR file
                       containing the application source code,
                       to be stored in the "dist.home" directory.
                       This filename should end with ".jar".

     dist.war          The name of the Web ARchive (WAR) file
                       containing our deployable application.
                       This filename should end with ".war".

     javadoc.home      The name of the base directory in which
                       the JavaDoc documentation for this application
                       is generated.

     tomcat.home       The name of the base directory in which
                       Tomcat has been installed.  This value is
                       normally set automatically from the value
                       of the TOMCAT_HOME environment variable.

     In the example below, the application being developed will be deployed
     to a subdirectory named "myapp", and will therefore be accessible at:

       http://localhost:8080/myapp
-->

  <property name="app.name"       value="proServ"/>
  <property name="deploy.home"    value="${tomcat.home}/webapps/${app.name}"/>
  <property name="dist.home"      value="${deploy.home}"/>
  <property name="dist.src"       value="${app.name}.jar"/>
  <property name="dist.war"       value="${app.name}.war"/>
  <property name="javadoc.home"   value="${deploy.home}/javadoc"/>


<!-- The "prepare" target is used to construct the deployment home
     directory structure (if necessary), and to copy in static files
     as required.  In the example below, Ant is instructed to create
     the deployment directory, copy the contents of the "web/" source
     hierarchy, and set up the WEB-INF subdirectory appropriately.
-->

  <target name="prepare">
    <mkdir dir="${deploy.home}"/>
    <copydir src="web" dest="${deploy.home}"/>
    <mkdir dir="${deploy.home}/WEB-INF"/>
    <copyfile src="etc/web.xml" dest="${deploy.home}/WEB-INF/web.xml"/>
    <mkdir dir="${deploy.home}/WEB-INF/classes"/>
    <mkdir dir="${deploy.home}/WEB-INF/lib"/>
    <copydir src="lib" dest="${deploy.home}/lib"/>
    <mkdir dir="${javadoc.home}"/>
  </target>


<!-- The "clean" target removes the deployment home directory structure,
     so that the next time the "compile" target is requested, it will need
     to compile everything from scratch.
-->

  <target name="clean">
    <deltree dir="${deploy.home}"/>
  </target>


<!-- The "compile" target is used to compile (or recompile) the Java classes
     that make up this web application.  The recommended source code directory
     structure makes this very easy because the <javac> task automatically
     works its way down a source code hierarchy and compiles any class that
     has not yet been compiled, or where the source file is newer than the
     class file.  After compilation is complete, any non-Java files (such as
     properties files containing resource bundles) found in the source code
     hierarchy are copied to a corresponding position in the destination
     directory hierarchy.

     Feel free to adjust the compilation option parameters (debug,
     optimize, and deprecation) to suit your requirements.  It is also
     possible to base them on properties, so that you can adjust this
     behavior at runtime.

     The "compile" task depends on the "prepare" task, so the deployment
     home directory structure will be created if needed the first time.
-->

  <target name="compile" depends="prepare">
    <javac srcdir="src" destdir="${deploy.home}/WEB-INF/classes"
           classpath="${deploy.home}/WEB-INF/classes"
           debug="on" optimize="off" deprecation="off"/>
  </target>



<!-- The "javadoc" target is used to create the Javadoc API documentation
     for the Java classes in this web application.  It is assumed that
     this documentation is included in the deployed application, so the
     example below generates the Javadoc HTML files in a subdirectory under
     the deployment home directory.
-->

  <target name="javadoc" depends="prepare">
    <!-- TODO -->
  </target>


<!-- The "all" target rebuilds everything by executing the "clean"
     target first, which forces the "compile" target to compile all
     source code instead of just the files that have been changed.
-->

  <target name="all" depends="clean,prepare,compile,javadoc"/>


<!-- The "dist" target builds the distribution Web ARchive (WAR) file
     for this application, suitable for distribution to sites that wish
     to install your application.  It also creates a JAR file containing
     the source code for this application, if you wish to distribute
     that separately.
-->

  <target name="dist" depends="prepare,compile">
    <jar jarfile="${dist.home}/${dist.src}"
         basedir="."/>
    <jar jarfile="${dist.home}/${dist.war}"
         basedir="${deploy.home}"/>
  </target>


</project>
etc/web.xml
<?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>
            prologServlet
        </servlet-name>
        <servlet-class>
            prologServ
        </servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>
            prologServlet
        </servlet-name>
        <url-pattern>
            /prologTest
        </url-pattern>
    </servlet-mapping>

</web-app>
src/prologServ.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
// 
//   JPL package
//
import jpl.Atom;
import jpl.Variable;
import jpl.Term;
import jpl.Query;
import jpl.JPL;

public class prologServ extends HttpServlet {
	public void doGet (
		HttpServletRequest req,
		HttpServletResponse res
		) throws ServletException, IOException
	{
		res.setContentType( "text/html" );
		PrintWriter out = res.getWriter();
		out.println( "<html><head><title>Finding decendents of the person</title></head>" );
		out.println( "<body>Using getParameter() method<br>" );

		JPL.init(); // We initialize JPL
		Term consult_arg[] = { 
			//
			// We have to specify the location of prolog program in full
			//
			new Atom( "/WinApps/jakarta-tomcat/webapps/proServ/WEB-INF/classes/test.pl" ) 
		};
		//
		// We consult 'test.pl'
		//
		Query consult_query = 
			new Query( 
				"consult", 
				consult_arg );

		boolean consulted = consult_query.query();

		if ( !consulted ){
			out.println( "Consult failed" );
			System.exit( 1 );
		}

		Enumeration enum = req.getParameterNames();
		while( enum.hasMoreElements() ) {
			String name = (String)enum.nextElement();
			String value = req.getParameter( name );
			out.println( name + "=" + value + "<br>" );
			// 
			//   We pass the task to test3 below
			//
			String descendent = test3( value ).name();
			out.println( "descendent = " +  descendent + "<br>" );
		}
		out.println( "</body></html>" );
		out.close();
	}
	
	//
	//  This is test3 method. 
	//  The type of the return value is Atom.
	//
	static Atom
	test3( String person )
	{
		//
		// We construct the query, descendent_of( X, Person )
		// where Person is instantiated already when called
		Variable X = new Variable();
		Term args[] = { 
			X,
			new Atom( person )
		};
		Query query = 
			new Query( 
				"descendent_of", 
				args );

		//
		// Obtain the first solution to return
		//
		java.util.Hashtable solution =	query.oneSolution();
		return (Atom)solution.get( X );
	}

	public void doPost (
		HttpServletRequest req,
		HttpServletResponse res
		) throws ServletException, IOException
	{
		doGet( req, res );
	}
}
web/index.html
<html>
<head>
<meta HTTP-EQUIV="Content-Type" CONTENT="text/html"">
<title>Calling prolog from Java</title>
</head>
<body>
<form action="/proServ/prologTest" method="POST">
Name: <input type="text" name="name">
<input type=submit value="SUBMIT">
</form>
</body>
</html>
part of server.xml
<Context path="/proServ" docBase="webapps/proServ" debug="0" reloadable="true" > 
</Context>

proServ2

build.xml
<!-- A "project" describes a set of targets that may be requested
     when Ant is executed.  The "default" attribute defines the
     target which is executed if no specific target is requested,
     and the "basedir" attribute defines the current working directory
     from which Ant executes the requested task.  This is normally
     set to the current working directory.
-->


<project name="Calling prolog and RDB from Servlet" default="compile" basedir=".">


<!-- Property Definitions

     Each of the following properties are used by convention in this
     build file.  The values specified can be overridden at run time by
     adding a "-Dname=value" argument to the command line that invokes Ant.
     This technique is normally used to copy the values of the ANT_HOME
     and TOMCAT_HOME environment variables into the "ant.home" and
     "tomcat.home" properties, which are normally not defined explicitly.

     app.name          Base name of this application, used to
                       construct filenames and directories.

     deploy.home       The name of the directory into which the
                       deployment hierarchy will be created.
                       Normally, this will be the name of a
                       subdirectory under $TOMCAT_HOME/webapps.

     dist.home	       The name of the base directory in which
                       distribution files are created.

     dist.src          The name of the distribution JAR file
                       containing the application source code,
                       to be stored in the "dist.home" directory.
                       This filename should end with ".jar".

     dist.war          The name of the Web ARchive (WAR) file
                       containing our deployable application.
                       This filename should end with ".war".

     javadoc.home      The name of the base directory in which
                       the JavaDoc documentation for this application
                       is generated.

     tomcat.home       The name of the base directory in which
                       Tomcat has been installed.  This value is
                       normally set automatically from the value
                       of the TOMCAT_HOME environment variable.

     In the example below, the application being developed will be deployed
     to a subdirectory named "myapp", and will therefore be accessible at:

       http://localhost:8080/myapp
-->

  <property name="app.name"       value="proServ2"/>
  <property name="deploy.home"    value="${tomcat.home}/webapps/${app.name}"/>
  <property name="dist.home"      value="${deploy.home}"/>
  <property name="dist.src"       value="${app.name}.jar"/>
  <property name="dist.war"       value="${app.name}.war"/>
  <property name="javadoc.home"   value="${deploy.home}/javadoc"/>


<!-- The "prepare" target is used to construct the deployment home
     directory structure (if necessary), and to copy in static files
     as required.  In the example below, Ant is instructed to create
     the deployment directory, copy the contents of the "web/" source
     hierarchy, and set up the WEB-INF subdirectory appropriately.
-->

  <target name="prepare">
    <mkdir dir="${deploy.home}"/>
    <copydir src="web" dest="${deploy.home}"/>
    <mkdir dir="${deploy.home}/WEB-INF"/>
    <copyfile src="etc/web.xml" dest="${deploy.home}/WEB-INF/web.xml"/>
    <mkdir dir="${deploy.home}/WEB-INF/classes"/>
    <mkdir dir="${deploy.home}/WEB-INF/lib"/>
    <copydir src="lib" dest="${deploy.home}/lib"/>
    <mkdir dir="${javadoc.home}"/>
  </target>


<!-- The "clean" target removes the deployment home directory structure,
     so that the next time the "compile" target is requested, it will need
     to compile everything from scratch.
-->

  <target name="clean">
    <deltree dir="${deploy.home}"/>
  </target>


<!-- The "compile" target is used to compile (or recompile) the Java classes
     that make up this web application.  The recommended source code directory
     structure makes this very easy because the <javac> task automatically
     works its way down a source code hierarchy and compiles any class that
     has not yet been compiled, or where the source file is newer than the
     class file.  After compilation is complete, any non-Java files (such as
     properties files containing resource bundles) found in the source code
     hierarchy are copied to a corresponding position in the destination
     directory hierarchy.

     Feel free to adjust the compilation option parameters (debug,
     optimize, and deprecation) to suit your requirements.  It is also
     possible to base them on properties, so that you can adjust this
     behavior at runtime.

     The "compile" task depends on the "prepare" task, so the deployment
     home directory structure will be created if needed the first time.
-->

  <target name="compile" depends="prepare">
    <javac srcdir="src" destdir="${deploy.home}/WEB-INF/classes"
           classpath="${deploy.home}/WEB-INF/classes"
           debug="on" optimize="off" deprecation="off"/>
  </target>



<!-- The "javadoc" target is used to create the Javadoc API documentation
     for the Java classes in this web application.  It is assumed that
     this documentation is included in the deployed application, so the
     example below generates the Javadoc HTML files in a subdirectory under
     the deployment home directory.
-->

  <target name="javadoc" depends="prepare">
    <!-- TODO -->
  </target>


<!-- The "all" target rebuilds everything by executing the "clean"
     target first, which forces the "compile" target to compile all
     source code instead of just the files that have been changed.
-->

  <target name="all" depends="clean,prepare,compile,javadoc"/>


<!-- The "dist" target builds the distribution Web ARchive (WAR) file
     for this application, suitable for distribution to sites that wish
     to install your application.  It also creates a JAR file containing
     the source code for this application, if you wish to distribute
     that separately.
-->

  <target name="dist" depends="prepare,compile">
    <jar jarfile="${dist.home}/${dist.src}"
         basedir="."/>
    <jar jarfile="${dist.home}/${dist.war}"
         basedir="${deploy.home}"/>
  </target>


</project>
etc/web.xml
<?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>
            prologServlet
        </servlet-name>
        <servlet-class>
            prologServ2
        </servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>
            prologServlet
        </servlet-name>
        <url-pattern>
            /prologTest
        </url-pattern>
    </servlet-mapping>

</web-app>
src/prologServ2.java
//
//   for Servlet
//
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
// 
//   JPL package
//
import jpl.Atom;
import jpl.Variable;
import jpl.Term;
import jpl.Query;
import jpl.JPL;
import java.util.Hashtable;
import jpl.Compound;
import jpl.Util;
import jpl.Integer;
//
//   for SQL
//
import java.sql.*;

public class prologServ2 extends HttpServlet {
    public void doGet (
        HttpServletRequest req,
        HttpServletResponse res
        ) throws ServletException, IOException
    {
        res.setContentType( "text/html" );
        PrintWriter out = res.getWriter();
        out.println( "<html><head><title>Finding decendents of the person</title></head>" );
        out.println( "<body>Using SWI-prolog and MySQL<br>" );

        load_prog();    // Loading test2.pl
        assert_facts(); // Asserting facts into prolog

        Enumeration enum = req.getParameterNames();
        while( enum.hasMoreElements() ) {
            String name = (String)enum.nextElement();
            String value = req.getParameter( name );
            out.println( name + "=" + value + "<br>" );
            test4( value, out );
        }
        // JPL.halt(); this causes Tomcat shutdown
        abolish_facts();
        out.println( "</body></html>" );
        out.close();
    }
    
    public void doPost (
        HttpServletRequest req,
        HttpServletResponse res
        ) throws ServletException, IOException
    {
        doGet( req, res );
    }

    static void
    load_prog()
    {
        JPL.init();

        Term consult_arg[] = { 
            new Atom( "/WinApps/jakarta-tomcat/webapps/proServ2/WEB-INF/classes/test2.pl" )
        };
        Query consult_query = 
            new Query( 
                "consult", 
                consult_arg );

        boolean consulted = consult_query.query();
        
        if ( !consulted ){
            System.err.println( "Consult failed" );
            System.exit( 1 );
        }
    }

    static void
    assert_facts() {
        try {
            Class.forName( "org.gjt.mm.mysql.Driver" );
            String url = "jdbc:mysql://ks15e0f00/mysqltest?user=YourID&password=YourPassword";
            Connection con = DriverManager.getConnection( url );

            Statement select = con.createStatement();
            String sql = "select * from child_of";
            ResultSet res = select.executeQuery( sql );

            while( res.next() ) {
                Term child = new Atom( res.getString( "child" ) );
                Term parent = new Atom( res.getString( "parent" ) );
                Term pair = new Compound( "child_of", Util.toTermArray( child, parent ) );
                
                Query assert_query = 
                    new Query( 
                              "assert", 
                              pair );
                assert_query.oneSolution();
            }
            select.close();
            con.close();
        }
        catch ( Exception e ) {
            e.printStackTrace();
        }
    }

    static void
    test4( String person, PrintWriter out )
    {
        Variable X = new Variable();
        Term args[] = { 
            X,
            new Atom( person )
        };
        Query query = 
            new Query( 
                "descendent_of", 
                args );

        out.println( "querying descendent_of( X, " + person + " ) <br>" );

        while ( query.hasMoreSolutions() ){
            java.util.Hashtable solution =
                query.nextSolution();
            out.println( "X = " + solution.get( X ) + "<br>" );
        }
    }

    static void abolish_facts() {
        Term pred = new Atom( "child_of" );
        Term num = new Integer( 2 );
        Term rem = new Compound( "/", Util.toTermArray( pred, num ) );

        Query query = 
                new Query( 
                          "abolish", 
                              rem );
        query.oneSolution();
    }
}
web/index.html
<html>
<head>
<meta HTTP-EQUIV="Content-Type" CONTENT="text/html"">
<title>Calling prolog from Java</title>
</head>
<body>
<form action="/proServ2/prologTest" method="POST">
Name: <input type="text" name="name">
<input type=submit value="SUBMIT">
</form>
</body>
</html>