Advertisement
Guest User

Untitled

a guest
Jun 15th, 2016
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.29 KB | None | 0 0
  1. package hr.fer.zemris.java.hw14.listeners;
  2.  
  3. import java.beans.PropertyVetoException;
  4. import java.io.BufferedReader;
  5. import java.io.IOException;
  6. import java.nio.charset.StandardCharsets;
  7. import java.nio.file.Files;
  8. import java.nio.file.Path;
  9. import java.nio.file.Paths;
  10. import java.sql.Connection;
  11. import java.sql.DatabaseMetaData;
  12. import java.sql.PreparedStatement;
  13. import java.sql.ResultSet;
  14. import java.sql.SQLException;
  15. import java.sql.Statement;
  16. import java.util.ArrayList;
  17. import java.util.List;
  18. import java.util.Properties;
  19.  
  20. import javax.servlet.ServletContextEvent;
  21. import javax.servlet.ServletContextListener;
  22. import javax.servlet.annotation.WebListener;
  23.  
  24. import com.mchange.v2.c3p0.ComboPooledDataSource;
  25. import com.mchange.v2.c3p0.DataSources;
  26.  
  27. import hr.fer.zemris.java.hw14.model.Poll;
  28. import hr.fer.zemris.java.hw14.model.PollOption;
  29.  
  30. @WebListener
  31. public class Initialization implements ServletContextListener {
  32.  
  33. private static final String POLLS_TABLE_CREATE = "CREATE TABLE Polls"
  34. + "(id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY," + "title VARCHAR(150) NOT NULL,"
  35. + "message CLOB(2048) NOT NULL)";
  36.  
  37. private static final String POLL_OPTIONS_TABLE_CREATE = "CREATE TABLE PollOptions"
  38. + "(id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY," + "optionTitle VARCHAR(100) NOT NULL,"
  39. + "optionLink VARCHAR(150) NOT NULL," + "pollID BIGINT,votesCount BIGINT,"
  40. + "FOREIGN KEY (pollID) REFERENCES Polls(id))";
  41.  
  42. /**
  43. * {@inheritDoc}
  44. */
  45. @Override
  46. public void contextDestroyed(ServletContextEvent sce) {
  47. ComboPooledDataSource cpds = (ComboPooledDataSource) sce.getServletContext()
  48. .getAttribute("hr.fer.zemris.dbpool");
  49. if (cpds != null) {
  50. try {
  51. DataSources.destroy(cpds);
  52. } catch (SQLException e) {
  53. e.printStackTrace();
  54. }
  55. }
  56. }
  57.  
  58. /**
  59. * {@inheritDoc}
  60. */
  61. @Override
  62. public void contextInitialized(ServletContextEvent sce) {
  63. ComboPooledDataSource cpds = new ComboPooledDataSource();
  64. try {
  65. cpds.setDriverClass("org.apache.derby.jdbc.ClientDriver");
  66. } catch (PropertyVetoException e1) {
  67. throw new RuntimeException("Error while initializing connection-pool", e1);
  68. }
  69.  
  70. String fileName = sce.getServletContext().getRealPath("/WEB-INF/dbsettings.properties");
  71. Path propertiesFile = Paths.get(fileName);
  72. if (Files.notExists(propertiesFile)) {
  73. throw new RuntimeException("File with database properties does not exist.");
  74. }
  75.  
  76. String connectionURL = getConnectionURL(propertiesFile);
  77. cpds.setJdbcUrl(connectionURL);
  78.  
  79. try {
  80. readPollOptions(Paths.get(sce.getServletContext().getRealPath("/WEB-INF/superhero-options.txt")));
  81. } catch (IOException e1) {
  82. // TODO Auto-generated catch block
  83. e1.printStackTrace();
  84. }
  85.  
  86. try {
  87. Connection con = cpds.getConnection();
  88. if (!tableExist(con.getMetaData(), "Polls")) {
  89. createPollsTable(con);
  90. }
  91.  
  92. if (!tableExist(con.getMetaData(), "PollOptions")) {
  93. createPollOptionsTable(con);
  94. }
  95.  
  96. if (tableIsEmpty(con, "Polls")) {
  97. String path = sce.getServletContext().getRealPath("/WEB-INF/polls-definition.txt");
  98. List<Poll> polls = fillPollsTable(con, path);
  99.  
  100. for(Poll p: polls) {
  101. fillPollOptionsTable(con, Paths.get(sce.getServletContext().getRealPath("/WEB-INF/" + p.getLink())), p.getId());
  102. }
  103. }
  104. } catch (Exception e) {
  105. throw new IllegalArgumentException(e.getMessage());
  106. }
  107.  
  108. sce.getServletContext().setAttribute("hr.fer.zemris.dbpool", cpds);
  109. }
  110.  
  111. private String getConnectionURL(Path file) {
  112. Properties properties = new Properties();
  113. StringBuilder sb = new StringBuilder();
  114. try (BufferedReader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
  115. properties.load(reader);
  116.  
  117. sb.append("jdbc:derby://");
  118. sb.append(properties.getProperty("host")).append(":");
  119. sb.append(properties.getProperty("port")).append("/");
  120. sb.append(properties.getProperty("name")).append(";");
  121. sb.append("user=").append(properties.getProperty("user")).append(";");
  122. sb.append("password=").append(properties.getProperty("password"));
  123.  
  124. } catch (IOException e) {
  125. throw new RuntimeException("Could not load database properties.", e);
  126. }
  127. return sb.toString();
  128. }
  129.  
  130.  
  131. private boolean tableExist(DatabaseMetaData metaData, String tableName) throws SQLException {
  132. int numberOfRows = 0;
  133.  
  134. ResultSet rs = metaData.getTables(null, null, tableName.toUpperCase(), null);
  135. while (rs.next()) {
  136. ++numberOfRows;
  137. }
  138.  
  139. return numberOfRows > 0;
  140. }
  141.  
  142. private void createPollOptionsTable(Connection con) throws SQLException {
  143. Statement ps = con.createStatement();
  144. ps.executeUpdate(POLL_OPTIONS_TABLE_CREATE);
  145. }
  146.  
  147. private void createPollsTable(Connection con) throws SQLException {
  148. Statement ps = con.createStatement();
  149. ps.executeUpdate(POLLS_TABLE_CREATE);
  150. }
  151.  
  152. private boolean tableIsEmpty(Connection con, String table) throws SQLException {
  153. int numberOfRows = 0;
  154.  
  155. PreparedStatement ps = con.prepareStatement("SELECT * FROM " + table);
  156. ResultSet rs = ps.executeQuery();
  157. while (rs != null && rs.next()) {
  158. ++numberOfRows;
  159. }
  160.  
  161. return numberOfRows <= 0;
  162. }
  163.  
  164. private List<Poll> fillPollsTable(Connection con, String path)
  165. throws IOException, SQLException {
  166. List<Poll> pollsDef = readPolls(
  167. Paths.get(path));
  168.  
  169. for (Poll pd : pollsDef) {
  170. PreparedStatement ps = con.prepareStatement("INSERT INTO Polls (title, message) values (?,?)",
  171. Statement.RETURN_GENERATED_KEYS);
  172.  
  173. ps.setString(1, pd.getTitle());
  174. ps.setString(2, pd.getMessage());
  175. ps.executeUpdate();
  176.  
  177. ResultSet rset = ps.getGeneratedKeys();
  178. Long pollID = null;
  179. if (rset != null && rset.next()) {
  180. pollID = rset.getLong(1);
  181. }
  182. if (pollID == null) {
  183. System.exit(1);
  184. }
  185. ps.close();
  186. pd.setId(pollID);
  187. }
  188.  
  189. return pollsDef;
  190. }
  191.  
  192. private void fillPollOptionsTable(Connection con, Path path, Long pollID)
  193. throws IOException, SQLException {
  194. List<PollOption> pollOpt = readPollOptions(path);
  195.  
  196. for (PollOption po : pollOpt) {
  197. PreparedStatement ps = con.prepareStatement(
  198. "INSERT INTO PollOptions (optionTitle, optionLink, pollID, votesCount) values (?,?,?,?)");
  199.  
  200. ps.setString(1, po.getOptionTitle());
  201. ps.setString(2, po.getOptionLink());
  202. ps.setLong(3, pollID);
  203. ps.setLong(4, 0);
  204.  
  205. ps.executeUpdate();
  206. ps.close();
  207. }
  208.  
  209. }
  210.  
  211. private List<PollOption> readPollOptions(Path file) throws IOException {
  212. List<String> lines = Files.readAllLines(file, StandardCharsets.UTF_8);
  213.  
  214. List<PollOption> pollOpt = new ArrayList<>();
  215. for (String l : lines) {
  216. String[] data = l.split("\t");
  217. if (data.length != 2) {
  218. throw new RuntimeException("Illigal format of " + file.getFileName() + " file.");
  219. }
  220. PollOption opt = new PollOption(null, data[0], data[1], null, null);
  221. pollOpt.add(opt);
  222. }
  223.  
  224. return pollOpt;
  225. }
  226.  
  227. private List<Poll> readPolls(Path file) throws IOException {
  228. List<String> lines = Files.readAllLines(file, StandardCharsets.UTF_8);
  229.  
  230. List<Poll> polls = new ArrayList<>();
  231. for (String l : lines) {
  232. String[] data = l.split("\t");
  233. if (data.length != 3) {
  234. throw new RuntimeException("Illigal format of " + file.getFileName() + " file.");
  235. }
  236. Poll poll = new Poll(null, data[0], data[1], data[2]);
  237. polls.add(poll);
  238. }
  239.  
  240. return polls;
  241. }
  242.  
  243. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement