本文整理汇总了Scala中java.util.NoSuchElementException类的典型用法代码示例。如果您正苦于以下问题:Scala NoSuchElementException类的具体用法?Scala NoSuchElementException怎么用?Scala NoSuchElementException使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了NoSuchElementException类的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: circeJsonDecoder
//设置package包名称以及导入依赖的类
package api
import java.util.NoSuchElementException
import javax.security.sasl.AuthenticationException
import io.circe.{Decoder, Encoder}
import org.http4s._
import org.http4s.dsl._
import scalaz._
import scalaz.concurrent.Task
trait BaseApi {
implicit def circeJsonDecoder[A](implicit decoder: Decoder[A]) = org.http4s.circe.jsonOf[A]
implicit def circeJsonEncoder[A](implicit encoder: Encoder[A]) = org.http4s.circe.jsonEncoderOf[A]
implicit def eitherToResponse[A](e: Throwable \/ A)(implicit encoder: Encoder[A]): Task[Response] =
e.fold(l => InternalServerError(l.getMessage), r => Ok(r))
implicit def eitherTaskToResponse[A](e: Task[Throwable \/ A])(implicit encoder: Encoder[A]): Task[Response] =
for {
t <- e
x <- t.fold(l => throwbe2response(l), r => Ok(r))
} yield (x)
val throwbe2response: Throwable => Task[Response] = t => t match {
case e: AuthenticationException => Unauthorized(Challenge("", "", Map()))
case e: IllegalArgumentException => BadRequest (e.getMessage)
case e: NoSuchElementException => NotFound (e.getMessage)
case e: Throwable => InternalServerError(e.getMessage)
}
}
示例2: flatten
//设置package包名称以及导入依赖的类
package michid.script.oak
import java.util.NoSuchElementException
def flatten[T](iterators: Iterator[Iterator[T]]): Iterator[T] = new Iterator[T] {
private var currentIterator: Iterator[T] = emptyIterator
private var hasMore: Option[Boolean] = None
override def hasNext: Boolean = {
// Memoizing the result of hasNext is crucial to performance when recursively
// traversing tree structures.
if (hasMore.isEmpty) {
while (!currentIterator.hasNext && iterators.hasNext) {
currentIterator = iterators.next
}
hasMore = Some(currentIterator.hasNext)
}
hasMore.get
}
override def next: T =
if (hasNext) {
hasMore = None
currentIterator.next
}
else throw new NoSuchElementException
}
}
示例3: isEmpty
//设置package包名称以及导入依赖的类
package samples
package invariant
import java.util.NoSuchElementException
trait List[T] {
def isEmpty: Boolean
def head: T
def tail: List[T]
}
class Cons[T](val head: T, val tail: List[T]) extends List[T] {
def isEmpty = false
}
class Nil[T] extends List[T] {
def isEmpty = true
def head = throw new NoSuchElementException("Nil.head")
def tail = throw new NoSuchElementException("Nil.tail")
}
示例4: Lists
//设置package包名称以及导入依赖的类
package example
import java.util
import java.util.NoSuchElementException
object Lists {
def max(xs: List[Int]): Int = {
if (xs.isEmpty) {
throw new NoSuchElementException()
} else{
auxMax( xs.tail, xs.head)
}
}
def auxMax(xs: List[Int], max: Int): Int = {
if (xs.isEmpty) {
max
}
else {
if( xs.head < max){
auxMax(xs.tail, max)
} else{
auxMax(xs.tail, xs.head)
}
}
}
}
示例5: IndexedMapIteratorTest
//设置package包名称以及导入依赖的类
package org.epl_lang.bytecode.util
import java.util.NoSuchElementException
import org.junit.Assert._
import org.junit.Test
import org.scalatest.junit.JUnitSuite
class IndexedMapIteratorTest extends JUnitSuite {
@Test def validMapTest(): Unit = {
val map = Map(0 -> 12, 1 -> "abc", 2 -> null)
IndexedMapIterator(map).foreach { value => }
}
@Test def invalidMapTest(): Unit = {
val map = Map(0 -> 12, 1 -> "abc", 3 -> null)
try {
IndexedMapIterator(map).foreach { value => }
throw new IllegalStateException("Failed to throw a NoSuchElementException")
} catch {
case e: Throwable => assertEquals(e.getClass, classOf[NoSuchElementException])
}
}
}
示例6: ConfigurationSpec
//设置package包名称以及导入依赖的类
import java.util.NoSuchElementException
import configuration.{LockStepConfiguration, LockStepConfigurationManager, RemoteLocation}
import org.scalatest.{BeforeAndAfter, FlatSpec}
import scala.reflect.io.File
class ConfigurationSpec extends FlatSpec with BeforeAndAfter {
val testConfigFile:String = "TEST_CONFIG_FILE"
val testLocalDir:String = "fooLocalDir"
val testRemoteDir:String = "fooRemoteDir"
val testRemoteAddr:String = "fooRemoteAddr"
before {
File(testConfigFile).createFile(failIfExists = true)
}
after {
File(testConfigFile).delete()
}
"A LockStepConfigurationManager" should "be able to add and retrieve " +
"configuration items in config file" in {
val configMgr = LockStepConfigurationManager(testConfigFile)
configMgr.storeLockStepConfigurationEntry(testLocalDir,
RemoteLocation(testRemoteDir, testRemoteAddr))
val lockStepConfig = configMgr.readLockStepConfigurationFile()
assertResult(lockStepConfig.getRemoteDir(testLocalDir))(testRemoteDir)
assertResult(lockStepConfig.getRemoteServerAddr(testLocalDir))(testRemoteAddr)
}
"A LockStepConfiguration" should "not break on getting invalid configs" in {
val lockStepConfig = LockStepConfiguration()
assertThrows[NoSuchElementException] {
lockStepConfig.getRemoteDir(testLocalDir)
}
assertThrows[NoSuchElementException] {
lockStepConfig.getRemoteServerAddr(testLocalDir)
}
}
}
示例7: MongoHealthCheckRegistrationTest
//设置package包名称以及导入依赖的类
package metrics
import java.util.NoSuchElementException
import com.codahale.metrics.health.HealthCheckRegistry
import libs.Mongo
import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
import play.api.Mode
import play.api.inject.guice.GuiceApplicationBuilder
import scala.util.{Failure, Success, Try}
class MongoHealthCheckRegistrationTest extends FlatSpec with Matchers with BeforeAndAfterAll {
val application = new GuiceApplicationBuilder().in(Mode.Test).build
val injector = application.injector
val registry = injector.instanceOf[HealthCheckRegistry]
override protected def afterAll(): Unit = {
application.stop()
}
behavior of "MongoHealthCheckRegistration"
it should "register MongoHealthCheck" in {
registry.getNames.contains("mongo") shouldEqual true
}
it should "can check mongodb healthy" in {
registry.runHealthCheck("mongo").isHealthy shouldEqual true
}
it should "can check mongodb unhealty" in {
injector.instanceOf[Mongo].connection.client.close()
registry.runHealthCheck("mongo").isHealthy shouldEqual false
}
it should "unregistered health check when shutdown" in {
injector.instanceOf[MongoHealthCheckRegistration].shutdown()
Try {
registry.runHealthCheck("mongo")
} match {
case Failure(exception: NoSuchElementException) => // success
case Success(_) => fail("it should throw no suck element exception")
case _ => fail("it should throw no suck element exception")
}
}
}
示例8: Lists
//设置package包名称以及导入依赖的类
package example
import scala.annotation.tailrec
import java.util.NoSuchElementException
object Lists {
def max(xs: List[Int]): Int = {
@tailrec
def _max(xs: List[Int], max: Int): Int = xs match {
case Nil => max
case y :: ys => _max(ys, if (y > max) y else max)
}
xs match {
case Nil => throw new NoSuchElementException
case y :: ys => _max(ys, y)
}
}
}
示例9: IssueQueriesController
//设置package包名称以及导入依赖的类
package controllers
import java.util.NoSuchElementException
import javax.inject._
import play.api._
import play.api.mvc._
import play.api.Logger
import play.api.libs.json
import spray.json._
import DefaultJsonProtocol._
import domains.issue_query.IssueQueryProtocol._
import domains.issue_query.IssueQueryEntity
import services.issue_query.IssueQueryService
@Singleton
class IssueQueriesController @Inject()(issueQueryService: IssueQueryService) extends Controller {
def index = Action {
val queries = issueQueryService.listAll()
Ok(JsArray(queries.map{ query => query.toJson }.toVector).prettyPrint)
}
def show(id: Long) = Action {
val query = issueQueryService.fetch(id)
query match {
case Some(x) => Ok(x.toJson.prettyPrint)
case None => NotFound("""{"status": "error", "code": "Not Found"}""")
}
}
def create: Action[json.JsValue] = Action(parse.json) { request =>
val requestBody = request.body
Logger.info(s"request = ${requestBody.toString()}")
try {
val jsonAst = JsonParser(requestBody.toString())
val issueQuery = jsonAst.convertTo[IssueQueryEntity]
Logger.info(s"${issueQuery.toJson.compactPrint}")
val id = issueQueryService.insert(issueQuery)
id match {
case Some(i) => {
val iq = issueQueryService.fetch(i).get
Ok(iq.toJson.prettyPrint).as(JSON)
}
case None => InternalServerError(s"Can't save entity: ${issueQuery.toJson.compactPrint}")
}
} catch {
case e: DeserializationException => UnprocessableEntity(s"DeserializationException: ${e.getMessage}")
case e: NoSuchElementException => UnprocessableEntity(s"NoSuchElementException: ${e.getMessage}")
}
}
}
示例10: DrinkController
//设置package包名称以及导入依赖的类
package drinks
import java.util.NoSuchElementException
import javax.inject._
import akka.actor.ActorSystem
import drinks.models.{CreateDrinkDto, Drink, DrinkResponse, DrinkType}
import drinks.repos.DrinksRepository
import play.api.Logger
import play.api.libs.json.Json
import play.api.mvc._
import users.models.CreatedResponse
import scala.concurrent.{ExecutionContext, Future}
@Singleton
class DrinkController @Inject()(actorSystem: ActorSystem, drinksRepository: DrinksRepository)
(implicit exec: ExecutionContext) extends Controller {
val logger: Logger = Logger(this.getClass)
def getDrinks(drinkTypeString: String) = Action.async {
Future(DrinkType.withName(drinkTypeString.toUpperCase))
.flatMap(drinksRepository.getAll)
.map(drinks => Ok(Json.toJson(DrinkResponse(drinks))))
.recoverWith({
case e: NoSuchElementException => Future {
BadRequest(e.toString)
}
case e => Future {
logger.error(e.toString)
InternalServerError
}
})
}
def saveDrink(drinkTypeString: String) = Action.async(parse.json[CreateDrinkDto]) { request =>
val drinkName = request.body.name
Future(DrinkType.withName(drinkTypeString.toUpperCase))
.map(Drink(drinkName, _))
.flatMap(drinksRepository.insert)
.map(id => Ok(Json.toJson(CreatedResponse(id))))
.recoverWith({
case e: NoSuchElementException => Future {
BadRequest(e.toString)
}
case e => Future {
logger.error(e.toString)
InternalServerError
}
})
}
}
示例11: format
//设置package包名称以及导入依赖的类
package au.com.agiledigital.rest.json
import java.util.NoSuchElementException
import play.api.libs.json._
import scala.util.Try
def format[A <: Enumeration](e: A): Format[A#Value] = {
new Format[A#Value] {
val className = e.getClass
override def writes(o: A#Value): JsValue = JsString(o.toString)
override def reads(json: JsValue): JsResult[A#Value] = json match {
case JsString(name) =>
Try {
JsSuccess(e.withName(name))
} recover {
case nse: NoSuchElementException =>
JsError(s"""Unknown $className [$name], accepted values are [${e.values.mkString(",")}].""")
} getOrElse {
JsError(s"""Unknown $className [$name], accepted values are [${e.values.mkString(",")}].""")
}
case u => JsError(s"Input for $className should be a JsString, got a [${u.getClass}] - [$u].")
}
}
}
}