Advertisement
Guest User

Untitled

a guest
May 3rd, 2017
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 20.95 KB | None | 0 0
  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */
  6. package engine;
  7.  
  8. import webserver.OnHandleRequestResult;
  9. import facebooklikershelper.FacebookLikersHelper;
  10. import java.sql.Connection;
  11. import java.sql.DriverManager;
  12. import java.sql.ResultSet;
  13. import java.sql.SQLException;
  14. import java.sql.Statement;
  15. import java.text.SimpleDateFormat;
  16. import java.util.Calendar;
  17. import java.util.concurrent.ConcurrentHashMap;
  18. import java.util.logging.Level;
  19. import java.util.logging.Logger;
  20. import java.util.regex.Matcher;
  21. import java.util.regex.Pattern;
  22. import webserver.WebServer;
  23.  
  24. /**
  25.  *
  26.  * @author Happy
  27.  */
  28. public class CommunicatingWebServer extends WebServer {
  29.  
  30.     private static Object syncPosts = new Object();
  31.     private static Object syncLikers = new Object();
  32.     private static Object syncGroups = new Object();
  33.    
  34.     private static long reparseGroupsInterval = 1 * 24 * 60 * 60 * 1000L;
  35.     private static long deleteLikersInterval = 7 * 24 * 60 * 60 * 1000L;
  36.    
  37.     private static long lastTimeLikersUpdated = 0L;
  38.     private static long updateLikersInterval = 3 * 60 * 60 * 1000L;
  39.     public static ConcurrentHashMap<String, Long> likers = new ConcurrentHashMap<String, Long>();
  40.  
  41.     private synchronized void init(Object[] params, Connection connection, Statement st, ResultSet rs) {
  42.  
  43.         if (params[0].equals(true)) {
  44.             try {
  45.                 dbExecuteUpdate(connection, "UPDATE Posts SET InUse = 0;\n"
  46.                         + "UPDATE Groups SET InUse = 0;");
  47.                
  48.             } catch (SQLException ex) {
  49.                 Logger.getLogger(CommunicatingWebServer.class.getName()).log(Level.SEVERE, null, ex);
  50.             }
  51.  
  52.             params[0] = false;
  53.  
  54.         }
  55.        
  56.         if (likers.isEmpty()){
  57.             try {
  58.                 rs = dbExecuteQuery(connection, "SELECT * FROM Likers ;");
  59.                 while (rs.next()){
  60.                     likers.put(rs.getString("LikerAddFriendUrlPart"), rs.getLong("AddedTime"));
  61.                 }
  62.             } catch (SQLException ex) {
  63.                 Logger.getLogger(CommunicatingWebServer.class.getName()).log(Level.SEVERE, null, ex);
  64.             }
  65.         }
  66.     }
  67.    
  68.     private synchronized void updateLikers(Connection connection, Statement st, ResultSet rs) {
  69.        
  70.         if ((System.currentTimeMillis() - lastTimeLikersUpdated) >= updateLikersInterval) {
  71.            
  72.             /*String[] likersKeySet = likers.keySet().toArray(new String[0]);
  73.            
  74.             for (String liker : likersKeySet) {
  75.             if (likers.keySet().contains(liker) &&
  76.             (likers.get(liker) <= (System.currentTimeMillis() - deleteLikersInterval)))
  77.             likers.remove(liker);
  78.             }*/
  79.            
  80.             try {
  81.                 dbExecuteUpdate(connection, "DELETE FROM Likers WHERE AddedTime <= "
  82.                         + (System.currentTimeMillis() - deleteLikersInterval) + ";");
  83.  
  84.             } catch (SQLException ex) {
  85.                 Logger.getLogger(CommunicatingWebServer.class.getName()).log(Level.SEVERE, null, ex);
  86.             }
  87.            
  88.             likers.clear();
  89.            
  90.             init(new Object[] {false}, connection, st, rs);
  91.            
  92.             lastTimeLikersUpdated = System.currentTimeMillis();
  93.         }
  94.     }
  95.    
  96.     private ResultSet dbExecuteQuery(Connection connection, String sql) throws SQLException{
  97.         connection.setAutoCommit(false);
  98.         Statement st = connection.createStatement();
  99.         ResultSet rs = st.executeQuery(sql);
  100.         connection.commit();
  101.        
  102.         return rs;
  103.     }
  104.    
  105.     private int dbExecuteUpdate(Connection connection, String sql) throws SQLException{
  106.         connection.setAutoCommit(false);
  107.         Statement st = connection.createStatement();
  108.         int rs = st.executeUpdate(sql);
  109.         connection.commit();
  110.        
  111.         return rs;
  112.     }
  113.  
  114.     @Override
  115.     protected OnHandleRequestResult onHandleRequest(String request, Object[] params) {
  116.  
  117.         request = request.replace("null", "");
  118.  
  119.         Connection connection = null;
  120.         Statement st = null;
  121.         ResultSet rs = null;
  122.         Matcher m;
  123.  
  124.         String log = new SimpleDateFormat("[dd.MM.yyyy HH:mm:ss]").format(Calendar.getInstance().getTime())
  125.                 + ": " + request;
  126.  
  127.         try {
  128.             try {
  129.                 connection = DriverManager.getConnection("jdbc:mariadb://localhost:3306/posts_likers?user=root&password=password&allowMultiQueries=true&characterEncoding=UTF-8");
  130.  
  131.             } catch (SQLException ex) {
  132.                 Logger.getLogger(FacebookLikersHelper.class.getName()).log(Level.SEVERE, null, ex);
  133.             }
  134.  
  135.             log += "db connection ok\r\n";
  136.  
  137.             init(params, connection, st, rs);
  138.  
  139.             log += "init ok\r\n";
  140.            
  141.             updateLikers (connection, st, rs);
  142.            
  143.             log += "update likers ok\r\n";
  144.  
  145.             if (request.split("[ \t]")[0].equals("POST")) {
  146.                 if (request.contains("do=take")) {
  147.                     if (request.contains("what=post")) {
  148.                         m = Pattern.compile("(?<=group_post: )[^ \\r\\n\\s$]+").matcher(request);
  149.                         while (m.find()) {
  150.                             synchronized (syncPosts) {
  151.                                 try {
  152.                                     rs = dbExecuteQuery(connection, "SELECT @gr_id := MAX(GroupID) FROM Groups;"
  153.                                             + "INSERT INTO Groups (GroupID, GroupUrl, LastParsedTime, InUse)\n"
  154.                                             + "VALUES (@gr_id + 1, '" + m.group().split("\\|")[0] + "', '"
  155.                                             + System.currentTimeMillis() + "', 1)\n"
  156.                                             + "ON DUPLICATE KEY UPDATE\n"
  157.                                             + "PostsNum = PostsNum + 1, LastParsedTime = '"
  158.                                             + System.currentTimeMillis() + "';");
  159.  
  160.                                     rs = dbExecuteQuery(connection, "SELECT GroupID FROM Groups WHERE GroupUrl = '"
  161.                                             + m.group().split("\\|")[0] + "';");
  162.  
  163.                                     rs.first();
  164.  
  165.                                     int currentGroupID = rs.getInt("GroupID");
  166.  
  167.                                     rs = dbExecuteQuery(connection, "SELECT PostUrl FROM Posts WHERE PostUrl = '"
  168.                                             + m.group().split("\\|")[1] + "';");
  169.  
  170.                                     if (rs.isBeforeFirst()) {
  171.                                         rs.first();
  172.                                         String post = rs.getString("PostUrl");
  173.                                         if ((post != null) && (!post.equals("null")) && (!post.equals("NULL"))) {
  174.                                             dbExecuteUpdate(connection, "UPDATE Groups\n"
  175.                                                     + "SET PostsNum = PostsNum - 1\n"
  176.                                                     + "WHERE GroupID = '" + currentGroupID + "';");
  177.                                             log += "do=take&what=post - DUPLICATE POST!\r\n";
  178.                                             return new OnHandleRequestResult(false, "error");
  179.                                         }
  180.                                     }
  181.  
  182.                                     dbExecuteUpdate(connection, "INSERT INTO Posts (PostUrl, GroupID)\n"
  183.                                             + "VALUES ('" + m.group().split("\\|")[1] + "', '"
  184.                                             + currentGroupID + "');");
  185.  
  186.                                 } catch (SQLException ex) {
  187.                                     Logger.getLogger(FacebookLikersHelper.class.getName()).log(Level.SEVERE, null, ex);
  188.                                     log += "do=take&what=post exception\r\n";
  189.                                     return new OnHandleRequestResult(false, "error");
  190.                                 }
  191.                             }
  192.  
  193.                         }
  194.                        
  195.                         return new OnHandleRequestResult(true, "OK");
  196.                            
  197.                     } else if (request.contains("what=liker")) {
  198.  
  199.                         m = Pattern.compile("(?<=liker: )[^ \\r\\n\\s$]+").matcher(request);
  200.                         while (m.find()) {
  201.  
  202.                             synchronized (syncLikers) {
  203.                                 likers.put(m.group().trim(), System.currentTimeMillis());
  204.  
  205.                                 try {
  206.                                     /*rs = st.executeQuery("SELECT PostID FROM Posts WHERE PostUrl = '"
  207.                                 + m.group().split("\\|")[1] + "';");
  208.                                
  209.                                 int currentPostID = rs.getInt("PostID");*/
  210.  
  211.                                     dbExecuteUpdate(connection, "INSERT INTO Likers (LikerAddFriendUrlPart, AddedTime)\n"
  212.                                             + "VALUES ('" + m.group() + "', '"
  213.                                             + System.currentTimeMillis() + "');");
  214.  
  215.                                 } catch (SQLException ex) {
  216.                                     Logger.getLogger(FacebookLikersHelper.class.getName()).log(Level.SEVERE, null, ex);
  217.                                     log += "do=take&what=liker exception\r\n";
  218.                                     return new OnHandleRequestResult(false, "error");
  219.                                 }
  220.  
  221.                             }
  222.  
  223.                             return new OnHandleRequestResult(true, "OK");
  224.                         }
  225.                     }
  226.                 } else if (request.contains("do=release")) {
  227.                     if (request.contains("what=post")) {
  228.                         m = Pattern.compile("(?<=postid: )[^ \\r\\n\\s$]+").matcher(request);
  229.                         while (m.find()) {
  230.                             synchronized (syncPosts) {
  231.                                 try {
  232.                                     while (dbExecuteUpdate(connection, "UPDATE Posts SET InUse = 0 WHERE PostID = "
  233.                                             + m.group() + ";") == 0){;};
  234.  
  235.                                 } catch (SQLException ex) {
  236.                                     Logger.getLogger(FacebookLikersHelper.class.getName()).log(Level.SEVERE, null, ex);
  237.                                     log += "do=release&what=post exception\r\n";
  238.                                     return new OnHandleRequestResult(false, "error");
  239.                                 }
  240.  
  241.                             }
  242.                         }
  243.  
  244.                         return new OnHandleRequestResult(true, "OK");
  245.                        
  246.                     } else if (request.contains("what=group")) {
  247.                         m = Pattern.compile("(?<=groupid: )[^ \\r\\n\\s$]+").matcher(request);
  248.                         while (m.find()) {
  249.                             synchronized (syncGroups) {
  250.                                 try {
  251.                                     while (dbExecuteUpdate(connection, "UPDATE Groups SET InUse = 0, "
  252.                                             + "LastParsedTime = " + System.currentTimeMillis()
  253.                                             + " WHERE GroupID = "
  254.                                             + m.group() + ";") == 0){;};
  255.  
  256.                                 } catch (SQLException ex) {
  257.                                     Logger.getLogger(FacebookLikersHelper.class.getName()).log(Level.SEVERE, null, ex);
  258.                                     log += "do=release&what=group exception\r\n";
  259.                                     return new OnHandleRequestResult(false, "error");
  260.                                 }
  261.                             }
  262.                         }
  263.  
  264.                         return new OnHandleRequestResult(true, "OK");
  265.                     }
  266.                 }
  267.                 else if (request.contains("do=delete")) {
  268.                     if (request.contains("what=post")) {
  269.                         m = Pattern.compile("(?<=postid: )[^ \\r\\n\\s$]+").matcher(request);
  270.                         while (m.find()) {
  271.                             synchronized (syncPosts) {
  272.                                 try {
  273.                                     dbExecuteUpdate(connection, "DELETE FROM Posts WHERE PostID = "
  274.                                             + m.group() + ";");
  275.                                 } catch (SQLException ex) {
  276.                                     Logger.getLogger(CommunicatingWebServer.class.getName()).log(Level.SEVERE, null, ex);
  277.                                     log += "do=delete&what=post exception\r\n";
  278.                                     return new OnHandleRequestResult(false, "error");
  279.                                 }
  280.                             }
  281.  
  282.                         }
  283.  
  284.                         return new OnHandleRequestResult(true, "OK");
  285.                      }
  286.                     else if (request.contains("what=group")) {
  287.                         m = Pattern.compile("(?<=groupid: )[^ \\r\\n\\s$]+").matcher(request);
  288.                         while (m.find()) {
  289.                             synchronized (syncGroups) {
  290.                                 try {
  291.                                     dbExecuteUpdate(connection, "DELETE FROM Groups WHERE GroupID = "
  292.                                             + m.group() + ";");
  293.                                 } catch (SQLException ex) {
  294.                                     Logger.getLogger(CommunicatingWebServer.class.getName()).log(Level.SEVERE, null, ex);
  295.                                     log += "do=delete&what=group exception\r\n";
  296.                                     return new OnHandleRequestResult(false, "error");
  297.                                 }
  298.                             }
  299.  
  300.                         }
  301.  
  302.                         return new OnHandleRequestResult(true, "OK");
  303.                      }
  304.                 }
  305.             } else if (request.split("[ \t]")[0].equals("GET")) {
  306.                 if (request.contains("do=give")) {
  307.                     String response = "";
  308.                     if (request.contains("what=post")) {
  309.                        
  310.                         try {
  311.  
  312.                             synchronized (syncPosts) {
  313.                                
  314.                                 String post = "";
  315.                                 int postID = 0;
  316.                                 String group = "";
  317.                                 int groupID = 0;
  318.                                
  319.                                 rs = dbExecuteQuery(connection, "SELECT PostID, PostUrl, GroupID FROM Posts WHERE InUse = 0 LIMIT 1;");
  320.                                
  321.                                 if (!rs.isBeforeFirst()) {
  322.                                     log += "do=give&what=post no available posts\r\n";
  323.                                     return new OnHandleRequestResult(false, "error");
  324.                                 }
  325.                                 rs.first();
  326.                                
  327.                                 post = rs.getString("PostUrl");
  328.                                 postID = rs.getInt("PostID");
  329.                                 groupID = rs.getInt("GroupID");
  330.                                
  331.                                 if ((post == null) || post.equals("null") || post.equals("NULL")){
  332.                                     log += "do=give&what=post no available posts\r\n";
  333.                                     return new OnHandleRequestResult(false, "error");  
  334.                                 }
  335.                                
  336.                                 rs = dbExecuteQuery(connection, "SELECT GroupUrl FROM Groups WHERE GroupID = " + groupID + ";");
  337.                                 rs.first();
  338.                                
  339.                                 group = rs.getString("GroupUrl");
  340.                                
  341.                                 response = "post_postid_group: " + post + "|" + postID + "|" + group;
  342.                                 dbExecuteUpdate(connection, "UPDATE Posts SET InUse = 1 WHERE PostID = " + postID + ";");
  343.                            
  344.                             }
  345.                             /* st.execute("START TRANSACTION;\n"
  346.                             + "SELECT @post_id := PostID, PostUrl FROM Posts WHERE InUse = 0 LIMIT 1;\n"
  347.                             + "UPDATE Posts SET InUse = 1 WHERE PostID = @post_id;\n"
  348.                             + "COMMIT;");*/
  349.  
  350.                         } catch (SQLException ex) {
  351.                             Logger.getLogger(FacebookLikersHelper.class.getName()).log(Level.SEVERE, null, ex);
  352.                             log += "do=give&what=post exception\r\n";
  353.                             return new OnHandleRequestResult(false, "error");
  354.                         }
  355.  
  356.                         return new OnHandleRequestResult(true, response);
  357.  
  358.                     } else if (request.contains("what=group")) {
  359.  
  360.                         try {
  361.  
  362.                             synchronized (syncGroups) {
  363.                                
  364.                                 rs = dbExecuteQuery(connection, "SELECT GroupID, GroupUrl, MAX(PostsNum) FROM Groups\n"
  365.                                         + "WHERE GroupID = ANY (SELECT GroupID FROM Groups\n"
  366.                                         + "WHERE InUse = 0 AND LastParsedTime <= " + (System.currentTimeMillis() - reparseGroupsInterval) + ")\n"
  367.                                         + "LIMIT 1;");
  368.                      
  369.                                
  370.                                  if (!rs.isBeforeFirst()) {
  371.                                     log += "do=give&what=group no available groups\r\n";
  372.                                     return new OnHandleRequestResult(false, "error");
  373.                                 }
  374.                                
  375.                                 rs.first();
  376.                                 if ((rs.getString("GroupUrl") == null) || rs.getString("GroupUrl").equals("null")
  377.                                          || rs.getString("GroupUrl").equals("NULL")){
  378.                                     log += "do=give&what=group no available groups\r\n";
  379.                                     return new OnHandleRequestResult(false, "error");
  380.                                 }
  381.                                
  382.                                 response = "group_groupid: " + rs.getString("GroupUrl") + "|" + rs.getInt("GroupID");
  383.                                 dbExecuteUpdate(connection, "UPDATE Groups SET InUse = 1 WHERE GroupID = " + rs.getInt("GroupID") + ";");
  384.                             }
  385.  
  386.                         } catch (SQLException ex) {
  387.                             Logger.getLogger(FacebookLikersHelper.class.getName()).log(Level.SEVERE, null, ex);
  388.                             log += "do=give&what=group exception\r\n";
  389.                             return new OnHandleRequestResult(false, "error");
  390.                         }
  391.  
  392.                         return new OnHandleRequestResult(true, response);
  393.  
  394.                     }
  395.                 }
  396.                
  397.                 else if (request.contains("do=check")) {
  398.                     String response = "";
  399.                    
  400.                     if (request.contains("what=liker")) {
  401.                         m = Pattern.compile("(?<=likerurlpart: )[^ \\r\\n\\s$]+").matcher(request);
  402.                         while (m.find()) {
  403.                             synchronized (syncLikers) {
  404.                                 boolean addedLiker = false;
  405.                                 response += "liker_ifadded: " + m.group() + "|";
  406.                                 for (String liker : likers.keySet()) {
  407.                                     if (liker.equals(m.group().trim())) {
  408.                                         response += "true";
  409.                                         addedLiker = true;
  410.                                         break;
  411.                                     }
  412.                                 }
  413.                                 if (!addedLiker) {
  414.                                     response += "false";
  415.                                 }
  416.  
  417.                                 response += "\r\n";
  418.                             }
  419.                         }
  420.  
  421.                         return new OnHandleRequestResult(true, response);
  422.                     }
  423.                 }
  424.                
  425.             }
  426.  
  427.             return new OnHandleRequestResult(false, "error");
  428.            
  429.         } finally {
  430.             log += "likers count: " + likers.size();
  431.             if (connection != null)
  432.                 try {
  433.                    connection.close();
  434.                 } catch (SQLException ex) {
  435.                     Logger.getLogger(CommunicatingWebServer.class.getName()).log(Level.SEVERE, null, ex);
  436.                 }
  437.             addToLog(log);
  438.         }
  439.     }
  440.  
  441. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement