Advertisement
Guest User

Untitled

a guest
Feb 9th, 2015
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 2.33 KB | None | 0 0
  1. import java.net.{SocketException, UnknownHostException, SocketTimeoutException}
  2. import java.util.concurrent.{TimeUnit, ExecutorService, Executors}
  3.  
  4. import scalaj.http.Http
  5. import java.io._
  6. import java.sql._
  7.  
  8. object Main extends App {
  9.  
  10.   val sites = "E:\\Tools\\scala\\sites.txt"
  11.   val poolSize = 1000
  12.  
  13.  
  14.   val pool: ExecutorService = Executors.newFixedThreadPool(poolSize)
  15.  
  16.   val myDriver = "com.mysql.jdbc.Driver"
  17.   val myUrl = "jdbc:mysql://localhost/mydb"
  18.   var conn: Connection = null
  19.   Class.forName(myDriver)
  20.   conn = DriverManager.getConnection(myUrl, "root", "t,@ysq1")
  21.  
  22.   val now = System.nanoTime
  23.   for (line <- scala.io.Source.fromFile(sites).getLines()) {
  24.     pool.execute(new Fetcher(line, conn))
  25.   }
  26.   pool.shutdown()
  27.   try {
  28.     pool.awaitTermination(Long.MaxValue, TimeUnit.NANOSECONDS)
  29.     val elapsedTime = System.nanoTime - now
  30.     println("Time elapsed: " + elapsedTime / 1000000000.0 + " seconds")
  31.   } catch {
  32.     case e: InterruptedException =>
  33.       println("process interrupted")
  34.   }
  35.   conn.close()
  36. }
  37.  
  38. class Fetcher(url: String, conn: Connection) extends Runnable {
  39.  
  40.   def run() {
  41.     val writer1 = new PrintWriter(new OutputStreamWriter(new FileOutputStream("socket_error.txt", true), "UTF-8"))
  42.     val writer2 = new PrintWriter(new OutputStreamWriter(new FileOutputStream("socket_timeout.txt", true), "UTF-8"))
  43.     val writer3 = new PrintWriter(new OutputStreamWriter(new FileOutputStream("unknown_host.txt", true), "UTF-8"))
  44.     println("Fetching " + url)
  45.  
  46.     try {
  47.       val res = Http("http://" + url).timeout(connTimeoutMs = 10000, readTimeoutMs = 5000).asString
  48.       println(url + " fetched")
  49.       val query = "INSERT INTO test (site, data) values (?, ?)"
  50.       val preparedStmt = conn.prepareStatement(query)
  51.       preparedStmt.setString(1, url)
  52.       preparedStmt.setString(2, res.toString())
  53.       preparedStmt.execute();
  54.     } catch {
  55.       case se: SocketException =>
  56.         println("---!---" + url + " socket error")
  57.         writer1.write(url + '\n')
  58.       case ste: SocketTimeoutException =>
  59.         println("---!---" + url + " socket timeout")
  60.         writer2.write(url + '\n')
  61.       case uhe: UnknownHostException =>
  62.         println("---!---" + url + " unknown host")
  63.         writer3.write(url + '\n')
  64.     }
  65.     writer1.close()
  66.     writer2.close()
  67.     writer3.close()
  68.   }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement