Guest User

Untitled

a guest
Sep 11th, 2013
211
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 26.91 KB | None | 0 0
  1. package crawler;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.util.ArrayList;
  7. import java.util.Iterator;
  8. import java.util.List;
  9. import java.util.Scanner;
  10. import java.util.logging.Level;
  11. import java.util.logging.Logger;
  12. import crawler.BasicDAO;
  13.  
  14. /*
  15.  * To change this template, choose Tools | Templates
  16.  * and open the template in the editor.
  17.  */
  18.  
  19. /**
  20.  *
  21.  * @author syncsys
  22.  */
  23. public class Main {
  24.     public static volatile long processedLinksCount = 0;
  25.     public static volatile long nonUniqueEmailsCount = 0;
  26.     public static volatile long UniqueEmailsCount = 0;
  27.     private static Integer requiredThreadCount;
  28.     private static Integer intervalToShowUpdate; // in minuts
  29.     private static boolean resumeWithSavedLinksBoolean = false;
  30.     // run crawler once with given url
  31.     // run threads
  32.    
  33.     public static void main(String [] args){
  34.        
  35.        String initialUrl = null;
  36.        BasicDAO dao =  new BasicDAO();
  37.        if(!dao.connectionAvailable()){
  38.            return;
  39.        }
  40.        
  41.        Scanner scanner = new Scanner(System.in);
  42.        System.out.println("Are you running this application first time? (y/n) ");
  43.        String firstTime = scanner.nextLine();
  44.        if (firstTime.toLowerCase().equals("y")){
  45.            if(!dao.createTables()){
  46.                System.out.println("This is not your first time. The database already exists.");
  47.                System.out.println("Hit ctrl + c and next time choose type n instead of y");
  48.            }
  49.        }
  50.        System.out.println("Would you like to resume processing saved links (y) or start with a new one (n) : (y/n): ");
  51.        String resumeWithSavedLinks = scanner.nextLine();
  52.        if(resumeWithSavedLinks.toLowerCase().equals("y")){
  53.            resumeWithSavedLinksBoolean = true;
  54.        }else{
  55.            System.out.println("Type url to crawl (e.g http://yahoo.com) : ");
  56.            initialUrl = scanner.nextLine();
  57.        }
  58.        
  59.        System.out.println("Type number of Threads to use : ");
  60.        requiredThreadCount = Integer.parseInt(scanner.nextLine()) ;
  61.        System.out.println("Type time interval for which you want stats to be updated and shown to you (minuts) : ");
  62.        intervalToShowUpdate = Integer.parseInt(scanner.nextLine()) ;
  63.        scanner.close();        
  64.                
  65.        
  66.    
  67.         List<Thread> threadList = new ArrayList<Thread>();
  68.         int runningThreadCount = 0;
  69.        
  70.        
  71.         while(true){
  72.            
  73.             runningThreadCount = threadList.size();
  74.        
  75.             if(runningThreadCount < requiredThreadCount){
  76.                 int difference = requiredThreadCount - runningThreadCount;
  77.                
  78.                 for (int i = 0; i < difference; i++) {
  79.                    
  80.                
  81.                     try {
  82.                          
  83. //                        if(resumeWithSavedLinksBoolean){
  84.                          
  85.                              Thread thread = new Thread(new Crawler("https://www.google.com.pk/?gws_rd=cr&ei=-q8vUqqNDIny4QTLlYCwAQ#q=pakistan"/*new BasicDAO().getNonProcessedLink()*/));
  86.                              System.out.println("resume with saved link true");
  87. //                        }else{
  88. //                             thread = new Thread(new Crawler(initialUrl));
  89. //                             resumeWithSavedLinksBoolean = true;    
  90. //                             System.out.println("resume with saved links false");
  91. //                        }
  92.  
  93.                         thread.start();
  94.                        
  95.                         System.out.println("thread stared");
  96.                         threadList.add(thread);
  97.                         System.out.println("thread added to arraylist");
  98.                         Thread.sleep(20000);
  99.                     } catch (Exception ex) {
  100.                         new Logging().logError(ex.toString());
  101.                     }
  102.                    
  103.                }    
  104.                
  105.             }
  106.            
  107.             if (threadList.size() > 0){
  108.                 Iterator it = threadList.iterator();
  109.                 while (it.hasNext()){
  110.                     Thread t = (Thread)it.next();
  111.                     if(t.isAlive()){
  112.                         System.out.println("thread alive");
  113.                        
  114.                     }else{
  115.                         System.out.println("Thread state : "+t.getState());
  116.                         System.out.println("thread dead");
  117. //                        t.start();
  118. //                        System.out.println("thread restarted");
  119. //                        System.out.println("Thread state : "+t.getState());
  120.                     }
  121.                 }
  122.                
  123.             }
  124.            
  125.             try {
  126.                 Thread.sleep(intervalToShowUpdate*60*1000);
  127.             } catch (InterruptedException ex) {
  128.                 new Logging().logError(ex.toString());
  129.             }
  130.            
  131.             System.out.println("=====================================================");
  132.             System.out.println("---Pages--------------------");
  133.             System.out.println("Fetched links so far: \t \t " + getLinksCountFromDB());
  134.             System.out.println("Processed pages so far: \t \t " + processedLinksCount);
  135.             System.out.println("---Emails--------------------");
  136.             System.out.println("Emains fetched so far (non-unique) : \t \t " + nonUniqueEmailsCount);
  137.             System.out.println("Emains fetched so far (unique) : \t \t " + getEmailCountFromDB());
  138.             System.out.println("---Threads--------------------");
  139.             System.out.println("Threads required : \t \t " + requiredThreadCount);
  140.             System.out.println("Threads running currently : \t \t " + runningThreadCount);
  141.             System.out.println("Thread list size (debuggin mode) : \t \t " + threadList.size());
  142.             System.out.println("---Others--------------------");
  143.             System.out.println("Interval to update stats : \t \t " + intervalToShowUpdate+" minuts");
  144.             System.out.println("=====================================================");
  145.         }
  146.        
  147.        
  148.        
  149. //        new Thread(new Runnable(){
  150. //            @Override
  151. //            public void run() {
  152. //                System.out.println("blah");
  153. //            }
  154. //        }).start();
  155.     }
  156.             private static long getEmailCountFromDB(){
  157.                 return 1;
  158.             }
  159.             private static long getLinksCountFromDB(){
  160.                 return 1;
  161.             }
  162. }
  163.  
  164.  
  165.  
  166.  
  167. =========================
  168.  
  169. /*
  170.  * To change this template, choose Tools | Templates
  171.  * and open the template bf the editor.
  172.  */
  173. package crawler;
  174.  
  175. import crawler.Main;
  176. import java.io.BufferedReader;
  177. import java.io.IOException;
  178. import java.io.InputStreamReader;
  179. import java.net.URL;
  180. import java.util.ArrayList;
  181. import java.util.List;
  182. import java.util.logging.Level;
  183. import java.util.logging.Logger;
  184. import java.util.regex.Matcher;
  185. import java.util.regex.Pattern;
  186. import org.jsoup.Jsoup;
  187. import org.jsoup.nodes.Document;
  188. import org.jsoup.nodes.Element;
  189. import org.jsoup.select.Elements;
  190.  
  191.  
  192. /**
  193.  *
  194.  * @author syncsys
  195.  */
  196. public class Crawler implements Runnable {
  197. private static final String patternString = "[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})";
  198. private volatile String url;
  199.  
  200.    
  201.    
  202.     private void crawl(String url) {
  203.        
  204.         //get url from db or use supplied url
  205.         //use boolean "first time" to check if its first time or sufficient urls are in db.
  206.         BufferedReader bf = null;
  207.         try {
  208.             URL target = new URL(url);
  209.             bf = new BufferedReader(
  210.                     new InputStreamReader(target.openStream())
  211.                  );
  212. // System.out.println("debug ========= 1");
  213.             StringBuilder html = new StringBuilder();
  214.             String inputLine;
  215.             while ((inputLine = bf.readLine()) != null) {
  216.                
  217.                 html.append(inputLine);
  218.                
  219.             }
  220.             List emailList = new ArrayList( getEmailList(html.toString()) );
  221.             List linkList = new ArrayList( getLinkList(html.toString(), url) );
  222.             System.out.println("Just worked on --------- "+ url);
  223.             if(new BasicDAO().markLinkAsProcesed(url)){
  224.                 System.out.println("Link marked processed in db "+url);
  225.             }
  226.             Main.processedLinksCount++;
  227.             putEmailsInDB(emailList);
  228.             putLinksInDB(linkList);
  229. // System.out.println("debug ========= 2");      
  230.            
  231.            
  232.                
  233.         } catch (IOException ex) {
  234.             new Logging().logError(ex.toString());
  235.             new BasicDAO().deleteLink(url);
  236.         } catch (Exception ex) {
  237.             new Logging().logError(ex.toString());
  238.             new BasicDAO().deleteLink(url);
  239.         }finally{
  240.             if(bf !=null){
  241.                 try {
  242.                 bf.close();
  243.  // System.out.println("debug ========= 3");
  244.                 } catch (IOException ex) {
  245.                     new Logging().logError(ex.toString());
  246.                 }
  247.            
  248.             }
  249.  //  System.out.println("debug ========= 4");
  250.             String nonProcessedLinkFromDB = null;
  251.  
  252.             nonProcessedLinkFromDB = getNonProcessedLinkFromDB();
  253.             System.out.println("fetched non-processed link from db: ++++++++++++++++ "+ nonProcessedLinkFromDB);
  254.             crawl(nonProcessedLinkFromDB);
  255.            
  256.  //           System.out.println("nonePlinkfromDB is ++++++++++++++++++++++++++" + nonProcessedLinkFromDB);
  257.            
  258.            
  259.   // System.out.println("debug ========= 5");        
  260.            
  261.             nonProcessedLinkFromDB= null;
  262.         }
  263.  ///       String line = "kj asdkfj a;sdlfkj <p>[email protected]</p> asdkfja sdlfkj [email protected] ads";
  264.     }
  265.    
  266.     private  List getLinkList(String html, String url) {
  267.         Document doc = Jsoup.parse(html);
  268.         Elements bodies = doc.select("body");
  269.         List linkList =  new ArrayList();
  270.         for(Element body : bodies ){
  271.             Elements aTags = body.getElementsByTag("a");
  272.             for (Element a: aTags){
  273.                String link =  a.attr("href");
  274.                if ( !(link.startsWith("#"))
  275.                      &&
  276.                     !(link.contains("()"))      ){
  277.                    
  278.                     if( link.startsWith("/") ){
  279.                         link = url+link;
  280.                     }
  281.                  linkList.add(link);
  282.                  //put link in db
  283.                }    
  284.             }
  285.         }
  286.        
  287.         return linkList;
  288.     }
  289.  
  290.     private  List getEmailList(String html) {
  291.         Pattern p = Pattern.compile(patternString);
  292.         Matcher m = p.matcher(html);
  293.         List emailList = new ArrayList();
  294.         while(m.find()){
  295.             emailList.add(m.group());
  296.             Main.nonUniqueEmailsCount++;
  297.         }
  298.        
  299.         return emailList;    
  300.     }
  301.    
  302.    
  303.  
  304.     private  String getNonProcessedLinkFromDB() {
  305.         return ( new BasicDAO().getNonProcessedLink() );
  306.     }
  307.  
  308.     private  void putEmailsInDB(List emailList) {
  309.         new BasicDAO().insertEmail(emailList);
  310.     }
  311.  
  312.     private  void putLinksInDB(List linkList) {
  313.        new BasicDAO().insertLinks(linkList);
  314.     }
  315.  
  316.     @Override
  317.     public void run() {
  318.         if(url != null){
  319.             crawl(url);
  320.         }else{
  321.  //           crawl();
  322.         }
  323.        
  324.     }
  325.     public Crawler(String url){
  326.         this.url = url;
  327.     }
  328.    
  329.     public Crawler(){
  330.         this.url =  null;
  331.     }
  332. }
  333.  
  334.        
  335.  
  336.  
  337.  
  338.  
  339.  
  340.  
  341.  
  342.  
  343.  
  344. =========================
  345.  
  346.  
  347.  
  348. /*
  349.  * To change this template, choose Tools | Templates
  350.  * and open the template in the editor.
  351.  */
  352. package crawler;
  353.  
  354. import java.sql.Connection;
  355. import java.sql.DriverManager;
  356. import java.sql.PreparedStatement;
  357. import java.sql.ResultSet;
  358. import java.sql.SQLException;
  359. import java.util.List;
  360. import java.util.logging.Level;
  361. import java.util.logging.Logger;
  362.  
  363. /**
  364.  *
  365.  * @author syncsys
  366.  */
  367. public class BasicDAO {
  368.     private static final String DBUser = "postgres";
  369.     private static final String DBName = "postgres";
  370.     private static final String DBPass= "abc";
  371.    
  372.     public boolean connectionAvailable(){
  373.         System.out.println("------------------ PostgreSQL "
  374.                 + "JDBC Connection Testing ------------------");
  375.  
  376.         try {
  377.  
  378.                 Class.forName("org.postgresql.Driver");
  379.  
  380.         } catch (ClassNotFoundException e) {
  381.  
  382.                 System.out.println("PostgreSQL JDBC Driver not found in application directory ");
  383.                 e.printStackTrace();
  384.                 return false;
  385.  
  386.         }
  387.  
  388.         System.out.println("PostgreSQL JDBC Driver Registered!");
  389.  
  390.         Connection connection = null;
  391.  
  392.         try {
  393.  
  394.                 connection = DriverManager.getConnection(
  395.                                 "jdbc:postgresql://127.0.0.1:5432/"+DBName, DBUser,
  396.                                 DBPass);
  397.  
  398.         } catch (SQLException e) {
  399.  
  400.                 System.out.println("Connection Failed! Check output console");
  401.                 e.printStackTrace();
  402.                 return false;
  403.  
  404.         }
  405.  
  406.         if (connection != null) {
  407.                 System.out.println("------------------ Database Connectivity : OK ------------------");
  408.                 return true;
  409.         } else {
  410.                 System.out.println("Failed to make connection!");
  411.         }
  412.             return false;
  413.     }
  414.    
  415.     public boolean createTables(){
  416.         try {
  417.  
  418.                 Class.forName("org.postgresql.Driver");
  419.  
  420.         } catch (ClassNotFoundException e) {
  421.  
  422.                 System.out.println("PostgreSQL JDBC Driver not found in application directory ");
  423.                 e.printStackTrace();
  424.                 return false;
  425.  
  426.         }
  427.  
  428.  
  429.         Connection connection = null;
  430.  
  431.         try {
  432.  
  433.                 connection = DriverManager.getConnection(
  434.                                 "jdbc:postgresql://127.0.0.1:5432/"+DBName, DBUser,
  435.                                 DBPass);
  436.  
  437.         } catch (SQLException e) {
  438.  
  439.                 System.out.println("Connection Failed! Check output console");
  440.                 e.printStackTrace();
  441.                 return false;
  442.  
  443.         }
  444.  
  445.         if (connection != null) {
  446.                
  447.             try {
  448.                 PreparedStatement pStmt = connection.prepareStatement(
  449.                     "create table links ("
  450.                       + "id bigserial PRIMARY KEY,"
  451.                       + "href text UNIQUE,"
  452.                       + "processed boolean"
  453.                       + ")"
  454.                     );          
  455.  
  456.            
  457.  
  458.                 pStmt.execute();
  459.                 pStmt.close();
  460.                
  461.                 PreparedStatement pStmt2 = connection.prepareStatement(
  462.                     "create table emails ("
  463.                       + "id bigserial PRIMARY KEY,"
  464.                       + "email VARCHAR(255) UNIQUE"
  465.                       + ")"
  466.                     );          
  467.  
  468.            
  469.  
  470.             pStmt2.execute();
  471.             pStmt2.close();
  472.  
  473.  
  474.             connection.close();
  475.             System.out.println("tables created succesfully -------------------");
  476.             return true;
  477.             } catch (SQLException ex) {
  478.                 new Logging().logError(ex.toString());
  479.             }  
  480.         } else {
  481.                 System.out.println("Failed to make connection!");
  482.         }
  483.         return false;
  484.     }
  485.    
  486.     public void insertEmail(List emailList){
  487.         try {
  488.  
  489.                 Class.forName("org.postgresql.Driver");
  490.  
  491.         } catch (ClassNotFoundException e) {
  492.  
  493.                 System.out.println("PostgreSQL JDBC Driver not found in application directory ");
  494.                 e.printStackTrace();
  495.                
  496.  
  497.         }
  498.  
  499.  
  500.         Connection connection = null;
  501.  
  502.         try {
  503.  
  504.                 connection = DriverManager.getConnection(
  505.                                 "jdbc:postgresql://127.0.0.1:5432/"+DBName, DBUser,
  506.                                 DBPass);
  507.  
  508.         } catch (SQLException e) {
  509.  
  510.                 new Logging().logError(e.toString());
  511.                
  512.  
  513.         }
  514.  
  515.         if (connection != null) {
  516.                
  517.             try {
  518.                 if (emailList.size() > 0){
  519.                     for(Object email : emailList){
  520.                         try{  
  521.                             PreparedStatement pStmt = connection.prepareStatement(
  522.                             "Insert into emails("
  523.  
  524.                                + "email"
  525.                                + ")"
  526.                                + " Values ("
  527.                                + "?"
  528.                                + ")"
  529.                            );
  530.  
  531.  
  532.                             pStmt.setString(1, email.toString());
  533.  
  534.  
  535.                             pStmt.execute();
  536.                             if(pStmt != null){
  537.                                 pStmt.close();
  538.                             }
  539.                            
  540.                         } catch (SQLException ex) {
  541.                             Logger.getLogger(BasicDAO.class.getName()).log(Level.SEVERE, null, ex);
  542.                         }  
  543.                     }
  544.                 }
  545.                
  546.                
  547.                
  548.  
  549.             connection.close();
  550.            
  551.          
  552.             } catch (SQLException ex) {
  553.                 Logger.getLogger(BasicDAO.class.getName()).log(Level.SEVERE, null, ex);
  554.             }  
  555.         } else {
  556.                 new Logging().logError("Failed to make db connection");
  557.         }
  558.     }
  559.    
  560.    
  561.     public void insertLinks(List linkList){
  562.         try {
  563.  
  564.                 Class.forName("org.postgresql.Driver");
  565.  
  566.         } catch (ClassNotFoundException e) {
  567.  
  568.                 new Logging().logError(e.toString());
  569.                
  570.  
  571.         }
  572.  
  573.  
  574.         Connection connection = null;
  575.  
  576.         try {
  577.  
  578.                 connection = DriverManager.getConnection(
  579.                                 "jdbc:postgresql://127.0.0.1:5432/"+DBName, DBUser,
  580.                                 DBPass);
  581.  
  582.         } catch (SQLException e) {
  583.  
  584.                 new Logging().logError(e.toString());
  585.                
  586.  
  587.         }
  588.  
  589.         if (connection != null) {
  590.                
  591.             try {
  592.                 if (linkList.size() > 0){
  593.                     for(Object link : linkList){
  594.                         try{  
  595.                             PreparedStatement pStmt = connection.prepareStatement(
  596.                             "Insert into links("
  597.  
  598.                                + "href,"
  599.                                + "processed"
  600.                                + ")"
  601.                                + " Values ("
  602.                                + "?,?"
  603.                                + ")"
  604.                            );
  605.  
  606.  
  607.                             pStmt.setString(1, link.toString());
  608.                             pStmt.setBoolean(2, false);
  609.  
  610.  
  611.                             pStmt.execute();
  612.                             if(pStmt != null) {pStmt.close();}
  613.                    
  614.                         } catch (SQLException ex) {
  615.                             new Logging().logError(ex.toString());
  616.                         }
  617.                     }
  618.                 }
  619.                
  620.                
  621.                
  622.  
  623.            if (connection != null) {
  624.                connection.close();
  625.            }
  626.            
  627.          
  628.             } catch (SQLException ex) {
  629.                 Logger.getLogger(BasicDAO.class.getName()).log(Level.SEVERE, null, ex);
  630.             } finally{
  631.                             if (connection != null) {
  632.                                 try {
  633.                                     connection.close();
  634.                                 } catch (SQLException ex) {
  635.                                     new Logging().logError(ex.toString());
  636.                                 }
  637.                             }
  638.                         }
  639.         } else {
  640.                 new Logging().logError("Failed to make db connection");
  641.         }
  642.     }
  643.    
  644.    
  645.     public String getNonProcessedLink(){
  646.         try {
  647.  
  648.                 Class.forName("org.postgresql.Driver");
  649.  
  650.         } catch (ClassNotFoundException e) {
  651.  
  652.                  new Logging().logError(e.toString());
  653.                
  654.  
  655.         }
  656.  
  657.  
  658.         Connection connection = null;
  659.  
  660.         try {
  661.  
  662.                 connection = DriverManager.getConnection(
  663.                                 "jdbc:postgresql://127.0.0.1:5432/"+DBName, DBUser,
  664.                                 DBPass);
  665.  
  666.         } catch (SQLException e) {
  667.  
  668.                 new Logging().logError(e.toString());
  669.                
  670.  
  671.         }
  672.  
  673.         if (connection != null) {
  674.                
  675.             try {                
  676.                  PreparedStatement pStmt = connection.prepareStatement(
  677.                "SELECT href from links where processed = false limit 1"
  678.                                    
  679.                 );
  680.                 ResultSet rs = null;
  681.                 rs = pStmt.executeQuery();
  682.                 String href = null;
  683.                 while(rs.next()){
  684.                     href = rs.getString("href");
  685.                 }
  686.                
  687.                 rs.close();
  688.                 pStmt.close();
  689.                 if(connection != null) {
  690.                     connection.close();
  691.                 }
  692. //System.out.println("debug ===============---------------================== d: "+ href);                
  693.                 return href;
  694.            
  695.             } catch (SQLException ex) {
  696.                 new Logging().logError(ex.toString());
  697.             }  
  698.         } else {
  699.                 new Logging().logError("Failed to make db connection");
  700.         }
  701.       return null;
  702.     }
  703.    
  704.    
  705.     public boolean markLinkAsProcesed(String link){
  706.         try {
  707.  
  708.                 Class.forName("org.postgresql.Driver");
  709.  
  710.         } catch (ClassNotFoundException e) {
  711.  
  712.                  new Logging().logError(e.toString());
  713.                
  714.  
  715.         }
  716.  
  717.  
  718.         Connection connection = null;
  719.  
  720.         try {
  721.  
  722.                 connection = DriverManager.getConnection(
  723.                                 "jdbc:postgresql://127.0.0.1:5432/"+DBName, DBUser,
  724.                                 DBPass);
  725.  
  726.         } catch (SQLException e) {
  727.  
  728.                 new Logging().logError(e.toString());
  729.                
  730.  
  731.         }
  732.  
  733.         if (connection != null) {
  734.                
  735.             try {    
  736. //System.out.println("debug +++++++++++++++++++++++++   1");
  737.                  PreparedStatement pStmt = connection.prepareStatement(
  738.                     "update links set processed = ? where href = ?"
  739.                    );
  740.  
  741. //System.out.println("debug +++++++++++++++++++++++++   2");
  742.                     pStmt.setBoolean(1, true);
  743.                     pStmt.setString(2, link);
  744.  
  745. //System.out.println("debug +++++++++++++++++++++++++   3" +pStmt.toString());
  746.                     pStmt.execute();
  747.                    
  748.  //                   System.out.println("link turned true in db ================================== " + link);
  749.                     System.out.println("The query was:         "+pStmt.toString());
  750.                     if(pStmt != null) {pStmt.close();}
  751.                     return true;
  752. // System.out.println("debug +++++++++++++++++++++++++   4");                  
  753.             } catch (SQLException ex) {
  754.  //               System.out.println(ex.toString());
  755.  //               ex.printStackTrace();
  756.                 new Logging().logError(ex.toString());
  757.             } finally{
  758.                 if (connection != null) {
  759.                     try {
  760.                         connection.close();
  761.                     } catch (SQLException ex) {
  762.                         new Logging().logError(ex.toString());
  763.                     }
  764.                 }
  765.             }
  766.         } else {
  767.                 new Logging().logError("Failed to make db connection");
  768.         }
  769.       return false;
  770.     }
  771.    
  772.     public String deleteLink(String link){
  773.         try {
  774.  
  775.                 Class.forName("org.postgresql.Driver");
  776.  
  777.         } catch (ClassNotFoundException e) {
  778.  
  779.                  new Logging().logError(e.toString());
  780.                
  781.  
  782.         }
  783.  
  784.  
  785.         Connection connection = null;
  786.  
  787.         try {
  788.  
  789.                 connection = DriverManager.getConnection(
  790.                                 "jdbc:postgresql://127.0.0.1:5432/"+DBName, DBUser,
  791.                                 DBPass);
  792.  
  793.         } catch (SQLException e) {
  794.  
  795.                 new Logging().logError(e.toString());
  796.                
  797.  
  798.         }
  799.  
  800.         if (connection != null) {
  801.                
  802.             try {    
  803.  
  804.                  PreparedStatement pStmt = connection.prepareStatement(
  805.                     "delete from links where href = ?"
  806.                    );
  807.  
  808.                    
  809.                     pStmt.setString(1, link);
  810.  
  811.                     pStmt.execute();
  812.  
  813.        
  814.                     if(pStmt != null) {pStmt.close();}
  815.  //System.out.println("deleted +++++++++++++++++++++++++   " + link);                  
  816.             } catch (SQLException ex) {
  817. //                System.out.println(ex.toString());
  818.  //               ex.printStackTrace();
  819.                 new Logging().logError(ex.toString());
  820.             } finally{
  821.                 if (connection != null) {
  822.                     try {
  823.                         connection.close();
  824.                     } catch (SQLException ex) {
  825.                         new Logging().logError(ex.toString());
  826.                     }
  827.                 }
  828.             }
  829.         } else {
  830.                 new Logging().logError("Failed to make db connection");
  831.         }
  832.       return null;
  833.     }
  834.      
  835.    
  836.    
  837. }
  838.  
  839.  
  840.  
  841.  
  842.  
  843.  
  844. ==========================
  845.  
  846.  
  847.  
  848.  
  849. /*
  850.  * To change this template, choose Tools | Templates
  851.  * and open the template in the editor.
  852.  */
  853. package crawler;
  854.  
  855. import java.io.BufferedWriter;
  856. import java.io.File;
  857. import java.io.FileWriter;
  858. import java.io.IOException;
  859.  
  860. /**
  861.  *
  862.  * @author syncsys
  863.  */
  864. public class Logging {
  865.     volatile static File errorFile = new File("errors.txt");
  866.     public static void logError (String error){
  867.        
  868.             try {
  869.                     BufferedWriter bw = new BufferedWriter(new FileWriter(errorFile,true));
  870.  
  871.                     //Write out a string to the file
  872.                     bw.write(error+"\r\n");
  873.                     //write a new line to the file so the next time you write
  874.                     //to the file it does it on the next line
  875.                     bw.newLine();
  876.                     //flushes and closes the stream
  877.                     bw.close();
  878.             } catch (IOException e) {
  879.                     // TODO Auto-generated catch block
  880.                     new Logging().logError(e.toString());
  881.             }
  882.        
  883.     }
  884. }
  885.  
  886.  
  887.  
  888.  
  889. ==========================
Advertisement
Add Comment
Please, Sign In to add comment