Advertisement
Guest User

Untitled

a guest
Sep 24th, 2016
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 20.94 KB | None | 0 0
  1. public class DatabaseHandler {
  2.  
  3.  
  4. private static DatabaseHandler instance = null;
  5. /** MySQL port to connect. */
  6. private static final int port = 3306; //Default is port 3306
  7. /** The url of the database we wat to connect. */
  8. private static String url = "j******************" + port +"/";
  9. /** The username to connect to database. */
  10. private static final String dbUser = "*******";
  11. /** The password to connecto to database */
  12. private static final String dbPassword = "**********";
  13. /** The name of the database we want to query */
  14. private static final String dbName = "**********";
  15.  
  16. private static Connection connect = null;
  17. private Statement statement = null;
  18. private PreparedStatement preparedStatement = null;
  19. private ResultSet resultSet = null;
  20.  
  21. /** Constructor load the MySQL Driver */
  22. public DatabaseHandler()
  23. {
  24. try{
  25. // Load the MySQL Driver
  26. Class.forName("com.mysql.jdbc.Driver");
  27. }catch(ClassNotFoundException e)
  28. {
  29. System.out.println("MySQL Driver could not loaded!");
  30. e.printStackTrace();
  31. }
  32. }
  33.  
  34. /**
  35. * Returns a list with the houses coordinates needed from the {@link GroundBuilder#buildMissingGround(World, int)} to spawn the ground.
  36. * @param rowID the ID of the row we want the coordinates
  37. */
  38. public List<MissingGroundCoordinates> getMissingGroundCoordinates(int rowID)
  39. {
  40. List<MissingGroundCoordinates> missingGroundCoordinates = new ArrayList<MissingGroundCoordinates>();
  41.  
  42. try
  43. {
  44. statement = connect.createStatement();
  45. resultSet = statement.executeQuery("SELECT startBuildingPosX, startBuildingPosY, startBuildingPosZ, blocksInX, blocksInZ FROM houses_coordinates WHERE rowID = " + rowID);
  46.  
  47. while (resultSet.next())
  48. {
  49. MissingGroundCoordinates mGroundCoordinates = new MissingGroundCoordinates();
  50.  
  51. mGroundCoordinates.setStartBuildingPosX(resultSet.getInt("startBuildingPosX"));
  52. mGroundCoordinates.setStartBuildingPosY(resultSet.getInt("startBuildingPosY"));
  53. mGroundCoordinates.setStartBuildingPosZ(resultSet.getInt("startBuildingPosZ"));
  54. mGroundCoordinates.setBlocksInX(resultSet.getInt("blocksInX"));
  55. mGroundCoordinates.setBlocksInZ(resultSet.getInt("blocksInZ"));
  56.  
  57. missingGroundCoordinates.add(mGroundCoordinates);
  58.  
  59. //System.out.println(mGroundCoordinates); // DEBUG
  60. }
  61. return missingGroundCoordinates;
  62. }
  63. catch(SQLException e)
  64. {
  65. System.out.println("There is been a problem in DatabaseHandler.getMissingGroundCoordinates.Try block caught an sql exception and the method returns a null valued list.");
  66. return null;
  67. }
  68. finally
  69. {
  70. close();
  71. }
  72. }
  73.  
  74. /**
  75. * Query the database to get maxBlocksInZ value for a row.
  76. * @param rowID id of the row needed the maxBlocksInZ
  77. * @return the maxBlocksInZ for the row it passed as arguement
  78. */
  79. public int getMaxBlocksInZForARow(int rowID)
  80. {
  81. int maxBlocksInZ = 0;
  82. try
  83. {
  84. statement = connect.createStatement();
  85. resultSet = statement.executeQuery("SELECT maxBlocksInZ FROM houses_rows WHERE rowID = " + rowID);
  86.  
  87. while(resultSet.next())
  88. {
  89. maxBlocksInZ = resultSet.getInt("maxBlocksInZ");
  90. }
  91. return maxBlocksInZ;
  92. }
  93. catch(SQLException e)
  94. {
  95. System.out.println("SQL Exception occured. getMaxBlocksInZForARow returns 0");
  96. return 0;
  97. }
  98. finally
  99. {
  100. close();
  101. }
  102.  
  103.  
  104. }
  105.  
  106. /**
  107. * Query the database to fetch the color of the block used to build the under construction house.
  108. * @return the name of the color
  109. */
  110. public String getBlockColor()
  111. {
  112. String color = null;
  113. try
  114. {
  115. statement = connect.createStatement();
  116. resultSet = statement.executeQuery("SELECT blockColor FROM tc_coordinates");
  117.  
  118. while(resultSet.next())
  119. {
  120. color = resultSet.getString("blockColor");
  121. }
  122. //System.out.println(color); // DEBUG
  123. return color;
  124. }
  125. catch(SQLException e)
  126. {
  127. return null;
  128. }
  129. finally
  130. {
  131. close();
  132. }
  133. }
  134.  
  135. /**
  136. * This method is called when a block from our city is clicked. It queries the database searching the ID
  137. * that matches the coordinates of the block it was clicked. Then we use that ID to fetch the tweet data.
  138. * @param x the x coordinate of the block that was clicked
  139. * @param y the y coordinate of the block that was clicked
  140. * @param z the z coordinate of the block that was clicked
  141. * @return a {@link Tweet} instance with its fields setted.
  142. */
  143. public Tweet getTweet(int x,int y, int z)
  144. {
  145. int id = 0;
  146. Tweet tweet = null;
  147.  
  148. try {
  149. preparedStatement = connect.prepareStatement("SELECT ID FROM spawned_blocks WHERE posX LIKE ? AND posY LIKE ? AND posZ LIKE ?");
  150.  
  151. preparedStatement.setInt(1,x);
  152. preparedStatement.setInt(2,y);
  153. preparedStatement.setInt(3,z);
  154. resultSet = preparedStatement.executeQuery();
  155.  
  156. while(resultSet.next())
  157. {
  158. id = resultSet.getInt("ID");
  159. }
  160.  
  161. if(id > 0){
  162. statement = connect.createStatement();
  163. resultSet = statement.executeQuery("SELECT * FROM tweets WHERE ID LIKE " + id);
  164.  
  165. while (resultSet.next())
  166. {
  167. tweet = new Tweet();
  168.  
  169. tweet.setID(resultSet.getInt("ID"));
  170. tweet.setUsername(resultSet.getString("user_name"));
  171. tweet.setTweetText(resultSet.getString("tweet_text"));
  172. tweet.setTweetDate(resultSet.getString("tweet_date"));
  173. }
  174. }
  175. } catch (SQLException e) {
  176. e.printStackTrace();
  177. }finally{
  178. close();
  179. }
  180. return tweet;
  181. }
  182.  
  183. /**
  184. * We fetch the latest ID in the table we define.
  185. * @param tableName the name of the table we need the latest id from
  186. * @return the latest ID from the table we gave as parameter
  187. */
  188. public int getLatestID(String tableName)
  189. {
  190. int latestID = 0;
  191. try
  192. {
  193. String columnName = "";
  194. statement = connect.createStatement();
  195.  
  196. // If the table name is houses_coordinates we need the latest houseID
  197. if (tableName.equals("houses_coordinates"))
  198. {
  199. columnName = "houseID";
  200. }
  201. else{
  202. columnName = "ID";
  203. }
  204. resultSet = statement.executeQuery("SELECT " + columnName + " FROM " + tableName + " ORDER BY " + columnName + " DESC LIMIT 1");
  205.  
  206. while(resultSet.next())
  207. {
  208. latestID = resultSet.getInt(columnName);
  209. }
  210. }
  211. catch (SQLException e)
  212. {
  213. e.printStackTrace();
  214. }
  215. finally
  216. {
  217. close();
  218. }
  219.  
  220. return latestID;
  221. }
  222.  
  223. /**
  224. * Spawns the blocks need to be spawned.
  225. * @param world the world object
  226. * @param latestBuildedBlockIDInWorld the last block's id that was builded in this world
  227. */
  228. public void spawnUnspawnedBlocks(World world, int latestBuildedBlockIDInWorld)
  229. {
  230. try
  231. {
  232. statement = connect.createStatement();
  233.  
  234. resultSet = statement.executeQuery("SELECT * FROM spawned_blocks WHERE ID > " + latestBuildedBlockIDInWorld);
  235.  
  236. while (resultSet.next()) {
  237. // System.out.println("To id einai: " + resultSet.getInt("ID") + ", to posX einai: " +
  238. // resultSet.getInt("posX") +", to posY einai: " + resultSet.getInt("posY") +", to posZ einai: " + resultSet.getInt("posZ"));
  239. world.setBlock(resultSet.getInt("posX"), resultSet.getInt("posY"), resultSet.getInt("posZ"), BlockPicker.getBlockByColor(resultSet.getString("blockColor")));
  240. }
  241.  
  242. }
  243. catch(SQLException e)
  244. {
  245. e.printStackTrace();
  246. }
  247. finally
  248. {
  249. close();
  250. }
  251. }
  252.  
  253. /**
  254. * Spawns the floor,stairs,doors or/and roof where is necessary.
  255. * @param world the world object
  256. * @param currentlyConstructingHouseIDInThisWorld the houses ID that is currently under construction in this world.
  257. */
  258. public void spawnUnspawnedFloorStairsDoorsRoof(World world, int currentlyConstructingHouseIDInThisWorld)
  259. {
  260. try
  261. {
  262. int i = 1;
  263. statement = connect.createStatement();
  264.  
  265. resultSet = statement.executeQuery("SELECT * FROM houses_coordinates WHERE houseID >= " + currentlyConstructingHouseIDInThisWorld);
  266.  
  267. while(resultSet.next())
  268. {
  269. if(resultSet.getBoolean("finishedBuilding"))
  270. {
  271. //Build the roof
  272. RoofBuilder.buildRoof(world, resultSet.getInt("startBuildingPosX"), resultSet.getInt("boundsY"),
  273. resultSet.getInt("startBuildingPosZ"), resultSet.getInt("blocksInX"), resultSet.getInt("blocksInZ"));
  274.  
  275. //Build door and Stairs
  276. DoorAndStairsBuilder.buildDoorAndStairs(world, resultSet.getInt("startBuildingPosX"), resultSet.getInt("startBuildingPosY"),
  277. resultSet.getInt("startBuildingPosZ"), resultSet.getInt("blocksInZ"));
  278.  
  279. //If the houseID is the first result we got we skip building ground because it is already builded
  280. if (resultSet.getInt("houseID") != currentlyConstructingHouseIDInThisWorld)
  281. {
  282.  
  283. GroundBuilder.buildGround(world, resultSet.getInt("startBuildingPosX"), resultSet.getInt("startBuildingPosY"),
  284. resultSet.getInt("startBuildingPosZ"), resultSet.getInt("blocksInX"), resultSet.getInt("blocksInZ"));
  285. }
  286. }
  287. else
  288. {
  289. GroundBuilder.buildGround(world, resultSet.getInt("startBuildingPosX"), resultSet.getInt("startBuildingPosY"),
  290. resultSet.getInt("startBuildingPosZ"), resultSet.getInt("blocksInX"), resultSet.getInt("blocksInZ"));
  291. }
  292. }
  293.  
  294. int rowIDForCurrentlyConstructingHouse = 0;
  295. resultSet = statement.executeQuery("SELECT rowID FROM houses_coordinates WHERE houseID = " + currentlyConstructingHouseIDInThisWorld);
  296. while(resultSet.next())
  297. {
  298. rowIDForCurrentlyConstructingHouse = resultSet.getInt("rowID");
  299. }
  300.  
  301. resultSet = statement.executeQuery("SELECT rowID FROM houses_rows WHERE rowID >= " + rowIDForCurrentlyConstructingHouse);
  302.  
  303. //If result.next() returns false then the resultSet is empty
  304. if (resultSet.next())
  305. {
  306. resultSet.last();
  307. int[] rowIDs = new int[resultSet.getRow()];
  308. resultSet.beforeFirst();
  309.  
  310. int loopCounter = 0;
  311. while(resultSet.next())
  312. {
  313. rowIDs[loopCounter] = resultSet.getInt("rowID");
  314. loopCounter++;
  315. }
  316.  
  317. for (int l = 0; l < rowIDs.length; l++)
  318. {
  319. GroundBuilder.buildMissingGround(world, rowIDs[l]);
  320. }
  321. }
  322.  
  323. }
  324. catch(SQLException e)
  325. {
  326. e.printStackTrace();
  327. }
  328. finally
  329. {
  330. close();
  331. }
  332. }
  333.  
  334.  
  335. /**
  336. * Get the values of the tc_coordinates table's fields and assign to the fields of the data object class {@link Coordinates}
  337. */
  338. public void coordinatesInitialization()
  339. {
  340. try
  341. {
  342. statement = connect.createStatement();
  343. resultSet = statement.executeQuery("SELECT * FROM tc_coordinates");
  344. while(resultSet.next())
  345. {
  346.  
  347. Coordinates.getInstance().buildedHouses = resultSet.getInt("buildedHouses");
  348. Coordinates.getInstance().maxBuildedHousesInXAxis = resultSet.getInt("maxBuildedHousesInXAxis");
  349.  
  350. Coordinates.getInstance().startBuildingPosX = resultSet.getInt("startBuildingPosX");
  351. Coordinates.getInstance().startBuildingPosY = resultSet.getInt("startBuildingPosY");
  352. Coordinates.getInstance().startBuildingPosZ = resultSet.getInt("startBuildingPosZ");
  353.  
  354. Coordinates.getInstance().blocksInX = resultSet.getInt("blocksInX");
  355. Coordinates.getInstance().blocksInY = resultSet.getInt("blocksInY");
  356. Coordinates.getInstance().blocksInZ = resultSet.getInt("blocksInZ");
  357.  
  358. Coordinates.getInstance().boundsX = resultSet.getInt("boundsX");
  359. Coordinates.getInstance().boundsY = resultSet.getInt("boundsY");
  360. Coordinates.getInstance().boundsZ = resultSet.getInt("boundsZ");
  361.  
  362. Coordinates.getInstance().nextPosX = resultSet.getInt("nextPosX");
  363. Coordinates.getInstance().nextPosY = resultSet.getInt("nextPosY");
  364. Coordinates.getInstance().nextPosZ = resultSet.getInt("nextPosZ");
  365.  
  366. Coordinates.getInstance().currentRowID = resultSet.getInt("currentRowID");
  367. Coordinates.getInstance().buildedHousesInCurrentRow = resultSet.getInt("buildedHousesInCurrentRow");
  368. Coordinates.getInstance().maxBlocksInZForCurrentRow = resultSet.getInt("maxBlocksInZForCurrentRow");
  369. }
  370. }
  371. catch(SQLException e)
  372. {
  373. e.printStackTrace();
  374. }
  375. finally
  376. {
  377. close();
  378. }
  379. }
  380.  
  381.  
  382. /**
  383. * Update the table tc_coordinates with values' of the fields from the data object class {@link Coordinates}
  384. */
  385. public void updateCoordinates()
  386. {
  387. Coordinates coords = Coordinates.getInstance();
  388.  
  389. try
  390. {
  391. preparedStatement = connect.prepareStatement("UPDATE tc_coordinates SET "
  392. + "buildedHouses = ?, maxBuildedHousesInXAxis = ?, startBuildingPosX = ?, startBuildingPosY = ?, startBuildingPosZ = ?, "
  393. + "blocksInX = ?, blocksInY = ?, blocksInZ = ?, boundsX = ?, boundsY = ?, boundsZ = ?, "
  394. + "nextPosX = ?, nextPosY = ?, nextPosZ = ?, currentRowID = ?, buildedHousesInCurrentRow =?, maxBlocksInZForCurrentRow = ?");
  395.  
  396. preparedStatement.setInt(1, coords.buildedHouses);
  397. preparedStatement.setInt(2, coords.maxBuildedHousesInXAxis);
  398. preparedStatement.setInt(3, coords.startBuildingPosX);
  399. preparedStatement.setInt(4, coords.startBuildingPosY);
  400. preparedStatement.setInt(5, coords.startBuildingPosZ);
  401. preparedStatement.setInt(6, coords.blocksInX);
  402. preparedStatement.setInt(7, coords.blocksInY);
  403. preparedStatement.setInt(8, coords.blocksInZ);
  404. preparedStatement.setInt(9, coords.boundsX);
  405. preparedStatement.setInt(10, coords.boundsY);
  406. preparedStatement.setInt(11, coords.boundsZ);
  407. preparedStatement.setInt(12, coords.nextPosX);
  408. preparedStatement.setInt(13, coords.nextPosY);
  409. preparedStatement.setInt(14, coords.nextPosZ);
  410. preparedStatement.setInt(15, coords.currentRowID);
  411. preparedStatement.setInt(16, coords.buildedHousesInCurrentRow);
  412. preparedStatement.setInt(17, coords.maxBlocksInZForCurrentRow);
  413.  
  414. preparedStatement.execute();
  415.  
  416. }
  417. catch(SQLException e)
  418. {
  419. e.printStackTrace();
  420. }
  421. finally
  422. {
  423. close();
  424. }
  425. }
  426.  
  427. /**
  428. * Update the column blockColor in the table tc_coordinates with the color of the block the under construction house is building.
  429. * @param color the color of the block we need to update
  430. */
  431. public void updateBlockColor(String color)
  432. {
  433. try
  434. {
  435. statement = connect.createStatement();
  436. statement.executeUpdate("UPDATE tc_coordinates SET blockColor = " + """ + color + """);
  437. }
  438. catch(SQLException e)
  439. {
  440. e.printStackTrace();
  441. }
  442. finally
  443. {
  444. close();
  445. }
  446. }
  447.  
  448. /**
  449. * Called when the current under construction building finishes and sets the finishedBuilding value to 1 (true)
  450. */
  451. public void updateFinishedBuildingValue()
  452. {
  453. try
  454. {
  455. int houseID = 0;
  456. statement = connect.createStatement();
  457. resultSet = statement.executeQuery("SELECT MAX(houseID) FROM houses_coordinates");
  458. while(resultSet.next())
  459. {
  460. houseID = resultSet.getInt("MAX(houseID)");
  461. }
  462.  
  463. statement.executeUpdate("UPDATE houses_coordinates SET finishedBuilding = 1 WHERE houseID = " + houseID);
  464. }
  465. catch(SQLException e)
  466. {
  467. e.printStackTrace();
  468. }
  469. finally
  470. {
  471. close();
  472. }
  473. }
  474.  
  475. /**
  476. * When a row is finished we add in the houses_rows table
  477. * @param buildedHousesInCurrentRow how many houses are builded to the row
  478. * @param maxBlocksInZForCurrentRow what is the maxBlocksInZ for the row
  479. */
  480. public void addNewRowInHousesRowsTable(int buildedHousesInCurrentRow, int maxBlocksInZForCurrentRow)
  481. {
  482. try
  483. {
  484. preparedStatement = connect.prepareStatement("INSERT INTO houses_rows (buildedHousesInRow, maxBlocksInZ) VALUES (?, ?)");
  485.  
  486. preparedStatement.setInt(1, buildedHousesInCurrentRow);
  487. preparedStatement.setInt(2, maxBlocksInZForCurrentRow);
  488.  
  489. preparedStatement.execute();
  490. }
  491. catch (SQLException e)
  492. {
  493. e.printStackTrace();
  494. }
  495. finally
  496. {
  497. close();
  498. }
  499. }
  500.  
  501. /**
  502. * Adds a spawned block's coordinates in the spawned_blocks table
  503. * @param x x coordinate of the block
  504. * @param y y coordinate of the block
  505. * @param z z coordinate of the block
  506. * @param blockColor the block's color
  507. */
  508. public void addSpawnedBlock(int x, int y, int z, String blockColor)
  509. {
  510. try
  511. {
  512. preparedStatement = connect.prepareStatement("INSERT INTO spawned_blocks (posX, posY, posZ, blockColor) VALUES (?, ?, ?, ?)");
  513.  
  514. preparedStatement.setInt(1, x);
  515. preparedStatement.setInt(2, y);
  516. preparedStatement.setInt(3, z);
  517. preparedStatement.setString(4, blockColor);
  518.  
  519. preparedStatement.execute();
  520.  
  521. }
  522. catch (SQLException e)
  523. {
  524. e.printStackTrace();
  525. }
  526. finally
  527. {
  528. close();
  529. }
  530. }
  531.  
  532. /**
  533. * Called when a house finished constructing to add the next's house ,that is going to be builded, coordinates.
  534. */
  535. public void addNextConstructingHouseInHousesCoordinatesTable()
  536. {
  537. Coordinates coords = Coordinates.getInstance();
  538.  
  539. try
  540. {
  541. preparedStatement = connect.prepareStatement("INSERT INTO houses_coordinates (rowID, startBuildingPosX, startBuildingPosY, startBuildingPosZ,"
  542. + " blocksInX, blocksInY, blocksInZ, boundsX, boundsY, boundsZ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
  543.  
  544. preparedStatement.setInt(1, coords.currentRowID);
  545. preparedStatement.setInt(2, coords.startBuildingPosX);
  546. preparedStatement.setInt(3, coords.startBuildingPosY);
  547. preparedStatement.setInt(4, coords.startBuildingPosZ);
  548. preparedStatement.setInt(5, coords.blocksInX);
  549. preparedStatement.setInt(6, coords.blocksInY);
  550. preparedStatement.setInt(7, coords.blocksInZ);
  551. preparedStatement.setInt(8, coords.boundsX);
  552. preparedStatement.setInt(9, coords.boundsY);
  553. preparedStatement.setInt(10, coords.boundsZ);
  554.  
  555. preparedStatement.execute();
  556. }
  557. catch (SQLException e)
  558. {
  559. e.printStackTrace();
  560. }
  561. finally
  562. {
  563. close();
  564. }
  565. }
  566.  
  567. /**
  568. * Closes the resultSet, statement and connect objects.
  569. */
  570. public void close() {
  571. try
  572. {
  573. if (resultSet != null)
  574. {
  575. resultSet.close();
  576. }
  577.  
  578. if (statement != null)
  579. {
  580. statement.close();
  581. }
  582.  
  583. if (connect != null)
  584. {
  585. connect.close();
  586. }
  587. }
  588. catch (Exception e)
  589. {
  590. System.out.println("There is been a problem while closing the MySQL ResultSet, Statement or Connection!");
  591. }
  592. }
  593.  
  594. /**
  595. * Singleton Pattern so it cannot exist more than one instance of this class.
  596. * If there is no instance of this class we create one.
  597. * Every time this method is called we check if the connection is OK and
  598. * if is not we try to initialize it.
  599. */
  600. public static DatabaseHandler getInstance ()
  601. {
  602. if(instance == null)
  603. {
  604. instance = new DatabaseHandler();
  605. }
  606.  
  607. if (connect != null)
  608. {
  609. try {
  610. if(connect.isClosed())
  611. {
  612. connect = DriverManager.getConnection(url + dbName + "?user=" + dbUser + "&password=" + dbPassword);
  613. }
  614. } catch (SQLException e) {
  615.  
  616. //e.printStackTrace();
  617. }
  618. }
  619. else
  620. {
  621. try {
  622. connect = DriverManager.getConnection(url + dbName + "?user=" + dbUser + "&password=" + dbPassword);
  623. } catch (SQLException e) {
  624. e.printStackTrace();
  625. }
  626. }
  627. return instance;
  628. }
  629.  
  630. /**
  631. * This method issues a lightweight query to the database in order determine if the connection with the database is fine.
  632. * @return true if the query where succesfully executed to the database
  633. */
  634. public boolean isConnected()
  635. {
  636. String PING_MARKER = "/* ping */ SELECT 1";
  637.  
  638. /*
  639. * If (connect != null) is true means we had a connection with MySQL before and we need to CHECK if it
  640. * is still OK.
  641. */
  642. if(connect != null)
  643. {
  644. /*
  645. * If an excpetion get caught that means the query did not execute.
  646. * If not, our connection is OK and we return true
  647. */
  648. try
  649. {
  650. statement = connect.createStatement();
  651. resultSet = statement.executeQuery(PING_MARKER);
  652. return true;
  653. }
  654. catch(SQLException e)
  655. {
  656. return false;
  657. }
  658. finally
  659. {
  660. close();
  661. }
  662. }
  663. //If (connect == null) means we never had a connection with the MySQL database
  664. else
  665. {
  666. return false;
  667. }
  668. }
  669. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement