本文整理汇总了Scala中scala.util.Try类的典型用法代码示例。如果您正苦于以下问题:Scala Try类的具体用法?Scala Try怎么用?Scala Try使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Try类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: IdJwtHandler
//设置package包名称以及导入依赖的类
package io.scalac.frees.login.handlers.id
import java.security.{PrivateKey, PublicKey}
import java.util.concurrent.TimeUnit
import cats.Id
import io.scalac.frees.login.algebras.{Claims, JwtService}
import io.scalac.frees.login.types.{JWT, UserId}
import pdi.jwt.{Jwt, JwtAlgorithm, JwtCirce, JwtClaim}
import scala.concurrent.duration.FiniteDuration
import scala.util.Try
class IdJwtHandler(
pubKey: PublicKey,
privKey: PrivateKey
) extends JwtService.Handler[Id] {
val twoDays = FiniteDuration(2, TimeUnit.DAYS).toSeconds
val algo = JwtAlgorithm.ES512
override def issue(id: UserId): Id[JWT] = {
val claim = JwtClaim()
.about(id.toString)
.issuedNow
.expiresIn(twoDays)
Jwt.encode(claim, privKey, algo)
}
override def validate(jwt: JWT): Id[Option[Claims]] = {
JwtCirce.decode(jwt, pubKey, Seq(algo)).toOption.flatMap { c =>
for {
userId <- c.subject.flatMap(s => Try(s.toLong).toOption)
expiration <- c.expiration.filter(_ > currentTimeSeconds)
issuedAt <- c.issuedAt.filter(_ <= System.currentTimeMillis())
} yield Claims(userId, issuedAt, expiration)
}
}
private def currentTimeSeconds: Long = System.currentTimeMillis() / 1000
}
示例2: Server
//设置package包名称以及导入依赖的类
package foobar
import foobar.page.{Contact, Index}
import org.http4s.MediaType.`text/html`
import org.http4s.dsl._
import org.http4s.headers.`Content-Type`
import org.http4s.server.ServerApp
import org.http4s.server.blaze._
import org.http4s.{HttpService, Response, StaticFile}
import scala.io.Source
import scala.util.Try
import scalatags.Text.TypedTag
import scalaz.concurrent.Task
object Server extends ServerApp {
def page(p: TypedTag[String]): Task[Response] =
Ok(p.render).withContentType(Some(`Content-Type`(`text/html`)))
val service = HttpService {
case GET -> Root => page(Index.page)
case GET -> Root / "contact" => page(Contact.page)
case req @ GET -> Root / path =>
println("file: " + Try(Source.fromFile(path).getLines().mkString))
StaticFile.fromResource(path.toString, Some(req)).fold(NotFound())(Task.now)
}
def server(args: List[String]) =
BlazeBuilder.bindHttp(8080)
.mountService(service, "/")
.start
}
示例3: ActivationProviders
//设置package包名称以及导入依赖的类
package im.actor.server.activation.common
import akka.actor.ActorSystem
import im.actor.config.ActorConfig
import scala.collection.JavaConversions._
import scala.util.{ Failure, Success, Try }
object ActivationProviders {
val Sms = "sms"
val Smtp = "smtp"
val Call = "call"
val Internal = "internal"
/**
* Instantiates activation providers based on configuration.
* Makes sure to instantiate only one instance of provider,
* if it is present for several activation types
* @param system actor system
* @return map from activation type to activation provider instance
*/
def getProviders()(implicit system: ActorSystem): Map[String, ActivationProvider] = {
val providersConfig = ActorConfig.load().getConfig("services.activation.providers")
val configMap = providersConfig.root.unwrapped.toMap
val reverseAcc = Map.empty[String, List[String]].withDefaultValue(List.empty[String])
// this is made to avoid duplicate instantiation of same providers
val reverseMap = (configMap foldLeft reverseAcc) {
case (acc, (activationType, value)) ?
val className = value.toString
acc.updated(className, activationType :: acc(className))
}
reverseMap flatMap {
case (className, activationTypes) ?
providerOf(className, system) match {
case Success(instance) ?
system.log.debug("Successfully instantiated code provider: {}, for activation types: [{}]", className, activationTypes mkString ", ")
(activationTypes map { _ ? instance }).toMap
case Failure(e) ?
system.log.warning("Failed to instantiate code provider: {}, exception: {}", className, e)
Map.empty[String, ActivationProvider]
}
}
}
private def providerOf(fqcn: String, system: ActorSystem): Try[ActivationProvider] = {
for {
constructor ? Try(Class.forName(fqcn).asSubclass(classOf[ActivationProvider]).getConstructor(classOf[ActorSystem]))
} yield constructor.newInstance(system)
}
}
示例4: SeqUpdatesManagerRegion
//设置package包名称以及导入依赖的类
package im.actor.server.sequence
import akka.actor.{ ActorRef, ActorSystem, Props }
import akka.cluster.sharding.{ ClusterSharding, ClusterShardingSettings, ShardRegion }
import akka.event.Logging
import scala.util.{ Success, Try }
final case class SeqUpdatesManagerRegion(ref: ActorRef)
object SeqUpdatesManagerRegion {
import UserSequenceCommands._
private def extractEntityId(system: ActorSystem): ShardRegion.ExtractEntityId = {
val log = Logging(system, getClass)
{
case e @ Envelope(userId, payload) ? (userId.toString, Try(e.getField(Envelope.descriptor.findFieldByNumber(payload.number))) match {
case Success(any) ? any
case _ ?
val error = new RuntimeException(s"Payload not found for $e")
log.error(error, error.getMessage)
throw error
})
}
}
private val extractShardId: ShardRegion.ExtractShardId = {
case Envelope(userId, _) ? (userId % 10).toString // TODO: configurable
}
private val typeName = "SeqUpdatesManager"
private def start(props: Props)(implicit system: ActorSystem): SeqUpdatesManagerRegion =
SeqUpdatesManagerRegion(ClusterSharding(system).start(
typeName = typeName,
entityProps = props,
settings = ClusterShardingSettings(system),
extractEntityId = extractEntityId(system),
extractShardId = extractShardId
))
def start()(
implicit
system: ActorSystem
): SeqUpdatesManagerRegion =
start(UserSequence.props)
def startProxy()(implicit system: ActorSystem): SeqUpdatesManagerRegion =
SeqUpdatesManagerRegion(ClusterSharding(system).startProxy(
typeName = typeName,
role = None,
extractEntityId = extractEntityId(system),
extractShardId = extractShardId
))
}
示例5: parseResult
//设置package包名称以及导入依赖的类
package neo4j.client
import play.api.libs.json._
import play.api.libs.functional.syntax._
import scala.util.{ Success, Failure, Try }
trait CypherResultParser extends CypherResponseParser {
override def parseResult[R](result: JsValue)(implicit parser: Reads[R]): Try[Seq[R]] = {
val rows = (result \ "data").as[JsArray].value.map(row ? {
// TODO: there should be a cleaner way of doing this; perhaps by looking at the returned "columns" field.
val r = row \ "row"
if (r.apply(1).toOption.isDefined) {
r
} else {
r(0)
}
})
val parsed = rows.map(row ? row.validate[R])
if (parsed.forall(res ? res.isSuccess)) {
Success(parsed.map(_.get))
} else {
val e = buildErrorMessage(parsed.filter(_.isError).asInstanceOf[Seq[JsError]])
Failure(new JsonValidationException(e.mkString("\n"), Some(result)))
}
}
}
object CypherResultAndErrorParser extends CypherResultParser with CypherErrorParser
object CypherErrorOnlyParser extends CypherNoopResultParser with CypherErrorParser
示例6: PlayJsonSnapshotMatcherSpec
//设置package包名称以及导入依赖的类
package com.commodityvectors.snapshotmatchers.playJson
import java.io.File
import com.commodityvectors.snapshotmatchers.{SnapshotMatcher, SnapshotSerializer}
import org.apache.commons.io.FileUtils
import org.scalatest.{BeforeAndAfterEach, Matchers, fixture}
import play.api.libs.json.{Format, JsValue, Json}
import scala.util.Try
class PlayJsonSnapshotMatcherSpec extends fixture.WordSpec with Matchers with SnapshotMatcher with PlayJsonSnapshotMatcher with BeforeAndAfterEach {
case class Test(value: Int)
implicit lazy val jsonFormat: Format[Test] = Json.format[Test]
val snapshotFolder: String = "scalatest-snapshot-matcher-play-json/src/test/__snapshots__"
val currentSpecPath: String = s"$snapshotFolder/com/commodityvectors/snapshotmatchers/playJson/PlayJsonSnapshotMatcherSpec"
override def afterEach(): Unit = {
Try(FileUtils.deleteDirectory(new File(snapshotFolder)))
}
"PlayJsonSnapshotMatcherSpec" should {
"pretty print json" in { implicit test =>
val instance = Test(1)
SnapshotSerializer.serialize(Json.toJson(instance)) shouldEqual
s"""{
| "value" : 1
|}""".stripMargin
}
"generate json snapshot file" in { implicit test =>
val instance = Test(1)
Json.toJson(instance) should matchSnapshot[JsValue]("customId")
FileUtils.readFileToString(
new File(s"$currentSpecPath/customId.snap")
) shouldEqual
s"""{
| "value" : 1
|}""".stripMargin
}
"allow deserialization" in { implicit test =>
val instance = Test(1)
Json.toJson(instance) should matchSnapshot[JsValue]("anotherId")
"anotherId" should deserializeAs(instance)
}
}
}
开发者ID:commodityvectors,项目名称:scalatest-snapshot-matchers,代码行数:50,代码来源:PlayJsonSnapshotMatcherSpec.scala
示例7: weekends
//设置package包名称以及导入依赖的类
package ps.csv
import scala.util.Try
object weekends {
def main(args: Array[String]): Unit = {
if (args.length <= 0) sys.error("You have to pass a csv file as a parameter")
System.err.println(s"weekends file: ${args(0)}")
convertDates(args(0))
def convertDates(fname: String): Unit = {
import com.github.tototoshi.csv._
val inp = CSVReader.open(fname)
inp.foreach(fields => doOneYear(fields))
inp.close()
}
def doOneYear(fields: Seq[String]): Unit = {
val year = Try { fields(0).toInt }
.map { y => doYear(y, fields) }
.foreach( outpYear(_) )
}
def outpYear(dates: Seq[String]): Unit = {
for (date <- dates) println(date)
}
def doYear(year: Int, fields: Seq[String]): Seq[String] = {
for {
month <- 1 to 12
lst = fields(month)
day <- lst.split(",")
date <- makeDate(year, month, day)
} yield date
}
def makeDate(year: Int, month: Int, day: String): Option[String] = {
Try { day.toInt }.map( d => f"$year-$month%02d-$d%02d" ).toOption
}
}
}
示例8: LocalDateTimeCoercionViolation
//设置package包名称以及导入依赖的类
package io.soheila.cms.api
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.Locale
import sangria.ast.StringValue
import sangria.schema.ScalarType
import sangria.validation.ValueCoercionViolation
import scala.util.{ Failure, Success, Try }
package object graphql {
case object LocalDateTimeCoercionViolation extends ValueCoercionViolation("Date value expected")
case object LocaleCoercionViolation extends ValueCoercionViolation("Locale value expected")
private[graphql] def parseLocalDateTime(s: String) = Try(LocalDateTime.parse(s)) match {
case Success(date) => Right(date)
case Failure(_) => Left(LocalDateTimeCoercionViolation)
}
private[graphql] def parseLocale(s: String) = Try(Locale.forLanguageTag(s)) match {
case Success(locale) => Right(locale)
case Failure(_) => Left(LocaleCoercionViolation)
}
val LocalDateTimeType = ScalarType[LocalDateTime](
"LocalDateTime",
coerceOutput = (value, caps) => value.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME),
coerceUserInput = {
case s: String => parseLocalDateTime(s)
case _ => Left(LocalDateTimeCoercionViolation)
},
coerceInput = {
case StringValue(s, _, _) => parseLocalDateTime(s)
case _ => Left(LocalDateTimeCoercionViolation)
}
)
val LocaleType = ScalarType[Locale](
"Locale",
coerceOutput = (value, caps) => value.toLanguageTag,
coerceUserInput = {
case s: String => parseLocale(s)
case _ => Left(LocaleCoercionViolation)
},
coerceInput = {
case StringValue(s, _, _) => parseLocale(s)
case _ => Left(LocaleCoercionViolation)
}
)
}
示例9: Publisher
//设置package包名称以及导入依赖的类
import org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence
import org.eclipse.paho.client.mqttv3.{MqttClient, MqttMessage}
import scala.util.{Failure, Random, Success, Try}
object Publisher extends App {
// Global information
val name = "apdl-case-study-from-scratch"
// MQTT Server info to publish
val brokerURL = "tcp://mosquitto-mqtt:1883"
val topicTemperature = s"temp"
val topicLuminosity = s"light"
val persistence = new MqttDefaultFilePersistence("tmp")
Try {
val client = new MqttClient(brokerURL, MqttClient.generateClientId(), persistence)
client.connect()
val topicTemp = client.getTopic(topicTemperature)
val topicLight = client.getTopic(topicLuminosity)
while (true) {
val temp = Random.nextInt(10) + 20
val light = Random.nextInt(40) + 640
val msgTemp = new MqttMessage(s"$temp".getBytes)
val msgLight = new MqttMessage(s"$light".getBytes)
println(s"Publish $temp to $topicTemperature")
println(s"Publish $light to $topicLight")
topicTemp.publish(msgTemp)
topicLight.publish(msgLight)
Thread.sleep(1000)
}
while(true) {
println("OK !")
Thread.sleep(1000)
}
} match {
case Failure(exception) => println(s"ERROR : $exception + ${exception.getCause}")
case Success(_) => println(s"OK !")
}
}
示例10: Categorical
//设置package包名称以及导入依赖的类
package org.sclot.dataset
import scala.util.Try
sealed trait DataKind
case object Categorical extends DataKind
case object Integral extends DataKind
case object Numeral extends DataKind
object DataKind {
def findKind(s:String): DataKind =
if(Try(s.toInt).isSuccess) Integral else if (Try(s.toDouble).isSuccess) Numeral else Categorical
def findBestKind(things:Seq[String]): DataKind = {
val kinds = things.map(findKind)
if(kinds.forall(klass => klass == Integral)) Integral
else if(kinds.forall(kind => kind == Integral || kind == Numeral)) Numeral
else Categorical
}
}
示例11: ReflectiveDynamicAccess
//设置package包名称以及导入依赖的类
package akka.actor
import scala.collection.immutable
import java.lang.reflect.InvocationTargetException
import scala.reflect.ClassTag
import scala.util.Try
class ReflectiveDynamicAccess(val classLoader: ClassLoader) extends DynamicAccess {
override def getClassFor[T: ClassTag](fqcn: String): Try[Class[_ <: T]] =
Try[Class[_ <: T]]({
val c = Class.forName(fqcn, false, classLoader).asInstanceOf[Class[_ <: T]]
val t = implicitly[ClassTag[T]].runtimeClass
if (t.isAssignableFrom(c)) c else throw new ClassCastException(t + " is not assignable from " + c)
})
override def createInstanceFor[T: ClassTag](clazz: Class[_], args: immutable.Seq[(Class[_], AnyRef)]): Try[T] =
Try {
val types = args.map(_._1).toArray
val values = args.map(_._2).toArray
val constructor = clazz.getDeclaredConstructor(types: _*)
constructor.setAccessible(true)
val obj = constructor.newInstance(values: _*)
val t = implicitly[ClassTag[T]].runtimeClass
if (t.isInstance(obj)) obj.asInstanceOf[T] else throw new ClassCastException(clazz.getName + " is not a subtype of " + t)
} recover { case i: InvocationTargetException if i.getTargetException ne null ? throw i.getTargetException }
override def createInstanceFor[T: ClassTag](fqcn: String, args: immutable.Seq[(Class[_], AnyRef)]): Try[T] =
getClassFor(fqcn) flatMap { c ? createInstanceFor(c, args) }
override def getObjectFor[T: ClassTag](fqcn: String): Try[T] = {
val classTry =
if (fqcn.endsWith("$")) getClassFor(fqcn)
else getClassFor(fqcn + "$") recoverWith { case _ ? getClassFor(fqcn) }
classTry flatMap { c ?
Try {
val module = c.getDeclaredField("MODULE$")
module.setAccessible(true)
val t = implicitly[ClassTag[T]].runtimeClass
module.get(null) match {
case null ? throw new NullPointerException
case x if !t.isInstance(x) ? throw new ClassCastException(fqcn + " is not a subtype of " + t)
case x: T ? x
}
} recover { case i: InvocationTargetException if i.getTargetException ne null ? throw i.getTargetException }
}
}
}
示例12: WiremockStart
//设置package包名称以及导入依赖的类
package uk.co.telegraph.sbt.wiremock.tasks
import java.net.Socket
import sbt._
import sbt.Keys.TaskStreams
import scala.util.Try
object WiremockStart {
import uk.co.telegraph.sbt.process.ProcessId._
private def isPortAvailable(port:Int):Boolean = {
Try( new Socket("localhost", port).close() ).isSuccess
}
def apply(
targetDir:File,
httpPort:Int,
httpsPort:Option[Int],
otherArgs:Map[String, Any],
logger:Logger
):String = {
val localJar = new File(targetDir, "wiremock-standalone.jar")
//Check ports available
if( isPortAvailable(httpPort) ){
sys.error(s"Port already being used [$httpPort].")
}
if( httpsPort.exists(isPortAvailable) ){
sys.error(s"Port already being used [$httpPort].")
}
val args = Seq("java") ++
Seq("-jar", localJar.getAbsolutePath) ++
Seq("--port", httpPort.toString) ++
httpsPort.map( p => Seq("--https-port", p.toString)).getOrElse(Seq.empty) ++
otherArgs.flatMap({
case (key, Some(value)) => Seq(key, value.toString)
case (key, true ) => Seq(key)
case (key, value ) => Seq(key, value.toString)
})
logger.info ("Starting Wiremock")
logger.info(s" Application: ${localJar.getPath}")
logger.info(s" Arguments : ${args.toString}")
Process(args).run()
do {
logger.info (s"Waiting for Wiremock to boot on port [$httpPort]")
Thread.sleep( 500 )
}while(!isPortAvailable(httpPort))
extractPid("jps -ml".!!, httpPort, localJar).getOrElse {
sys.error(s"Cannot find wiremock PID running on $httpPort")
}
}
}
示例13: AssetCompilers
//设置package包名称以及导入依赖的类
package com.karasiq.scalajsbundler.compilers
import scala.util.Try
case class AssetCompilers(pf: PartialFunction[String, AssetCompiler]) extends AnyVal {
def apply(mime: String): AssetCompiler = {
pf.applyOrElse(mime, (_: String) ? throw new IllegalArgumentException(s"No compiler defined for $mime"))
}
def orElse(pf: PartialFunction[String, AssetCompiler]): AssetCompilers = {
AssetCompilers(this.pf.orElse(pf))
}
def <<=(ac: AssetCompilers): AssetCompilers = {
this.orElse(ac.pf)
}
}
object AssetCompilers {
private object Mimes extends PredefinedMimeTypes
private def classExists(className: String): Boolean = {
Try(Class.forName(className, false, getClass.getClassLoader)).isSuccess
}
private def newCompiler(className: String): AssetCompiler = {
Class.forName(s"com.karasiq.scalajsbundler.compilers.$className")
.newInstance().asInstanceOf[AssetCompiler]
}
def default: AssetCompilers = AssetCompilers {
case Mimes.coffeescript ?
CoffeeScriptCompiler
case Mimes.less if classExists("com.github.sommeri.less4j.core.DefaultLessCompiler") ?
newCompiler("Less4jCompiler")
case Mimes.javascript if classExists("com.google.javascript.jscomp.Compiler") ?
newCompiler("JsClosureCompiler")
case Mimes.javascript if classExists("com.yahoo.platform.yui.compressor.JavaScriptCompressor") ?
newCompiler("JsYuiCompiler")
case Mimes.css if classExists("com.yahoo.platform.yui.compressor.CssCompressor") ?
newCompiler("CssYuiCompiler")
case Mimes.html if classExists("com.googlecode.htmlcompressor.compressor.HtmlCompressor") ?
newCompiler("HtmlGoogleCompiler")
case Mimes.jade if classExists("de.neuland.jade4j.Jade4J") ?
newCompiler("Jade4jCompiler")
}
}
示例14: AddUserRequest
//设置package包名称以及导入依赖的类
package controllers.DTO
import models.Users
import org.mindrot.jbcrypt.BCrypt
import scala.util.Try
case class AddUserRequest(
email: String,
name: String,
password: String
) {
def toUser: Try[Users] = Try {
Users(
id = None,
email = email,
name = name,
password = BCrypt.hashpw(password, BCrypt.gensalt(12))
)
}
}
示例15: RecordPaymentRequest
//设置package包名称以及导入依赖的类
package controllers.DTO
import models.Entry
import org.joda.time.{DateTime, DateTimeZone}
import scala.util.Try
case class RecordPaymentRequest(
coupleId: Long,
payerUserId: Long,
amount: Double,
submitterUserId: Long
) {
def toEntry: Try[Entry] = Try {
val subPer = if (submitterUserId == payerUserId) 0 else 100
Entry(
id = None,
coupleId = coupleId,
date = DateTime.now(DateTimeZone.UTC),
payerUserId = payerUserId,
amount = amount,
submitterUserId = submitterUserId,
submitterPercent = subPer
)
}
}