当前位置: 首页>>代码示例>>Scala>>正文


Scala ControlThrowable类代码示例

本文整理汇总了Scala中scala.util.control.ControlThrowable的典型用法代码示例。如果您正苦于以下问题:Scala ControlThrowable类的具体用法?Scala ControlThrowable怎么用?Scala ControlThrowable使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了ControlThrowable类的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。

示例1: cx

//设置package包名称以及导入依赖的类
package org.blinkmob

import java.sql.Connection
import javax.sql.DataSource

import resource._

import scala.util.control.ControlThrowable
import scala.util.{Failure, Success, Try}



trait CxProvider{ this:hasDataSource =>

  def cx[A](block: Connection => A): A = managed(ds.getConnection()).acquireAndGet(block(_))

  def tx[A](block: Connection => A): A ={
    cx { c =>
      c.setAutoCommit(false)
      Try({
        val r = block(c)
        c.commit()
        r
      }) match{
        case Success(r) => r
        case Failure(f) => {
          f match{
            case e: ControlThrowable => c.commit(); throw e
            case e => c.rollback(); throw e
          }
        }
      }


    }
  }

  def rbtx[A](block: Connection => A): A ={
    cx { c =>
      c.setAutoCommit(false)
      Try(block(c)) match{
        case Success(r) => c.rollback(); r
        case Failure(f) => c.rollback(); throw f
      }
    }
  }

} 
开发者ID:gnomff,项目名称:scala-tx-provider,代码行数:49,代码来源:CxProvider.scala

示例2: timeout

//设置package包名称以及导入依赖的类
package com.github.bots4s.telegramkit

import akka.stream.Materializer
import akka.stream.scaladsl.Source
import akka.NotUsed
import scala.concurrent.{ExecutionContext, Future}
import scala.util.control.ControlThrowable

import com.github.bots4s.telegramkit.marshalling._
import com.github.bots4s.telegramkit.method.{BotApiRequest, BotApiResponse, GetUpdates, SetWebhook}
import com.github.bots4s.telegramkit.model.Update


trait LongPollingSupport { this: TelegramBot =>
  protected def timeout: Int = 30

  def receiveUpdate(update: Update): Unit

  private[this] def apiUpdateSource(implicit m: BotMarshaller[BotApiRequest[Seq[Update]]], um: BotUnmarshaller[BotApiResponse[Seq[Update]]], mt: Materializer, ec: ExecutionContext): Source[Update, NotUsed] = {
    val iterator = Iterator.iterate(Future.successful((0L, scala.collection.immutable.Seq.empty[Update]))) {
      _ flatMap { case (lastKnownOffset, updates) =>
        val offset = if (updates.isEmpty) lastKnownOffset.toInt else updates.maxBy(_.updateId).updateId
        client.request(GetUpdates(Some(offset + 1), timeout = Some(timeout))).recover {
          case e: ControlThrowable =>
            log.error(e, "error during update polling")
            throw e
          case e: Throwable =>
            if (!e.getClass.getCanonicalName.contains("UnexpectedDisconnectException"))
              log.error(e, "error during update polling")
            scala.collection.immutable.Seq.empty
        }.map { offset -> scala.collection.immutable.Seq(_:_*) }
      }
    }
    Source.fromIterator(() => iterator).mapAsync(1)(_.map(_._2)).mapConcat(identity)
  }

  def startPolling()(implicit
    m1: BotMarshaller[BotApiRequest[Boolean]],
    um1: BotUnmarshaller[BotApiResponse[Boolean]],
    m2: BotMarshaller[BotApiRequest[Seq[Update]]],
    um2: BotUnmarshaller[BotApiResponse[Seq[Update]]]
  ): Unit = {
    client.request(SetWebhook("")).foreach { _ =>
      apiUpdateSource.runForeach(receiveUpdate)
    }
  }
} 
开发者ID:bots4s,项目名称:TelegramKit,代码行数:48,代码来源:LongPollingSupport.scala

示例3: Effect

//设置package包名称以及导入依赖的类
package jspha.tk

import scala.util.control.ControlThrowable


case class Effect[Req, Resp, +R](ffi: Req => Resp,
                                 request: Req,
                                 fail: Throwable => R,
                                 continue: Resp => R)

object Effect {

  def apply[Req, Resp](ffi: Req => Resp)(req: Req): Effect[Req, Resp, Either[Throwable, Resp]] =
    Effect(ffi, req, Left(_), Right(_))

  trait Runner[R] {
    def apply[Req, Resp](eff: Effect[Req, Resp, R]): R
  }

  def perform[R]: Runner[R] = new Runner[R] {

    def apply[Req, Resp](eff: Effect[Req, Resp, R]): R =
      try {
        eff.continue(eff.ffi(eff.request))
      } catch {
        // We don't want to interfere with control, se
        // http://www.scala-lang.org/api/2.10.3/index.html#scala.util.control.ControlThrowable
        case e: ControlThrowable => throw e
        case e: Throwable => eff.fail(e)
      }
  }

} 
开发者ID:tel,项目名称:scala-tk,代码行数:34,代码来源:Effect.scala

示例4: SingleGeoCoordinateParser

//设置package包名称以及导入依赖的类
package dbpedia.dataparsers

import java.util.logging.{Level, Logger}

import dbpedia.config.GeoCoordinateParserConfig
import dbpedia.dataparsers.coordinate.{Latitude, Longitude, SingleGeoCoordinate}
import dbpedia.dataparsers.util.Language
import dbpedia.dataparsers.util.wikiparser.Node

import scala.language.reflectiveCalls
import scala.util.control.ControlThrowable


class SingleGeoCoordinateParser(context : { def language : Language }) extends DataParser
{
    private val logger = Logger.getLogger(classOf[GeoCoordinateParser].getName)
    private val language = context.language.wikiCode
    
    private val lonHemLetterMap = GeoCoordinateParserConfig.longitudeLetterMap.getOrElse(language,GeoCoordinateParserConfig.longitudeLetterMap("en"))
    private val latHemLetterMap = GeoCoordinateParserConfig.latitudeLetterMap.getOrElse(language,GeoCoordinateParserConfig.latitudeLetterMap("en"))
    
	private val lonHemRegex = lonHemLetterMap.keySet.mkString("|")
	private val LongitudeRegex = ("""([0-9]{1,2})/([0-9]{1,2})/([0-9]{0,2}(?:.[0-9]{1,2})?)[/]?[\s]?("""+ lonHemRegex +""")""").r
	
	private val latHemRegex = latHemLetterMap.keySet.mkString("|")
	private val LatitudeRegex = ("""([0-9]{1,2})/([0-9]{1,2})/([0-9]{0,2}(?:.[0-9]{1,2})?)[/]?[\s]?("""+ latHemRegex +""")""").r
	

    override def parse(node : Node) : Option[SingleGeoCoordinate] =
    {
        try
        {
            for( text <- StringParser.parse(node);
                 coordinate <- parseSingleCoordinate(text) )
            {
                return Some(coordinate)
            }
        }
        catch
        {
            case ex : ControlThrowable => throw ex
            case ex : Exception => logger.log(Level.FINE, "Could not extract coordinates", ex)
        }

        None
    }

    
    def parseSingleCoordinate(coordStr : String) : Option[SingleGeoCoordinate] = 
    {
    	coordStr match {
    	  case LatitudeRegex(latDeg, latMin, latSec, latHem) => Some(new Latitude(latDeg.toDouble, latMin.toDouble, ("0"+latSec).toDouble, latHemLetterMap.getOrElse(latHem,"N")))
    	  case LongitudeRegex(lonDeg, lonMin, lonSec, lonHem) => Some(new Longitude(lonDeg.toDouble, lonMin.toDouble, ("0"+lonSec).toDouble, lonHemLetterMap.getOrElse(lonHem,"E")))
    	  case _ => None
    	}
    }
        
} 
开发者ID:FnOio,项目名称:dbpedia-parsing-functions-scala,代码行数:59,代码来源:SingleGeoCoordinateParser.scala

示例5: DB

//设置package包名称以及导入依赖的类
package com.payu.shorturl.persistence

import java.sql.Connection
import javax.inject.{Inject, Singleton}

import akka.actor.ActorSystem
import play.api.db.Database

import scala.concurrent.{ExecutionContext, Future, Promise}
import scala.util.control.ControlThrowable
import scala.util.{Failure, Success}

@Singleton
class DB @Inject()(
                    db: Database,
                    system: ActorSystem
                  ) {

  private implicit val ec: ExecutionContext = system.dispatchers.lookup("contexts.database")

  def withConnection[A](block: Connection => A): Future[A] = {
    Future(db.withConnection(block))(ec)
  }

  def withTransaction[A](block: Connection => A): Future[A] = {
    Future(db.withTransaction(block))(ec)
  }

  def withTransactionF[A](block: Connection => Future[A]): Future[A] = {
    val p = Promise[A]
    val connection = db.getConnection(false)

    block(connection) onComplete {
      case Success(r) =>
        connection.commit()
        connection.close()
        p.success(r)

      case Failure(e: ControlThrowable) =>
        connection.commit()
        connection.close()
        p.failure(e)

      case Failure(e) =>
        connection.rollback()
        connection.close()
        p.failure(e)
    }

    p.future
  }

} 
开发者ID:felipehaack,项目名称:shorturl,代码行数:54,代码来源:DB.scala

示例6: withTx

//设置package包名称以及导入依赖的类
package org.anormcypher

import scala.concurrent.{Future, ExecutionContext}
import scala.util.control.ControlThrowable


  def withTx[A](code: Neo4jTransaction => A)(implicit conn: Neo4jConnection, ec: ExecutionContext): Future[A] =
  for {
    tx <- conn.beginTx
  } yield try {
    val r = code(tx)
    tx.rollback
    r
  } catch {
    case e: ControlThrowable => tx.rollback; throw e
    case e: Throwable =>      tx.rollback; throw e
  }
} 
开发者ID:Kai-Chen,项目名称:anormcypher-wip,代码行数:19,代码来源:Neo4jTestTransaction.scala

示例7: withTx

//设置package包名称以及导入依赖的类
package org.anormcypher

import akka.NotUsed
import akka.stream._, scaladsl._
import scala.concurrent.{Future, ExecutionContext}
import scala.util.control.ControlThrowable


  def withTx[A](code: Neo4jTransaction => A)(implicit conn: Neo4jConnection, ec: ExecutionContext): Future[A] =
    for {
      tx <- conn.beginTx
    } yield try {
      val r = code(tx)
      tx.commit
      r
    } catch {
      case e: ControlThrowable => tx.commit; throw e
      case e: Throwable =>      tx.rollback; throw e
    }
} 
开发者ID:Kai-Chen,项目名称:anormcypher-wip,代码行数:21,代码来源:Neo4jConnection.scala

示例8: ControlSpec

//设置package包名称以及导入依赖的类
package lacasa.run

import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4

@RunWith(classOf[JUnit4])
class ControlSpec {
  import scala.util.control.ControlThrowable
  import lacasa.Box._

  @Test
  def test1(): Unit = {
    println("run.ControlSpec.test1")
    val res = try { 5 } catch {
      case c: ControlThrowable =>
        throw c
      case t: Throwable =>
        println("hello")
    }
    assert(res == 5, "this should not fail")
  }

} 
开发者ID:phaller,项目名称:lacasa,代码行数:25,代码来源:Control.scala

示例9: Message

//设置package包名称以及导入依赖的类
package lacasa.run

import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4

import scala.util.control.ControlThrowable

class Message {
  var arr: Array[Int] = _
}

@RunWith(classOf[JUnit4])
class Stack1Spec {

  import lacasa.Box._

  @Test
  def test1(): Unit = {
    println(s"run.Stack1Spec.test1")
    try {
      mkBox[Message] { packed =>
        implicit val access = packed.access
        packed.box open { msg =>
          msg.arr = Array(1, 2, 3, 4)
        }
      }
    } catch {
      case ct: ControlThrowable =>
        uncheckedCatchControl
        assert(true, "this should not fail!")
    }
  }

} 
开发者ID:phaller,项目名称:lacasa,代码行数:36,代码来源:Stack1.scala


注:本文中的scala.util.control.ControlThrowable类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。