Вы находитесь на странице: 1из 23

6/21/2014 Dukes Soccer League: commits@dukessoccerleague.kenai.

com: Archive Project Kenai


https://kenai.com/projects/dukessoccerleague/lists/commits/archive/2011-12/message/0 1/23
Kenai.com will be unavailable due to the Jira 6 upgrade from Friday June 20th at 6pm
PDT(Saturday 2am UTC) through June 21st 2014 at 12:01 am PDT(8:01am Saturday UTC). We
apologize for any inconvenience this may cause.
[dukessoccerleague~source-code-repository:9] Database Implemented
Back to List Archive
Chronological | Threaded
Previous Message Next
Previous Thread Next
From: Harita@...
To: commits@...
Subject: [dukessoccerleague~source-code-repository:9] Database Implemented
Date: Tue, 27 Dec 2011 05:27:57 +0000
Project: dukessoccerleague
Repository: source-code-repository
Revision: 9
Author: Harita
Date: 2011-12-27 05:27:54 UTC
Link:
Log Message:
------------
Database Implemented
Revisions:
----------
9
Modified Paths:
---------------
DukesSoccerLeague/src/java/sl314/model/LeagueService.java
DukesSoccerLeague/src/java/sl314/view/ListLeagueServlet.java
DukesSoccerLeague/src/java/sl314/controller/EnterPlayerAction.java
DukesSoccerLeague/src/java/sl314/controller/SelectLeagueAction.java
DukesSoccerLeague/src/java/sl314/controller/SelectDivisionAction.java
DukesSoccerLeague/src/java/sl314/model/Player.java
DukesSoccerLeague/web/WEB-INF/web.xml
DukesSoccerLeague/src/java/sl314/controller/AddLeagueAction.java
DukesSoccerLeague/src/java/sl314/model/RegisterService.java
Added Paths:
------------
DukesSoccerLeague/src/java/sl314/model/ObjectIdDAO.java
DukesSoccerLeague/src/java/sl314/model/LeagueDAO.java
DukesSoccerLeague/src/java/sl314/model/PlayerDAO.java
Diffs:
6/21/2014 Dukes Soccer League: commits@dukessoccerleague.kenai.com: Archive Project Kenai
https://kenai.com/projects/dukessoccerleague/lists/commits/archive/2011-12/message/0 2/23
------
Index: DukesSoccerLeague/src/java/sl314/model/PlayerService.java
===================================================================
--- DukesSoccerLeague/src/java/sl314/model/PlayerService.java (revision 8)
+++ DukesSoccerLeague/src/java/sl314/model/PlayerService.java (revision 9)
@@ -1,128 +0,0 @@
-/*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
-
-package sl314.model;
-
-import java.io.File;
-import java.io.FileReader;
-import java.io.BufferedReader;
-import java.io.FileWriter;
-import java.io.PrintWriter;
-import java.io.IOException;
-
-/**
- *
- * @author Harita
- */
-public class PlayerService {
- private String dataDirectory;
- public PlayerService(String dataDirectory) {
- this.dataDirectory = dataDirectory;
- }
- public Player getPlayer(String name) {
-
- Player player = readPlayer(name);
-
- if ( player == null ) {
- player = new Player(name);
- }
-
- return player;
- }
- public void save(Player player) {
- // Store the player.
- storePlayer(player);
- // This is a poor design because it will allow duplicate player
- // records in the data file.
- }
-private Player readPlayer(String search_name) {
- File playerFile = new File(dataDirectory, "players.txt");
- BufferedReader playerReader = null;
- Player player = null;
-
- // Return null if the players data file does not yet exist.
- if ( ! playerFile.exists() ) {
- return null;
- }
-
- // Otherwise, loop through each record in the data file
- try {
6/21/2014 Dukes Soccer League: commits@dukessoccerleague.kenai.com: Archive Project Kenai
https://kenai.com/projects/dukessoccerleague/lists/commits/archive/2011-12/message/0 3/23
- playerReader = new BufferedReader(new FileReader(playerFile));
- String record;
-
- // Read every record (one per line)
- while ( (record = playerReader.readLine()) != null ) {
- String[] fields = record.split("\t");
-
- // Extract the name field from the record
- String name = fields[0];
-
- // If this record does not match the SEARCH NAME,
- // then continue searching the data file
- if ( ! search_name.equals(name) ) {
- continue;
- }
-
- // Otherwise, we have a match...
- // Extract the rest of the data fields
- String address = fields[1];
- String city = fields[2];
- String province = fields[3];
- String postalCode = fields[4];
-
- // Create the Player object from the data fields
- player = new Player(name, address, city, province,
postalCode);
-
- // and break from the loop
- break;
-
- } // END while loop
-
- } catch (Exception e) {
- System.err.println(e);
-
- // Clean up IO resources
- } finally {
- if ( playerReader != null ) {
- try { playerReader.close(); } catch (IOException e) {
System.err.println(e); }
- }
- }
-
- return player;
- }
-
- /**
- * This private method stores a single player to the data file.
- */
- private void storePlayer(Player player) {
- String playerFile = dataDirectory + "players.txt";
- PrintWriter playerWriter = null;
-
- try {
- // Open a writer stream and mark it to append the new data
- playerWriter = new PrintWriter(new FileWriter(playerFile, true));
-
6/21/2014 Dukes Soccer League: commits@dukessoccerleague.kenai.com: Archive Project Kenai
https://kenai.com/projects/dukessoccerleague/lists/commits/archive/2011-12/message/0 4/23
- playerWriter.print(player.name);
- playerWriter.print('\t');
- playerWriter.print(player.address);
- playerWriter.print('\t');
- playerWriter.print(player.city);
- playerWriter.print('\t');
- playerWriter.print(player.province);
- playerWriter.print('\t');
- playerWriter.print(player.postalCode);
- playerWriter.println();
-
- } catch (Exception e) {
- System.err.println(e);
-
- // Clean up IO resources
- } finally {
- if ( playerWriter != null ) {
- try { playerWriter.close(); } catch (Exception e) {
System.err.println(e); }
- }
- }
- }
-}
Index: DukesSoccerLeague/src/java/sl314/model/PlayerDAO.java
===================================================================
--- DukesSoccerLeague/src/java/sl314/model/PlayerDAO.java (revision 0)
+++ DukesSoccerLeague/src/java/sl314/model/PlayerDAO.java (revision 9)
@@ -0,0 +1,99 @@
+package sl314.model;
+
+// SQL imports
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.SQLException;
+import javax.sql.DataSource;
+// JNDI imports
+import javax.naming.Context;
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+
+
+/**
+ * This Data Access Object performs database operations on Player objects.
+ */
+class PlayerDAO {
+
+ /**
+ * This constructor creates a Player DAO object.
+ * Keep this package-private, so no other classes
+ * has access to these methods.
+ */
+ PlayerDAO() {
+ }
+
+ /**
+ * This method inserts the Player into the database.
+ */
6/21/2014 Dukes Soccer League: commits@dukessoccerleague.kenai.com: Archive Project Kenai
https://kenai.com/projects/dukessoccerleague/lists/commits/archive/2011-12/message/0 5/23
+ void insert(Player player) {
+
+ // JDBC variables
+ DataSource ds = null;
+ Connection connection = null;
+ PreparedStatement insert_stmt = null;
+
+ try {
+
+ // Retrieve the DataSource from JNDI
+ Context ctx = new InitialContext();
+ if ( ctx == null ) {
+ throw new RuntimeException("JNDI Context could not be found.");
+ }
+ ds = (DataSource)ctx.lookup("java:comp/env/jdbc/leagueDB");
+ if ( ds == null ) {
+ throw new RuntimeException("DataSource could not be found.");
+ }
+
+ // Get a database connection
+ connection = ds.getConnection();
+
+ // Create SQL INSERT statement
+ insert_stmt = connection.prepareStatement(INSERT_STMT);
+
+ // Get the next Player object ID
+ int playerID = ObjectIdDAO.getNextObjectID(ObjectIdDAO.PLAYER,
connection);
+
+ // Add the object ID as the first field to be entered.
+ insert_stmt.setInt(1, playerID);
+ // Add data fields
+ insert_stmt.setString(2, player.name);
+ insert_stmt.setString(3, player.address);
+ insert_stmt.setString(4, player.city);
+ insert_stmt.setString(5, player.province);
+ insert_stmt.setString(6, player.postalCode);
+
+ // Perform the SQL INSERT
+ insert_stmt.executeUpdate();
+
+ // Set the player's object ID
+ player.objectID = playerID;
+
+ // Handle any SQL errors
+ } catch (SQLException se) {
+ throw new RuntimeException("A database error occured. " +
se.getMessage());
+
+ // Handle any JNDI errors
+ } catch (NamingException ne) {
+ throw new RuntimeException("A JNDI error occured. " + ne.getMessage());
+
+ // Clean up JDBC resources
+ } finally {
+ if ( insert_stmt != null ) {
+ try { insert_stmt.close(); } catch (SQLException sex) {}
6/21/2014 Dukes Soccer League: commits@dukessoccerleague.kenai.com: Archive Project Kenai
https://kenai.com/projects/dukessoccerleague/lists/commits/archive/2011-12/message/0 6/23
+ }
+ if ( connection != null ) {
+ try { connection.close(); }
+ catch (Exception e) { e.printStackTrace(System.err); }
+ }
+ }
+ }
+
+ /**
+ * The SQL query for a prepared statement to insert a Player object.
+ */
+ private static final String INSERT_STMT
+ = "INSERT INTO Player (PID, name, address, city, province, postal_code) "
+ + "VALUES (?, ?, ?, ?, ?, ?)";
+}
Index: DukesSoccerLeague/src/java/sl314/model/LeagueService.java
===================================================================
--- DukesSoccerLeague/src/java/sl314/model/LeagueService.java (revision 8)
+++ DukesSoccerLeague/src/java/sl314/model/LeagueService.java (revision 9)
@@ -1,151 +1,52 @@
package sl314.model;

import java.util.List;
-import java.util.LinkedList;
-import java.util.Iterator;
-import java.util.Collections;
-import java.io.FileReader;
-import java.io.BufferedReader;
-import java.io.FileWriter;
-import java.io.PrintWriter;
-import java.io.IOException;

/**
- * This object performs a variety of league services, such as looking
- * up league objects and creating new ones.
+ * This object performs a variety of league services, like retrieving
+ * a league object from the database, or creating a new league object.
*/
public class LeagueService {

- /** The cache of League objects. */
- private static final List LEAGUES_CACHE = new LinkedList();
- private String dataDirectory;
+ /**
+ * The internal Data Access Object used for database CRUD operations.
+ */
+ private LeagueDAO leagueDataAccess;

- public LeagueService(String dataDirectory) {
- this.dataDirectory = dataDirectory;
+ /**
+ * This constructor creates a League Service object.
+ */
+ public LeagueService() {
+ leagueDataAccess = new LeagueDAO();
+ }

6/21/2014 Dukes Soccer League: commits@dukessoccerleague.kenai.com: Archive Project Kenai
https://kenai.com/projects/dukessoccerleague/lists/commits/archive/2011-12/message/0 7/23
- // Make sure that the leagues cache has been initialized
- synchronized ( LEAGUES_CACHE ) {
- if ( LEAGUES_CACHE.isEmpty() ) {
- cacheLeagues();
- }
- }
- }
+ /**
+ * This method returns a complete set of leagues.
+ */
+ public List getAllLeagues() {
+ return leagueDataAccess.retrieveAll();
+ }

- /**
- * This method returns a complete set of leagues.
- */
- public List getAllLeagues() {
- // Return an immutable List; which makes this read-only
- return Collections.unmodifiableList(LEAGUES_CACHE);
- }
+ /**
+ * This method finds the specified League object in the database.
+ */
+ public League getLeague(int year, String season)
+ throws ObjectNotFoundException {

- /**
- * This method finds the specified League object from the
- * complete set of leagues.
- */
- public League getLeague(int year, String season)
- throws ObjectNotFoundException {
+ return leagueDataAccess.retrieve(year, season);
+ }

- // Search in the cache.
- Iterator set = LEAGUES_CACHE.iterator();
- while ( set.hasNext() ) {
- League l = (League) set.next();
- if ( season.equals(l.getSeason()) && (year == l.getYear()) ) {
- return l;
- }
- }
+ /**
+ * This class adds a new League object to the database.
+ */
+ public League createLeague(int year, String season, String title) {

- // Throw an exception if the league was not found.
- throw new ObjectNotFoundException();
- }
+ // Create the league object
+ League league = new League(-1, year, season, title);

- /**
- * This method adds a new League object.
6/21/2014 Dukes Soccer League: commits@dukessoccerleague.kenai.com: Archive Project Kenai
https://kenai.com/projects/dukessoccerleague/lists/commits/archive/2011-12/message/0 8/23
- */
- public League createLeague(int year, String season, String title) {
+ // Perform the DB transaction
+ leagueDataAccess.insert(league);

- // Determine the next league objectID
- int nextID = LEAGUES_CACHE.size() + 1;
-
- // Create new league object
- League league = new League(nextID, year, season, title);
-
- // Store the league object
- storeLeague(league);
-
- // Record the league in the cache for easy retrieval
- LEAGUES_CACHE.add(league);
-
- return league;
- }
-
- /**
- * This method populates the cache of leagues from the data file.
- */
- private void cacheLeagues() {
- String leagueFile = dataDirectory + "leagues.txt";
- BufferedReader leagueReader = null;
-
- try {
- leagueReader = new BufferedReader(new FileReader(leagueFile));
- String record;
-
- // Read every record (one per line)
- while ( (record = leagueReader.readLine()) != null ) {
- String[] fields = record.split("\t");
-
- // Extract the data fields for the record
- int objectID = Integer.parseInt(fields[0]);
- int year = Integer.parseInt(fields[1]);
- String season = fields[2];
- String title = fields[3];
-
- // Create the League object and save it in the cache
- League l = new League(objectID, year, season, title);
- LEAGUES_CACHE.add(l);
-
- } // END while loop
-
- } catch (Exception e) {
- System.err.println(e);
-
- // Clean up IO resources
- } finally {
- if ( leagueReader != null ) {
- try { leagueReader.close(); } catch (IOException e) {
System.err.println(e); }
- }
- }
6/21/2014 Dukes Soccer League: commits@dukessoccerleague.kenai.com: Archive Project Kenai
https://kenai.com/projects/dukessoccerleague/lists/commits/archive/2011-12/message/0 9/23
- } // END of cacheLeagues method
-
- /**
- * This private method stores a single league to the data file.
- */
- private void storeLeague(League league) {
- String leagueFile = dataDirectory + "leagues.txt";
- PrintWriter leagueWriter = null;
-
- try {
- // Open a writer stream and mark it to append the new data
- leagueWriter = new PrintWriter(new FileWriter(leagueFile, true));
-
- leagueWriter.print(league.objectID);
- leagueWriter.print('\t');
- leagueWriter.print(league.year);
- leagueWriter.print('\t');
- leagueWriter.print(league.season);
- leagueWriter.print('\t');
- leagueWriter.print(league.title);
- leagueWriter.println();
-
- } catch (Exception e) {
- System.err.println(e);
-
- // Clean up IO resources
- } finally {
- if ( leagueWriter != null ) {
- try { leagueWriter.close(); } catch (Exception e) {
System.err.println(e); }
- }
- }
- } // END of storeLeague method
-
-} // END of LeagueService class
+ return league;
+ }
+}
Index: DukesSoccerLeague/src/java/sl314/model/RegisterService.java
===================================================================
--- DukesSoccerLeague/src/java/sl314/model/RegisterService.java (revision 8)
+++ DukesSoccerLeague/src/java/sl314/model/RegisterService.java (revision 9)
@@ -1,79 +1,108 @@
package sl314.model;

-import java.io.FileWriter;
-import java.io.PrintWriter;
+// SQL imports
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.SQLException;
+import javax.sql.DataSource;
+// JNDI imports
+import javax.naming.Context;
+import javax.naming.InitialContext;
+import javax.naming.NamingException;

6/21/2014 Dukes Soccer League: commits@dukessoccerleague.kenai.com: Archive Project Kenai
https://kenai.com/projects/dukessoccerleague/lists/commits/archive/2011-12/message/0 10/23
+
/**
* This object performs a variety of league registration services.
* It acts a Facade into the business logic of registering a Player for
* a League.
*/
public class RegisterService {
- private String dataDirectory;

- public RegisterService(String dataDirectory) {
- this.dataDirectory = dataDirectory;
- // do nothing
- }
+ /**
+ * This constructor creates a Registration Service object.
+ */
+ public RegisterService() {
+ }

- /**
- * This method finds the specified league, by delegating to the
- * LeagueService object.
- */
- public League getLeague(int year, String season)
- throws ObjectNotFoundException {
- LeagueService leagueSvc = new LeagueService(dataDirectory);
- return leagueSvc.getLeague(year, season);
- }
+ /**
+ * This method finds the specified League object.
+ */
+ public League getLeague(int year, String season)
+ throws ObjectNotFoundException {

- /**
- * This method return a Player object for the named person, by
- * delegating to the PlayerService object.
- */
- public Player getPlayer(String name) {
- PlayerService playerSvc = new PlayerService(dataDirectory);
- return playerSvc.getPlayer(name);
- }
+ // Delegate to the league service
+ LeagueService leagueSvc = new LeagueService();
+ return leagueSvc.getLeague(year, season);
+ }

- /**
- * This method stores the registration information for the player,
- * based on the league and division information.
- */
- public void register(League league, Player player, String division) {
+ public Player getPlayer(String name) {
+ return new Player(name);
+ }

- // Use the player service to save the player object
6/21/2014 Dukes Soccer League: commits@dukessoccerleague.kenai.com: Archive Project Kenai
https://kenai.com/projects/dukessoccerleague/lists/commits/archive/2011-12/message/0 11/23
- PlayerService playerSvc = new PlayerService(dataDirectory);
- playerSvc.save(player);
+ public void register(League league, Player player, String division) {

- // Record the registration
- insertRegistration(league, player, division);
- }
+ // Store the player object into the database
+ PlayerDAO playerDataAccess = new PlayerDAO();
+ playerDataAccess.insert(player);

- public void insertRegistration(League league, Player player,String
division) {
+ // Record the registration
+ insertRegistration(league, player, division);
+ }

- // Store the registration info to a data file
- String regFile = dataDirectory + "registrations.txt";
- PrintWriter regWriter = null;
- try {
- // Open a writer stream and mark it to append the new data
- regWriter = new PrintWriter(new FileWriter(regFile, true));
+ private void insertRegistration(League league, Player player, String
division) {

- regWriter.print(league.objectID);
- regWriter.print('\t');
- regWriter.print(player.name);
- regWriter.print('\t');
- regWriter.print(division);
- regWriter.println();
+ // JDBC variables
+ DataSource ds = null;
+ Connection connection = null;
+ PreparedStatement stmt = null;

- } catch (Exception e) {
- throw new RuntimeException(e);
+ try {

- // Clean up IO resources
- } finally {
- if ( regWriter != null ) {
- try { regWriter.close(); } catch (Exception e) {
System.err.println(e); }
- }
- }
- } // END of insertRegistration method
+ // Retrieve the DataSource from JNDI
+ Context ctx = new InitialContext();
+ if ( ctx == null ) {
+ throw new RuntimeException("JNDI Context could not be found.");
+ }
+ ds = (DataSource)ctx.lookup("java:comp/env/jdbc/leagueDB");
+ if ( ds == null ) {
+ throw new RuntimeException("DataSource could not be found.");
6/21/2014 Dukes Soccer League: commits@dukessoccerleague.kenai.com: Archive Project Kenai
https://kenai.com/projects/dukessoccerleague/lists/commits/archive/2011-12/message/0 12/23
+ }

-} // END of RegisterService class
+ // Get a database connection
+ connection = ds.getConnection();
+
+ // Record the registration in the database
+ stmt = connection.prepareStatement(INSERT_REGISTRATION_STMT);
+ stmt.setInt(1, league.objectID);
+ stmt.setInt(2, player.objectID);
+ stmt.setString(3, division);
+ stmt.executeUpdate();
+
+ // Handle any SQL errors
+ } catch (SQLException se) {
+ throw new RuntimeException("A database error occured. " +
se.getMessage());
+
+ // Handle any JNDI errors
+ } catch (NamingException ne) {
+ throw new RuntimeException("A JNDI error occured. " + ne.getMessage());
+
+ // Clean up JDBC resources
+ } finally {
+ if ( stmt != null ) {
+ try { stmt.close(); }
+ catch (SQLException se) { se.printStackTrace(System.err); }
+ }
+ if ( connection != null ) {
+ try { connection.close(); }
+ catch (Exception e) { e.printStackTrace(System.err); }
+ }
+ }
+ }
+
+ /**
+ * The SQL prepared statement to insert a Registration record.
+ */
+ private static final String INSERT_REGISTRATION_STMT
+ = "INSERT INTO Registration (LID, PID, division)"
+ + " VALUES (?, ?, ?)";
+}
Index: DukesSoccerLeague/src/java/sl314/model/LeagueDAO.java
===================================================================
--- DukesSoccerLeague/src/java/sl314/model/LeagueDAO.java (revision 0)
+++ DukesSoccerLeague/src/java/sl314/model/LeagueDAO.java (revision 9)
@@ -0,0 +1,289 @@
+package sl314.model;
+
+// SQL imports
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import javax.sql.DataSource;
+// JNDI imports
+import javax.naming.Context;
6/21/2014 Dukes Soccer League: commits@dukessoccerleague.kenai.com: Archive Project Kenai
https://kenai.com/projects/dukessoccerleague/lists/commits/archive/2011-12/message/0 13/23
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+// Utility imports
+import java.util.List;
+import java.util.LinkedList;
+
+
+/**
+ * This Data Access Object performs database operations
+ * on League objects.
+ */
+class LeagueDAO {
+
+ /**
+ * This constructor creates a League DAO object.
+ * Keep this package-private, so no other classes
+ * has access to these methods.
+ */
+ LeagueDAO() {
+ // do nothing
+ }
+
+ /**
+ * This method retrieves a unique League from the database.
+ */
+ League retrieve(int year, String season)
+ throws ObjectNotFoundException {
+
+ // JDBC variables
+ DataSource ds = null;
+ Connection connection = null;
+ PreparedStatement stmt = null;
+ ResultSet results = null;
+ int num_of_rows = 0;
+
+ // Domain variables
+ League league = null;
+
+ try {
+
+ // Retrieve the DataSource from JNDI
+ Context ctx = new InitialContext();
+ if ( ctx == null ) {
+ throw new RuntimeException("JNDI Context could not be found.");
+ }
+ ds = (DataSource)ctx.lookup("java:comp/env/jdbc/leagueDB");
+ if ( ds == null ) {
+ throw new RuntimeException("DataSource could not be found.");
+ }
+
+ // Get a database connection
+ connection = ds.getConnection();
+
+ // Create SQL SELECT statement
+ stmt = connection.prepareStatement(RETRIEVE_STMT);
+
+ // Initialize statement and execute the query
6/21/2014 Dukes Soccer League: commits@dukessoccerleague.kenai.com: Archive Project Kenai
https://kenai.com/projects/dukessoccerleague/lists/commits/archive/2011-12/message/0 14/23
+ stmt.setInt(1, year);
+ stmt.setString(2, season);
+ results = stmt.executeQuery();
+
+ // Iterator over the query results
+ while ( results.next() ) {
+ int objectID = results.getInt("LID");
+
+ // We expect only one row to be returned
+ num_of_rows++;
+ if ( num_of_rows > 1 ) {
+ throw new SQLException("Too many rows were returned.");
+ }
+
+ // Create and fill-in the League object
+ league = new League(objectID,
+ results.getInt("year"),
+ results.getString("season"),
+ results.getString("title"));
+ }
+
+ if ( league != null ) {
+ return league;
+ } else {
+ throw new ObjectNotFoundException();
+ }
+
+ // Handle any SQL errors
+ } catch (SQLException se) {
+ throw new RuntimeException("A database error occured. "
+ + se.getMessage());
+
+ // Handle any JNDI errors
+ } catch (NamingException ne) {
+ throw new RuntimeException("A JNDI error occured. "
+ + ne.getMessage());
+
+ // Clean up JDBC resources
+ } finally {
+ if ( results != null ) {
+ try { results.close(); }
+ catch (SQLException se) { se.printStackTrace(System.err); }
+ }
+ if ( stmt != null ) {
+ try { stmt.close(); }
+ catch (SQLException se) { se.printStackTrace(System.err); }
+ }
+ if ( connection != null ) {
+ try { connection.close(); }
+ catch (Exception e) { e.printStackTrace(System.err); }
+ }
+ } // END of try-catch-finally block
+ } // END of the retrieve method
+
+ /**
+ * The SQL query for a prepared statement to retrieve a League by the
+ * season and year fields.
6/21/2014 Dukes Soccer League: commits@dukessoccerleague.kenai.com: Archive Project Kenai
https://kenai.com/projects/dukessoccerleague/lists/commits/archive/2011-12/message/0 15/23
+ */
+ private static final String RETRIEVE_STMT
+ = "SELECT * FROM League WHERE \"year\"=? AND season=?";
+
+
+ /**
+ * This method retrieves a complete list of leagues from the database.
+ */
+ List retrieveAll() {
+
+ // JDBC variables
+ DataSource ds = null;
+ Connection connection = null;
+ PreparedStatement stmt = null;
+ ResultSet results = null;
+
+ // Domain variables
+ List leagueList = new LinkedList();
+ League league = null;
+
+ try {
+
+ // Retrieve the DataSource from JNDI
+ Context ctx = new InitialContext();
+ if ( ctx == null ) {
+ throw new RuntimeException("JNDI Context could not be found.");
+ }
+ ds = (DataSource)ctx.lookup("java:comp/env/jdbc/leagueDB");
+ if ( ds == null ) {
+ throw new RuntimeException("DataSource could not be found.");
+ }
+
+ // Get a database connection
+ connection = ds.getConnection();
+
+ // Create SQL SELECT statement
+ stmt = connection.prepareStatement(RETRIEVE_ALL_STMT);
+
+ // Execute the query
+ results = stmt.executeQuery();
+
+ // Iterator over the query results
+ while ( results.next() ) {
+ int objectID = results.getInt("LID");
+
+ // Create and fill-in the League object
+ league = new League(objectID,
+ results.getInt("year"),
+ results.getString("season"),
+ results.getString("title"));
+
+ // Store it in the collection
+ leagueList.add(league);
+ }
+
+ // Return the collection
+ return leagueList;
6/21/2014 Dukes Soccer League: commits@dukessoccerleague.kenai.com: Archive Project Kenai
https://kenai.com/projects/dukessoccerleague/lists/commits/archive/2011-12/message/0 16/23
+
+ // Handle any SQL errors
+ } catch (SQLException se) {
+ throw new RuntimeException("A database error occured. "
+ + se.getMessage());
+
+ // Handle any JNDI errors
+ } catch (NamingException ne) {
+ throw new RuntimeException("A JNDI error occured. "
+ + ne.getMessage());
+
+ // Clean up JDBC resources
+ } finally {
+ if ( results != null ) {
+ try { results.close(); }
+ catch (SQLException se) { se.printStackTrace(System.err); }
+ }
+ if ( stmt != null ) {
+ try { stmt.close(); }
+ catch (SQLException se) { se.printStackTrace(System.err); }
+ }
+ if ( connection != null ) {
+ try { connection.close(); }
+ catch (Exception e) { e.printStackTrace(System.err); }
+ }
+ } // END of try-catch-finally block
+ } // END of retrieveAll method
+
+ /**
+ * The SQL query for a prepared statement to retrieve
+ * the complete list of leagues.
+ */
+ private static final String RETRIEVE_ALL_STMT
+ = "SELECT * FROM League";
+
+
+ /**
+ * This method inserts the League into the database.
+ */
+ void insert(League league) {
+
+ // JDBC variables
+ DataSource ds = null;
+ Connection connection = null;
+ PreparedStatement insert_stmt = null;
+
+ try {
+
+ // Retrieve the DataSource from JNDI
+ Context ctx = new InitialContext();
+ if ( ctx == null ) {
+ throw new RuntimeException("JNDI Context could not be found.");
+ }
+ ds = (DataSource)ctx.lookup("java:comp/env/jdbc/leagueDB");
+ if ( ds == null ) {
+ throw new RuntimeException("DataSource could not be found.");
+ }
6/21/2014 Dukes Soccer League: commits@dukessoccerleague.kenai.com: Archive Project Kenai
https://kenai.com/projects/dukessoccerleague/lists/commits/archive/2011-12/message/0 17/23
+
+ // Get a database connection
+ connection = ds.getConnection();
+
+ // Create SQL INSERT statement
+ insert_stmt = connection.prepareStatement(INSERT_STMT);
+
+ // Get the next League object ID
+ int leagueID = ObjectIdDAO.getNextObjectID(ObjectIdDAO.LEAGUE,
connection);
+
+ // Add the object ID as the firs tfield to be entered.
+ insert_stmt.setInt(1, leagueID);
+ // Add data fields
+ insert_stmt.setInt(2, league.year);
+ insert_stmt.setString(3, league.season);
+ insert_stmt.setString(4, league.title);
+
+ // Execute SQL INSERT statement
+ insert_stmt.executeUpdate();
+
+ // Set the league's object ID
+ league.objectID = leagueID;
+
+ // Handle any SQL errors
+ } catch (SQLException se) {
+ throw new RuntimeException("A database error occured. " +
se.getMessage());
+
+ // Handle any JNDI errors
+ } catch (NamingException ne) {
+ throw new RuntimeException("A JNDI error occured. " + ne.getMessage());
+
+ // Clean up JDBC resources
+ } finally {
+ if ( insert_stmt != null ) {
+ try { insert_stmt.close(); }
+ catch (SQLException se) { se.printStackTrace(System.err); }
+ }
+ if ( connection != null ) {
+ try { connection.close(); }
+ catch (Exception e) { e.printStackTrace(System.err); }
+ }
+ }
+ }
+
+ /**
+ * The SQL query for a prepared statement to inser ta League object.
+ */
+ private static final String INSERT_STMT
+ = "INSERT INTO League (LID, \"year\", season, title) "
+ + "VALUES (?, ?, ?, ?)";
+}
Index: DukesSoccerLeague/src/java/sl314/model/ObjectIdDAO.java
===================================================================
--- DukesSoccerLeague/src/java/sl314/model/ObjectIdDAO.java (revision 0)
+++ DukesSoccerLeague/src/java/sl314/model/ObjectIdDAO.java (revision 9)
6/21/2014 Dukes Soccer League: commits@dukessoccerleague.kenai.com: Archive Project Kenai
https://kenai.com/projects/dukessoccerleague/lists/commits/archive/2011-12/message/0 18/23
@@ -0,0 +1,78 @@
+package sl314.model;
+
+// SQL imports
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+
+
+/**
+ * This Data Access utility class provides tools for allocating Object IDs.
+ */
+final class ObjectIdDAO {
+
+ public static final String LEAGUE = "League";
+ public static final String PLAYER = "Player";
+
+ /**
+ * Keeping the constructor private prevents the creation of instances.
+ */
+ private ObjectIdDAO() {
+ }
+
+ /**
+ * This method inserts the League into the database.
+ */
+ public static int getNextObjectID(String objectClassName,
+ Connection connection) {
+
+ // JDBC variables
+ PreparedStatement query_stmt = null;
+ PreparedStatement incr_stmt = null;
+ ResultSet result = null;
+ int id;
+
+ try {
+
+ // Create SQL SELECT statement
+ query_stmt = connection.prepareStatement(NEXT_ID_QUERY);
+ query_stmt.setString(1, objectClassName);
+ result = query_stmt.executeQuery();
+
+ if ( result.next() ) {
+ id = result.getInt("ID_number");
+ incr_stmt = connection.prepareStatement(UPDATE_ID_CMD);
+ incr_stmt.setInt(1, id + 1);
+ incr_stmt.setString(2, objectClassName);
+ incr_stmt.executeUpdate();
+
+ } else {
+ throw new RuntimeException("No ObjectID entry for class type: "+
objectClassName);
+ }
+
+ // Handle any SQL errors
+ } catch (SQLException se) {
6/21/2014 Dukes Soccer League: commits@dukessoccerleague.kenai.com: Archive Project Kenai
https://kenai.com/projects/dukessoccerleague/lists/commits/archive/2011-12/message/0 19/23
+ throw new RuntimeException("A database error occured. " +
se.getMessage());
+
+ // Clean up JDBC resources
+ } finally {
+ if ( result != null ) {
+ try { result.close(); } catch (SQLException se) {}
+ }
+ if ( query_stmt != null ) {
+ try { query_stmt.close(); } catch (SQLException se) {}
+ }
+ if ( incr_stmt != null ) {
+ try { incr_stmt.close(); } catch (SQLException se) {}
+ }
+ }
+
+ return id;
+ }
+
+ private static final String NEXT_ID_QUERY
+ = "SELECT ID_number FROM ObjectIDs WHERE table_name=?";
+ private static final String UPDATE_ID_CMD
+ = "UPDATE ObjectIDs SET ID_number=? WHERE table_name=?";
+}
Index: DukesSoccerLeague/src/java/sl314/model/Player.java
===================================================================
--- DukesSoccerLeague/src/java/sl314/model/Player.java (revision 8)
+++ DukesSoccerLeague/src/java/sl314/model/Player.java (revision 9)
@@ -10,53 +10,55 @@
* @author Harita
*/
public class Player {
-
+ int objectID;
String name = "";
String address = "";
String city = "";
String province = "";
String postalCode = "";

- Player(String name) {
- this(name, "", "", "", "");
- }
- Player(String name, String address, String city,String province, String
postalCode) {
- this.name = name;
- this.address = address;
- this.city = city;
- this.province = province;
- this.postalCode = postalCode;
- }
+ Player(String name) {
+ this(-1, name, "", "", "", "");
+ }

- public String getName() {
- return name;
6/21/2014 Dukes Soccer League: commits@dukessoccerleague.kenai.com: Archive Project Kenai
https://kenai.com/projects/dukessoccerleague/lists/commits/archive/2011-12/message/0 20/23
- }
- public void setName(String value) {
- name = value;
- }
- public String getAddress() {
- return address;
- }
- public void setAddress(String value) {
- address = value;
- }
- public String getCity() {
- return city;
- }
- public void setCity(String value) {
- city = value;
- }
- public String getProvince() {
- return province;
- }
- public void setProvince(String value) {
- province = value;
- }
- public String getPostalCode() {
- return postalCode;
- }
- public void setPostalCode(String value) {
- postalCode = value;
- }
+ Player(int objectID, String name, String address, String city,
+ String province, String postalCode) {
+ this.objectID = objectID;
+ this.name = name;
+ this.address = address;
+ this.city = city;
+ this.province = province;
+ this.postalCode = postalCode;
+ }

+ public String getName() {
+ return name;
+ }
+ public void setName(String value) {
+ name = value;
+ }
+ public String getAddress() {
+ return address;
+ }
+ public void setAddress(String value) {
+ address = value;
+ }
+ public String getCity() {
+ return city;
+ }
+ public void setCity(String value) {
+ city = value;
+ }
+ public String getProvince() {
6/21/2014 Dukes Soccer League: commits@dukessoccerleague.kenai.com: Archive Project Kenai
https://kenai.com/projects/dukessoccerleague/lists/commits/archive/2011-12/message/0 21/23
+ return province;
+ }
+ public void setProvince(String value) {
+ province = value;
+ }
+ public String getPostalCode() {
+ return postalCode;
+ }
+ public void setPostalCode(String value) {
+ postalCode = value;
+ }
}
\ No newline at end of file
Index: DukesSoccerLeague/src/java/sl314/controller/SelectLeagueAction.java
===================================================================
--- DukesSoccerLeague/src/java/sl314/controller/SelectLeagueAction.java
(revision 8)
+++ DukesSoccerLeague/src/java/sl314/controller/SelectLeagueAction.java
(revision 9)
@@ -64,7 +64,7 @@
// Perform business logic
ServletContext context = getServlet().getServletContext();
String dataDirectory =
(String)context.getAttribute("sl314.model.dataDirectory");
- RegisterService registerSvc = new RegisterService(dataDirectory);
+ RegisterService registerSvc = new RegisterService();

// Retrieve the league
// League league = registerSvc.getLeague(year, season);
Index: DukesSoccerLeague/src/java/sl314/controller/SelectDivisionAction.java
===================================================================
--- DukesSoccerLeague/src/java/sl314/controller/SelectDivisionAction.java
(revision 8)
+++ DukesSoccerLeague/src/java/sl314/controller/SelectDivisionAction.java
(revision 9)
@@ -47,7 +47,7 @@

ServletContext context = getServlet().getServletContext();
String dataDirectory =
(String)context.getAttribute("sl314.model.dataDirectory");
- RegisterService registerSvc = new RegisterService(dataDirectory);
+ RegisterService registerSvc = new RegisterService();

HttpSession session = request.getSession();

Index: DukesSoccerLeague/src/java/sl314/controller/EnterPlayerAction.java
===================================================================
--- DukesSoccerLeague/src/java/sl314/controller/EnterPlayerAction.java
(revision 8)
+++ DukesSoccerLeague/src/java/sl314/controller/EnterPlayerAction.java
(revision 9)
@@ -25,7 +25,7 @@
HttpServletResponse response) {
ServletContext context = getServlet().getServletContext();
String dataDirectory =
(String)context.getAttribute("sl314.model.dataDirectory");
- RegisterService registerSvc = new RegisterService(dataDirectory);
6/21/2014 Dukes Soccer League: commits@dukessoccerleague.kenai.com: Archive Project Kenai
https://kenai.com/projects/dukessoccerleague/lists/commits/archive/2011-12/message/0 22/23
+ RegisterService registerSvc = new RegisterService();
HttpSession session=request.getSession();
League league = (League) session.getAttribute("league");
if(session.isNew())
Index: DukesSoccerLeague/src/java/sl314/controller/AddLeagueAction.java
===================================================================
--- DukesSoccerLeague/src/java/sl314/controller/AddLeagueAction.java
(revision 8)
+++ DukesSoccerLeague/src/java/sl314/controller/AddLeagueAction.java
(revision 9)
@@ -64,7 +64,7 @@

ServletContext context = getServlet().getServletContext();
String dataDirectory =
(String)context.getAttribute("sl314.model.dataDirectory");
- LeagueService leagueSvc = new LeagueService(dataDirectory);
+ LeagueService leagueSvc = new LeagueService();
League league = leagueSvc.createLeague(year, season, title);
// Store the new league in the request-scope
request.setAttribute("league", league);
Index: DukesSoccerLeague/src/java/sl314/view/ListLeagueServlet.java
===================================================================
--- DukesSoccerLeague/src/java/sl314/view/ListLeagueServlet.java
(revision 8)
+++ DukesSoccerLeague/src/java/sl314/view/ListLeagueServlet.java
(revision 9)
@@ -46,7 +46,7 @@
out.println("</tr>");
out.println("</table>");
String dataDirectory =
(String)getServletContext().getAttribute("sl314.model.dataDirectory");
- LeagueService leagueSvc = new LeagueService(dataDirectory);
+ LeagueService leagueSvc = new LeagueService();
List leagueList = leagueSvc.getAllLeagues();
// Generate main body
out.println("<p>");
Index: DukesSoccerLeague/web/WEB-INF/web.xml
===================================================================
--- DukesSoccerLeague/web/WEB-INF/web.xml (revision 8)
+++ DukesSoccerLeague/web/WEB-INF/web.xml (revision 9)
@@ -3,11 +3,7 @@
<description>

</description>
- <display-name>SL-314 WebApp Example</display-name>
- <context-param>
- <param-name>data-directory</param-name>
-
<param-value>F:/Projects/DukesSoccerLeague/web/WEB-INF/data/</param-value>
- </context-param>
+ <display-name>Dukes Soccer League</display-name>
<filter>
<filter-name>PerfFilter</filter-name>
<filter-class>sl314.util.PerformanceFilter</filter-class>
@@ -145,4 +141,10 @@
<taglib-location>/WEB-INF/struts-tiles.tld</taglib-location>
</taglib>
6/21/2014 Dukes Soccer League: commits@dukessoccerleague.kenai.com: Archive Project Kenai
https://kenai.com/projects/dukessoccerleague/lists/commits/archive/2011-12/message/0 23/23
</jsp-config>
+ <resource-ref>
+ <res-ref-name>jdbc/leagueDB</res-ref-name>
+ <res-type>javax.sql.DataSource</res-type>
+ <res-auth>Container</res-auth>
+ <res-sharing-scope>Shareable</res-sharing-scope>
+ </resource-ref>
</web-app>
[dukessoccerleague~source-code-repository:9] Database Implemented
Harita 12/27/2011

Вам также может понравиться