Advertisement
Guest User

Untitled

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