Skip to content

Instantly share code, notes, and snippets.

@ksoumi
Created July 31, 2019 06:41
Show Gist options
  • Save ksoumi/7b1a809e55dc4de42fa748f36dd389b5 to your computer and use it in GitHub Desktop.
Save ksoumi/7b1a809e55dc4de42fa748f36dd389b5 to your computer and use it in GitHub Desktop.
InitializeLeagues.java
package io.pivotal.workshop.web;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import io.pivotal.workshop.model.League;
/**
* Application Lifecycle Listener implementation class InitializeLeagues
*
*/
public class InitializeLeagues implements ServletContextListener {
/**
* @see ServletContextListener#contextDestroyed(ServletContextEvent)
*/
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
}
/**
* @see ServletContextListener#contextInitialized(ServletContextEvent)
*/
public void contextInitialized(ServletContextEvent event) {
ServletContext context = event.getServletContext();
List leagueList = new LinkedList();
String leaguesFile = context.getInitParameter("leagues-file");
InputStream is = null;
BufferedReader reader = null;
try {
is = context.getResourceAsStream(leaguesFile);
reader = new BufferedReader(new InputStreamReader(is));
String record;
// Read every record (one per line)
while ( (record = reader.readLine()) != null ) {
String[] fields = record.split("\t");
// Extract the data fields for the record
int year = Integer.parseInt(fields[0]);
String season = fields[1];
String title = fields[2];
// Add the new League item to the list
League item = new League(year, season, title);
leagueList.add(item);
}
context.setAttribute("leagueList", leagueList);
context.log("The league list has been loaded.");
} catch (Exception e) {
context.log("Exception occured while processing the leagues file.", e);
} finally {
if ( is != null ) {
try { is.close(); } catch (Exception e) {}
}
if ( reader != null ) {
try { reader.close(); } catch (Exception e) {}
}
}
} // END of contextInitialized
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment