/**
  * Here we demonstrate the mass replace functions.
  * See example5.tlt for more information.
  */

/**
  * Note about SQL, I was using the postgreSQL database, table creation:
    CREATE TABLE person (
        person_id INT NOT NULL PRIMARY KEY,
        firstname VARCHAR(20) NOT NULL,
        lastname VARCHAR(20) NOT NULL,
        date_of_birth DATE
    );
    INSERT INTO person VALUES (1, 'John', 'Doe', NULL);
    INSERT INTO person VALUES (2, 'Marilyn', 'Monroe', '1926-06-01');
    INSERT INTO person VALUES (3, 'Charles', 'de Gaulle', '1890-11-22');
    INSERT INTO person VALUES (4, 'John', 'Lennon', '1940-10-9');
  */

import ee.mare.indrek.jtlt.*;
import ee.mare.indrek.jtlt.macros.*;

import java.sql.*;
import java.io.*;
import java.util.*;

public class Example5 {
  public static void main (String[] args) throws Exception
  {
    // In general when using templates these two lines would you run at
    // application initialization time, storing the generator somewhere
    HtmlTemplateContext ctx = new HtmlTemplateContext ();
    HtmlTemplateGenerator gen = new HtmlTemplateGenerator ("example5.tlt", ctx);

    // And then whenever you need to use the template you just call this
    HtmlTemplate tlt = gen.createHtmlTemplate();

    // But now back to the topic - mass replace functions

    // Case 1
    Map kv = new HashMap ();
    kv.put("key1", "This is key1 replacement.");
    kv.put("key2", "This is key2 replacement.");
    kv.put("key3", "This is key3 replacement.");

    // We instance the sub block and change tlt.replace key-values from the map
    tlt.instance ("sub1", kv);

    // We can also do that manually, so that we could do our own additional replace-s
    tlt.lock("sub1");
    tlt.replace(kv);
    tlt.unlock ();

    // Case 2, using SQL resultset, I use postgresql
    Class.forName("org.postgresql.Driver");   // initialize the driver
    Connection con = DriverManager.getConnection("jdbc:postgresql:test", "john", "");
    PreparedStatement stmt = con.prepareStatement ("select * from person");

    ResultSet res = stmt.executeQuery();

    // And now we replace all the values into the template making as man instances
    // of given sub block as there are rows in the resultset.
    tlt.instance_rows ("person", res);

    // Lets try to do this manually
    res = stmt.executeQuery ();

    while (res.next()) {
      tlt.lock("manual"); // for every row in result we do
      tlt.replace (res);
      tlt.unlock ();
    }

    System.out.println (tlt.toString());
  }
}



syntax highlighted by Code2HTML, v. 0.9.1