Advertisement
Guest User

Untitled

a guest
Jun 7th, 2017
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5.30 KB | None | 0 0
  1. package hr.fer.zemris.java.p12;
  2.  
  3. import java.beans.PropertyVetoException;
  4. import java.io.IOException;
  5. import java.nio.file.Files;
  6. import java.nio.file.Paths;
  7. import java.sql.Connection;
  8. import java.sql.DatabaseMetaData;
  9. import java.sql.PreparedStatement;
  10. import java.sql.ResultSet;
  11. import java.sql.SQLException;
  12. import java.sql.Statement;
  13. import java.util.ArrayList;
  14. import java.util.List;
  15. import java.util.Properties;
  16. import java.util.Scanner;
  17.  
  18. import javax.servlet.ServletContextEvent;
  19. import javax.servlet.ServletContextListener;
  20. import javax.servlet.annotation.WebListener;
  21.  
  22. import com.mchange.v2.c3p0.ComboPooledDataSource;
  23. import com.mchange.v2.c3p0.DataSources;
  24.  
  25. import hr.fer.zemris.java.p12.model.Band;
  26.  
  27. @WebListener
  28. public class Initialization implements ServletContextListener {
  29.  
  30.     private static final String CONFIG_FILE = "dbsettings.properties";
  31.  
  32.     public static final String CREATE_POLLS = "CREATE TABLE Polls"
  33.             + "(id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY," + "title VARCHAR(150) NOT NULL,"
  34.             + "message CLOB(2048) NOT NULL)";
  35.  
  36.     public static final String CREATE_POLL_OPTIONS = "CREATE TABLE PollOptions"
  37.             + "(id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY," + "optionTitle VARCHAR(100) NOT NULL,"
  38.             + "optionLink VARCHAR(150) NOT NULL," + "pollID BIGINT," + "votesCount BIGINT,"
  39.             + "FOREIGN KEY (pollID) REFERENCES Polls(id))";
  40.  
  41.     @Override
  42.     public void contextInitialized(ServletContextEvent sce) {
  43.  
  44.         String connectionURL;
  45.         try {
  46.             connectionURL = readInit(CONFIG_FILE, sce);
  47.         } catch (IOException e) {
  48.             throw new RuntimeException("The properties file is missing, or some property is missing.");
  49.         }
  50.  
  51.         ComboPooledDataSource cpds = new ComboPooledDataSource();
  52.         try {
  53.             cpds.setDriverClass("org.apache.derby.jdbc.ClientDriver");
  54.         } catch (PropertyVetoException e1) {
  55.             throw new RuntimeException("Pogreška prilikom inicijalizacije poola.", e1);
  56.         }
  57.         cpds.setJdbcUrl(connectionURL);
  58.  
  59.         sce.getServletContext().setAttribute("hr.fer.zemris.dbpool", cpds);
  60.  
  61.         try {
  62.             initializeTables(cpds, sce);
  63.         } catch (SQLException e) {
  64.             throw new RuntimeException("Can't initialize tables! - "+e.getMessage());
  65.         }
  66.     }
  67.  
  68.     @Override
  69.     public void contextDestroyed(ServletContextEvent sce) {
  70.         ComboPooledDataSource cpds = (ComboPooledDataSource) sce.getServletContext()
  71.                 .getAttribute("hr.fer.zemris.dbpool");
  72.         if (cpds != null) {
  73.             try {
  74.                 DataSources.destroy(cpds);
  75.             } catch (SQLException e) {
  76.                 e.printStackTrace();
  77.             }
  78.         }
  79.     }
  80.  
  81.     public String readInit(String fileName, ServletContextEvent sce) throws IOException {
  82.  
  83.         String pathString = sce.getServletContext().getRealPath("/WEB-INF/" + fileName);
  84.  
  85.         Properties p = new Properties();
  86.         p.load(Files.newInputStream(Paths.get(pathString)));
  87.  
  88.         String host = p.getProperty("host");
  89.         String port = p.getProperty("port");
  90.         String name = p.getProperty("name");
  91.         String user = p.getProperty("user");
  92.         String password = p.getProperty("password");
  93.  
  94.         if (host == null || port == null || name == null || user == null || password == null) {
  95.             throw new IOException("Error while getting dbsettings.properties!");
  96.         }
  97.  
  98.         String connectionURL = "jdbc:derby://" + host + ":" + port + "/" + name + ";user=" + user + ";password="
  99.                 + password;
  100.  
  101.         return connectionURL;
  102.     }
  103.  
  104.     private void initializeTables(ComboPooledDataSource cpds, ServletContextEvent sce) throws SQLException {
  105.         Connection con = cpds.getConnection();
  106.         DatabaseMetaData dbmd = con.getMetaData();
  107.         ResultSet res1 = dbmd.getTables(null, null, "POLLS", null);
  108.  
  109.         if (!res1.next()) {
  110.             createTables(con, sce);
  111.         }
  112.  
  113.     }
  114.  
  115.     private void createTables(Connection con, ServletContextEvent sce) throws SQLException {
  116.         PreparedStatement pst = null;
  117.         pst = con.prepareStatement(CREATE_POLLS);
  118.         pst.executeUpdate();
  119.        
  120.         pst = con.prepareStatement(CREATE_POLL_OPTIONS);
  121.         pst.executeUpdate();
  122.        
  123.         pst = con.prepareStatement("insert into Polls (title, message) VALUES (?,?)", Statement.RETURN_GENERATED_KEYS);
  124.         pst.setString(1, "Glasanje za omiljeni bend:");
  125.         pst.setString(2, "Od sljedećih bendova, koji Vam je bend najdraži?");
  126.         pst.executeUpdate();
  127.  
  128.         ResultSet idRes = pst.getGeneratedKeys();
  129.         idRes.next();
  130.         String generatedPollID = idRes.getString(1);
  131.        
  132.         for (Band band : readBands(sce)) {
  133.             pst = con.prepareStatement("insert into PollOptions (optionTitle,optionLink,pollID,votesCount) VALUES (?,?,?,?)");
  134.             pst.setString(1, band.getName());
  135.             pst.setString(2, band.getLink());
  136.             pst.setString(3, generatedPollID);
  137.             pst.setInt(4, 0);
  138.             pst.executeUpdate();
  139.         }
  140.     }
  141.  
  142.     private List<Band> readBands(ServletContextEvent sce) {
  143.         String fileName = sce.getServletContext().getRealPath("/WEB-INF/glasanje-definicija.txt");
  144.  
  145.         try (Scanner sc = new Scanner(Files.newInputStream(Paths.get(fileName)))) {
  146.             List<Band> bands = new ArrayList<>();
  147.  
  148.             while (sc.hasNextLine()) {
  149.                 String line = sc.nextLine();
  150.                 String[] elems = line.split("\t");
  151.                 if (elems.length != 3) {
  152.                     continue;
  153.                 }
  154.  
  155.                 String bandName = elems[1];
  156.                 String link = elems[2];
  157.  
  158.                 bands.add(new Band(bandName, link));
  159.             }
  160.  
  161.             return bands;
  162.         } catch (IOException ex) {
  163.             throw new RuntimeException("Error while reading definition! - Check if the file is located in /WEB-INF/ folder and if the format is good.");
  164.         }
  165.     }
  166. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement