• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala Try类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



在下文中一共展示了Try类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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

} 
开发者ID:LGLO,项目名称:freestyle-login,代码行数:44,代码来源:IdJwtHandler.scala


示例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
} 
开发者ID:julien-truffaut,项目名称:FooBar,代码行数:34,代码来源:Server.scala


示例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)
  }
} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:53,代码来源:ActivationProviders.scala


示例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
    ))
} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:58,代码来源:SeqUpdatesManagerRegion.scala


示例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 
开发者ID:mardambey,项目名称:neo4j-scala-dsl,代码行数:36,代码来源:CypherResponseParser.scala


示例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
        }
    }
} 
开发者ID:vasnake,项目名称:weekends,代码行数:45,代码来源:weekends.scala


示例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)
    }
  )
} 
开发者ID:esfand-r,项目名称:soheila-cm,代码行数:53,代码来源:package.scala


示例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 !")
  }
} 
开发者ID:SnipyJulmy,项目名称:APDL-from-scratch-mqtt,代码行数:48,代码来源:Publisher.scala


示例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
  }
} 
开发者ID:matthhan,项目名称:sclot,代码行数:19,代码来源:DataKind.scala


示例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 }
    }
  }
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:50,代码来源:DynamicAccess.scala


示例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")
    }
  }
} 
开发者ID:telegraph,项目名称:sbt-wiremock,代码行数:59,代码来源:WiremockStart.scala


示例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")
  }
} 
开发者ID:Karasiq,项目名称:sbt-scalajs-bundler,代码行数:55,代码来源:AssetCompilers.scala


示例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))
    )
  }
} 
开发者ID:JAGormley,项目名称:dutch-scala,代码行数:22,代码来源:AddUserRequest.scala


示例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
    )
  }
} 
开发者ID:JAGormley,项目名称:dutch-scala,代码行数:28,代码来源:RecordPaymentRequest.scala


示例16: RecordPurchaseRequest

//设置package包名称以及导入依赖的类
package controllers.DTO
import models.Entry
import org.joda.time.{DateTime, DateTimeZone}

import scala.util.Try


case class RecordPurchaseRequest(
                               payerUserId: Long,
                               amount: Double,
                               submitterPercent: Long,
                               note: Option[String]
) {
  def toEntry(coupleId: Long, submitterUserId: Long): Try[Entry] = Try {
    Entry(
      id = None,
      coupleId = coupleId,
      date = DateTime.now(DateTimeZone.UTC),
      payerUserId = payerUserId,
      amount = amount,
      submitterUserId = submitterUserId,
      submitterPercent = submitterPercent,
      note = note
    )
  }

} 
开发者ID:JAGormley,项目名称:dutch-scala,代码行数:28,代码来源:RecordPurchaseRequest.scala


示例17: Mailer

//设置package包名称以及导入依赖的类
package conf.util.mail

import org.apache.commons.mail.{DefaultAuthenticator, HtmlEmail}

import scala.util.Try


object Mailer {

  def send(emailMessage: EmailMessage) = Try({
    val email = new HtmlEmail()
    email.setStartTLSEnabled(true)
    email.setStartTLSRequired(true)
    email.setBounceAddress(emailMessage.recipient)
    email.setSmtpPort(emailMessage.smtpConfig.port)
    email.setHostName(emailMessage.smtpConfig.host)
    email.setAuthenticator(new DefaultAuthenticator(
      emailMessage.smtpConfig.user,
      emailMessage.smtpConfig.password
    ))
    email.setHtmlMsg(emailMessage.html)
      .setTextMsg(emailMessage.text)
      .addTo(emailMessage.recipient)
      .setFrom(emailMessage.from)
      .setSubject(emailMessage.subject)
      .send()
  })

} 
开发者ID:Masebeni,项目名称:hwork,代码行数:30,代码来源:Mailer.scala


示例18: ExecutionContextBackboneCoordinator

//设置package包名称以及导入依赖的类
package ie.zalando.pipeline.backbone.concurrent

import scala.concurrent.{ ExecutionContext, Future }
import scala.util.Try
import scala.util.control.NonFatal

import org.slf4j.LoggerFactory

import cats.data.Xor
import ie.zalando.pipeline.backbone.Backbone
import ie.zalando.pipeline.backbone.Phases.{ LocalReleasePhase, TransformationPipelineFailure }

class ExecutionContextBackboneCoordinator[DA](backbone: Backbone[DA], executionContext: ExecutionContext) {

  import ExecutionContextBackboneCoordinator._

  val localInitPhases = backbone.initializeTopLevelContexts

  def process(datum: DA): Future[Xor[TransformationPipelineFailure, DA]] = {
    Future {
      val (dataPhases, releasePhases) = backbone.initializeInLocalContext(-1, localInitPhases).unzip
      try {
        backbone.transformDatum(backbone.createStateMonad(dataPhases), datum)
      } finally {
        releasePhases.foreach((phase: LocalReleasePhase) => {
          Try({ phase.releaseLocalResources() }).recover { case NonFatal(ex) => log.warn(s"Release phase $phase failed:", ex) }
        })
      }
    }(executionContext)
  }

}

object ExecutionContextBackboneCoordinator {
  val log = LoggerFactory.getLogger(classOf[ExecutorServiceBackboneCoordinator[_]])
} 
开发者ID:retnuh,项目名称:pipeline-backbone,代码行数:37,代码来源:ExecutionContextBackboneCoordinator.scala


示例19: ExecutorServiceBackboneCoordinator

//设置package包名称以及导入依赖的类
package ie.zalando.pipeline.backbone.concurrent

import java.util.concurrent.{ Callable, Future, ExecutorService }

import scala.util.Try
import scala.util.control.NonFatal

import org.slf4j.LoggerFactory

import cats.data.Xor
import ie.zalando.pipeline.backbone.Backbone
import ie.zalando.pipeline.backbone.Phases.{ LocalReleasePhase, TransformationPipelineFailure }

class ExecutorServiceBackboneCoordinator[DA](backbone: Backbone[DA], executor: ExecutorService) {
  import ExecutorServiceBackboneCoordinator._

  val localInitPhases = backbone.initializeTopLevelContexts

  private class BackboneCallable(datum: DA) extends Callable[Xor[TransformationPipelineFailure, DA]] {
    override def call(): Xor[TransformationPipelineFailure, DA] = {
      val (dataPhases, releasePhases) = backbone.initializeInLocalContext(-1, localInitPhases).unzip
      try {
        backbone.transformDatum(backbone.createStateMonad(dataPhases), datum)
      } finally {
        releasePhases.foreach((phase: LocalReleasePhase) => {
          Try({ phase.releaseLocalResources() }).recover { case NonFatal(ex) => log.warn(s"Release phase $phase failed:", ex) }
        })
      }
    }
  }

  def process(datum: DA): Future[Xor[TransformationPipelineFailure, DA]] = {
    executor.submit(new BackboneCallable(datum))
  }

}

object ExecutorServiceBackboneCoordinator {
  val log = LoggerFactory.getLogger(classOf[ExecutorServiceBackboneCoordinator[_]])
} 
开发者ID:retnuh,项目名称:pipeline-backbone,代码行数:41,代码来源:ExecutorServiceBackboneCoordinator.scala


示例20: CompressedStorage

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

import cats.Monad
import cats.implicits._
import slate.bindings.LZString

import scala.util.Try

final case class CompressedStorage[F[_] : Monad](underlying: Storage[F]) extends Storage[F] {
  override def apply(key: String): F[Option[String]] =
    underlying(key).map(
      _.flatMap(r =>
        Try(LZString.decompressFromUTF16(r)).toOption
      )
    )

  override def update(key: String, data: String): F[Unit] =
    underlying.update(key, LZString.compressToUTF16(data))

  override def remove(key: String): F[Unit] =
    underlying.remove(key)
} 
开发者ID:edmundnoble,项目名称:slate,代码行数:23,代码来源:CompressedStorage.scala



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala Matchers类代码示例发布时间:2022-05-23
下一篇:
Scala ExecutionContext类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap