daily pastebin goal
54%
SHARE
TWEET

Untitled

a guest Dec 29th, 2016 98 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package com.gmail.hancury.tablemaker.util
  2.  
  3. import java.sql.{Connection, DriverManager}
  4. import com.jcraft.jsch.{JSch, Session}
  5. import org.apache.log4j.Logger
  6.  
  7. class Database(driver: String) {
  8.   Class.forName(driver).newInstance()
  9. }
  10.  
  11. object DBUtil {
  12.  
  13.   val logger = Logger.getLogger(this.getClass)
  14.  
  15.   def sshTunnelling(sshUser: String, sshPassword: String, sshHost: String,
  16.                     dbHost: String, dbPort: Int, localPort: Int): Maybe[Session] = {
  17.     try {
  18.       val jsch = new JSch()
  19.       val session = jsch.getSession(sshUser, sshHost)
  20.       session.setPassword(sshPassword)
  21.       session.setConfig("StrictHostKeyChecking", "no")
  22.       session.connect()
  23.       session.setPortForwardingL(localPort, dbHost, dbPort)
  24.       logger.info("port forwarded = %s:%d -> %s:%d".format(sshHost, localPort, dbHost, dbPort))
  25.       Maybe(session)
  26.     } catch {
  27.       case e: Exception => Failure(e.getMessage, e.getStackTrace)
  28.     }
  29.   }
  30.  
  31.   def getConnection(dbUser: String, dbPassword: String, dbHost: String, dbPort: Int, db: Database): Maybe[Connection] = {
  32.     var conn: Connection = null
  33.     try {
  34.       val url = "jdbc:mysql://%s:%d/bom?serverTimezone=Asia/Seoul".format(dbHost, dbPort)
  35.       logger.info(url)
  36.       conn = DriverManager.getConnection(url, dbUser, dbPassword)
  37.       Success(conn)
  38.     } catch {
  39.       case e: Exception =>
  40.         if (conn != null) conn.close()
  41.         Failure(e.getMessage, e.getStackTrace)
  42.     }
  43.   }
  44.  
  45.   def disconnect(safeDbConn: Maybe[Connection]): Unit = {
  46.     safeDbConn.map(_.close()).write
  47.   }
  48.  
  49.   def disconnect(safeDbConn: Maybe[Connection], sshSession: Maybe[Session]): Unit = {
  50.     safeDbConn.map(_.close()).write
  51.     sshSession.map(_.disconnect()).write
  52.   }
  53. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top