本文整理汇总了Scala中com.typesafe.scalalogging.StrictLogging类的典型用法代码示例。如果您正苦于以下问题:Scala StrictLogging类的具体用法?Scala StrictLogging怎么用?Scala StrictLogging使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了StrictLogging类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: name
//设置package包名称以及导入依赖的类
package cz.alenkacz.marathon.scaler
import com.typesafe.scalalogging.StrictLogging
import cz.alenkacz.marathon.scaler.rabbitmq.Client
import scala.util.{Failure, Success, Try}
trait Application {
def name: String
def vhost: String
def queueName: String
def maxMessagesCount: Int
def maxInstancesCount: Option[Int]
def minInstancesCount: Option[Int]
def rmqServerName: String
}
object ApplicationFactory extends StrictLogging {
def tryCreate(rabbitMqClient: Client,
name: String,
rmqServerName: String,
vhost: String,
queueName: String,
maxMessagesCount: Int,
maxInstancesCount: Option[Int] = None,
minInstancesCount: Option[Int] = None): Try[Application] = {
rabbitMqClient.queueExists(vhost, queueName) match {
case Success(true) =>
Success(
ApplicationImpl(name,
rmqServerName,
vhost,
queueName,
maxMessagesCount,
maxInstancesCount,
minInstancesCount))
case Failure(e) =>
logger.warn(
s"Unable to verify that '$queueName' for application '$name' exists. Ignoring this application configuration.",
e)
Failure(e)
case _ =>
logger.warn(
s"Queue '$queueName' for application '$name' does not exist. Ignoring this application configuration.")
Failure(
new Exception(
s"Queue '$queueName' for application '$name' does not exist."))
}
}
private case class ApplicationImpl(name: String,
rmqServerName: String,
vhost: String,
queueName: String,
maxMessagesCount: Int,
maxInstancesCount: Option[Int] = None,
minInstancesCount: Option[Int] = None)
extends Application
}
开发者ID:alenkacz,项目名称:marathon-rabbitmq-autoscale,代码行数:60,代码来源:Application.scala
示例2: ScrapingKitReactor
//设置package包名称以及导入依赖的类
package ru.fediq.scrapingkit
import akka.actor.{ActorSystem, Props}
import akka.http.scaladsl.model.Uri
import akka.routing.RoundRobinPool
import com.typesafe.scalalogging.StrictLogging
import net.ceedubs.ficus.Ficus._
import net.ceedubs.ficus.readers.ArbitraryTypeReader._
import ru.fediq.scrapingkit.backend.{FeedExporter, LinksHistory, LinksQueue, PageCache}
import ru.fediq.scrapingkit.model.PageRef
import ru.fediq.scrapingkit.platform._
import ru.fediq.scrapingkit.scraper.Scraper
import scala.util.Try
class ScrapingKitReactor(
linksQueue: LinksQueue,
linksHistory: LinksHistory,
pageCache: PageCache,
exporter: FeedExporter,
scrapers: Map[String, Scraper],
redirectFilter: Option[(PageRef, Uri) => Boolean] = None
)(implicit val system: ActorSystem)
extends AnyRef with AutoCloseable with StrictLogging {
val config = system.settings.config.as[ScrapingKitConfig]("scrapingkit")
val queueingActor = system
.actorOf(
Props(new QueueingActor(linksQueue, linksHistory, config))
.withDispatcher("pinnedDispatcher"),
"queueing"
)
val downloadingActor = system
.actorOf(
Props(new DownloadingActor(pageCache, config, redirectFilter)),
"downloading"
)
val scrapingActor = system
.actorOf(
RoundRobinPool(config.scrapingThreads, routerDispatcher = "pinnedDispatcher")
.props(Props(new ScrapingActor(scrapers, exporter, config))),
"scraping"
)
system.registerOnTermination(close())
override def close() = {
logger.info("Stopping ScarpingKit Reactor")
Try(linksQueue.close())
Try(linksHistory.close())
Try(pageCache.close())
Try(exporter.close())
logger.info("Stopped")
}
}
开发者ID:fediq,项目名称:scraping-kit,代码行数:59,代码来源:ScrapingKitReactor.scala
示例3: MyApplicationLoader
//设置package包名称以及导入依赖的类
package my.samples.core
import com.typesafe.config.ConfigFactory
import com.typesafe.scalalogging.{ LazyLogging, StrictLogging }
import controllers.Assets
import play.api.{ Application, BuiltInComponentsFromContext, Configuration, _ }
import play.api.libs.ws.ahc.AhcWSComponents
import my.samples.controllers.MyApplicationController
import play.api.ApplicationLoader.Context
import play.api.routing.Router
import router.Routes
import scala.concurrent.Future
// compile time DI for loading the play application
final class MyApplicationLoader extends ApplicationLoader with LazyLogging {
override def load(context: Context): Application = {
val configuration = Configuration(ConfigFactory.load())
val newContext = context.copy(initialConfiguration = configuration)
LoggerConfigurator(newContext.environment.classLoader)
.foreach(_.configure(newContext.environment))
new MyApp(newContext).application
}
}
class MyApp(context: Context)
extends BuiltInComponentsFromContext(context) with AhcWSComponents with StrictLogging {
implicit val s = monix.execution.Scheduler.Implicits.global
def stop(bindings: AppBindings) = {
logger.info("stopping application")
bindings.globalChannel.publishChannel.onComplete()
}
def start = {
logger.info("starting application")
AppBindings(actorSystem, materializer)
}
// 1. create the dependencies that will be injected
lazy val appBindings = start
// 2. inject the dependencies into the controllers
lazy val applicationController = new MyApplicationController(appBindings)
lazy val assets = new Assets(httpErrorHandler)
override def router: Router = new Routes(
httpErrorHandler, applicationController, assets
)
// 3. add the shutdown hook to properly dispose all connections
applicationLifecycle.addStopHook { () => Future(stop(appBindings)) }
}
开发者ID:joesan,项目名称:monix-samples,代码行数:55,代码来源:MyApplicationLoader.scala
示例4: Debug
//设置package包名称以及导入依赖的类
package se.kth.climate.fast.netcdf
import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
//import org.apache.hadoop.conf.Configuration
import com.typesafe.scalalogging.StrictLogging
object Debug extends App with StrictLogging {
// val config = new Configuration();
val conf = new SparkConf().setAppName("Diurnal Temperature Range");
conf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer");
conf.set("spark.kryo.registrator", "se.kth.climate.fast.netcdf.NCKryoRegistrator");
conf.set("spark.kryoserializer.buffer.max", "512m");
conf.set("spark.kryo.registrationRequired", "true");
implicit val sc = new SparkContext(conf);
sc.setLogLevel("DEBUG");
val meta = NetCDF.metaData("hdfs://10.0.104.162:8020/Projects/ClimateTest2/TestData/");
logger.info(s"****** Metadata *********\n$meta");
val rdd = NetCDF.rawData("hdfs://10.0.104.162:8020/Projects/ClimateTest2/TestData/rows_0-76695843.nc");
val res = rdd.map { ncfile =>
val v = ncfile.findVariable("values");
val arr = v.read();
val it = arr.getIndexIterator();
var zeroCount = 0;
while (it.hasNext) {
val v = it.getIntNext();
if (v == 0) zeroCount += 1 else ()
}
zeroCount
}.collect();
logger.info(s"****** Zeroes *********\n${res.mkString(",")}");
}
开发者ID:ClimateFAST,项目名称:FASTSpark,代码行数:36,代码来源:Debug.scala
示例5: AbstractExample
//设置package包名称以及导入依赖的类
package ru.tolsi.matcher
import scala.concurrent.duration.Duration
import scala.concurrent.{Await, ExecutionContext, Future}
import com.typesafe.scalalogging.StrictLogging
import org.slf4j.MarkerFactory
abstract class AbstractExample[C <: Client[Long]](
buildClient: ClientInfo => C,
clientRepository: Seq[C] => ClientRepository[Long],
orderExecutor: ReverseOrdersExecutor[Long],
orderBook: OrderBook)(implicit val ec: ExecutionContext) extends App with LoadExampleData with StrictLogging {
val ioEc = ExecutionContext.global
val loadClientsFuture = Future(loadClients(args.lift(0)).map(buildClient))(ioEc)
val loadCreateOrdersRequestsFuture = Future(loadCreateOrdersRequests(args.lift(1)))(ioEc)
val processFuture = for {
clients <- loadClientsFuture
clientsRepository = clientRepository(clients)
createOrdersRequests <- loadCreateOrdersRequestsFuture
_ <- {
logger.debug("Calculation started")
val exchange = new Exchange(clientsRepository, orderExecutor, orderBook)
exchange(createOrdersRequests)
}
clients <- clientsRepository.getAll
clientsBalances <- Future.sequence(clients.map(c => c.getAllBalances.map(balance => c.id -> balance)))
} yield {
def logClientBalance(userInfo: (String, Map[String, Long])): Unit = {
val (id, balances) = userInfo
logger.info(MarkerFactory.getMarker("results"), Seq(id, balances("USD"), balances("A"), balances("B"), balances(
"C"), balances("D")).mkString("\t"))
}
logger.debug(s"Final results:")
clientsBalances.toSeq.sortBy(_._1).foreach(logClientBalance)
}
Await.result(processFuture, Duration.Inf)
logger.debug("Calculation finished")
logger.debug("Results were recorded in the file 'results.txt'")
}
开发者ID:Tolsi,项目名称:matcher,代码行数:43,代码来源:AbstractExample.scala
示例6: SingleThreadOrderBook
//设置package包名称以及导入依赖的类
package ru.tolsi.matcher.naive
import scala.collection.mutable
import scala.concurrent.{ExecutionContext, Future}
import com.typesafe.scalalogging.StrictLogging
import ru.tolsi.matcher.OrderBook.AddOrMatchResult._
import ru.tolsi.matcher.{Order, OrderBook, OrderType, ReverseOrders}
private[naive] object SingleThreadOrderBook {
private[naive] def dequeueOrderWhichCanApply(
order: Order,
orderBook: collection.Map[String, collection.Map[(Int, Int, OrderType.Value), mutable.Queue[Order]]]): Option[Order] = {
import order._
orderBook.get(order.asset).flatMap(_.get((price, qty, OrderType.invert(`type`))).flatMap(_.dequeueFirst(_ => true)))
}
}
private[naive] class SingleThreadOrderBook extends OrderBook with StrictLogging {
import OrderBook._
import SingleThreadOrderBook._
private[naive] val instrumentsOrderBook = mutable.AnyRefMap
.empty[String, mutable.AnyRefMap[(Int, Int, OrderType.Value), mutable.Queue[Order]]]
override def addOrMatch(order: Order)(implicit ec: ExecutionContext): Future[AddOrMatchResult] = Future.successful {
dequeueOrderWhichCanApply(order, instrumentsOrderBook) match {
case Some(matchedOrder) =>
Matched(ReverseOrders(order, matchedOrder))
case None =>
import order._
instrumentsOrderBook.getOrElseUpdate(order.asset,
new mutable.AnyRefMap[(Int, Int, OrderType.Value), mutable.Queue[Order]]())
.getOrElseUpdate((price, qty, `type`), mutable.Queue.empty[Order]) += order
Added
}
}
}
开发者ID:Tolsi,项目名称:matcher,代码行数:37,代码来源:SingleThreadOrderBook.scala
示例7: LoadExampleData
//设置package包名称以及导入依赖的类
package ru.tolsi.matcher
import java.io.File
import com.typesafe.scalalogging.StrictLogging
import ru.tolsi.matcher.util.EitherUtils._
object LoadExampleData {
val defaultOrdersFilePath = "/orders.txt"
val defaultClientsFilePath = "/clients.txt"
}
trait LoadExampleData extends StrictLogging {
import LoadExampleData._
def loadClients(pathOpt: Option[String] = None): Seq[ClientInfo] = {
val (clientsErrors, clients) = splitEitherIterator(
ClientInfo.loadFromFile(
pathOpt.map(new File(_)).getOrElse(new File(getClass.getResource(defaultClientsFilePath).toURI))))
clientsErrors.foreach(logger.warn(_))
clients.toSeq
}
def loadCreateOrdersRequests(pathOpt: Option[String] = None): Seq[OrderOperation.Create] = {
val (ordersErrors, createOrdersRequests) = splitEitherIterator(
OrderOperation.Create.loadFromFile(
pathOpt.map(new File(_)).getOrElse(new File(getClass.getResource(defaultOrdersFilePath).toURI))))
ordersErrors.foreach(logger.warn(_))
createOrdersRequests.toSeq
}
}
开发者ID:Tolsi,项目名称:matcher,代码行数:28,代码来源:LoadExampleData.scala
示例8: Boot
//设置package包名称以及导入依赖的类
package app
import app.controllers.Application
import com.typesafe.scalalogging.StrictLogging
import com.ulasakdeniz.hakker.{Controller, LifeCycle}
object Boot extends LifeCycle with StrictLogging {
override def boot: List[Controller] = {
List(Application)
}
override def beforeStart: Unit = {
logger.info("BEFORE_START")
}
override def afterStop: Unit = {
logger.info("AFTER_STOP")
}
}
开发者ID:ulasakdeniz,项目名称:hakker-sample,代码行数:21,代码来源:Boot.scala
示例9: BatchService
//设置package包名称以及导入依赖的类
package sug.batchservice
import java.io.File
import com.github.tototoshi.csv.CSVReader
import com.typesafe.scalalogging.StrictLogging
import org.apache.commons.io.monitor.{FileAlterationListenerAdaptor, FileAlterationMonitor, FileAlterationObserver}
object BatchService extends App with StrictLogging {
def processor(person: Person): Person = person match {
case Person(fn, ln) => Person(fn.toUpperCase,ln.toUpperCase)
}
case class Person(firstName: String, lastName: String) {
override def toString: String = s"firstName: $firstName lastName: $lastName"
}
def monitor(directory: String, interval: Long = 1000) = {
val m = new FileAlterationMonitor(interval)
val o = new FileAlterationObserver(directory)
m.addObserver(o)
m.start()
val l = new FileAlterationListenerAdaptor {
override def onFileChange(file: File): Unit = {
logger.info(s"File changed ${file.getName}.")
//TODO
}
}
o.addListener(l)
}
def reader(absolutePath: String): List[List[String]] = {
val reader = CSVReader.open(new File(absolutePath))
val rows = reader.all()
logger.info(s"Read ${rows.size} row.")
rows.map(_.map(_.trim))
}
def converter(raw: List[String]): Either[List[String], Person] = raw match {
case firstName :: lastName :: Nil if lastName.nonEmpty && firstName.nonEmpty =>
Right(Person(firstName, lastName))
case row => Left(row)
}
def errorWriter(err: List[String]): Unit =
logger.info(s"Err: $err")
def okWriter(person: Person): Unit =
logger.info(s"Writer: $person")
}
开发者ID:mateuszjancy,项目名称:IntroToRxScala,代码行数:54,代码来源:BatchService.scala
示例10: SourceCodeInfo
//设置package包名称以及导入依赖的类
package tutor
import com.typesafe.scalalogging.StrictLogging
import tutor.utils.FileUtil
import tutor.utils.FileUtil._
import scala.util.Try
final case class SourceCodeInfo(path: String, localPath: String, lineCount: Int)
object SourceCodeInfo {
implicit object SourceCodeInfoOrdering extends Ordering[SourceCodeInfo] {
override def compare(x: SourceCodeInfo, y: SourceCodeInfo): Int = x.lineCount compare y.lineCount
}
}
trait SourceCodeAnalyzer extends StrictLogging {
def processFile(path: Path): Try[SourceCodeInfo] = {
import scala.io._
Try {
val source = Source.fromFile(path)
try {
val lines = source.getLines.toList
SourceCodeInfo(path, FileUtil.extractLocalPath(path), lines.length)
} catch {
case e: Throwable => throw new IllegalArgumentException(s"error processing file $path", e)
} finally {
source.close()
}
}
}
}
开发者ID:notyy,项目名称:CodeAnalyzerTutorial,代码行数:35,代码来源:SourceCodeInfo.scala
示例11: MainApp
//设置package包名称以及导入依赖的类
package tutor
import java.io.File
import com.typesafe.scalalogging.StrictLogging
import tutor.PresetFilters.{ignoreFolders, knownFileTypes}
import tutor.repo.{AnalyzeHistoryRepository, H2DB}
import tutor.utils.FileUtil.Path
import tutor.utils.{BenchmarkUtil, WriteSupport}
object MainApp extends App with ReportFormatter with WriteSupport with StrictLogging {
if (args.length < 1) {
println("usage: CodeAnalyzer FilePath [-oOutputfile]")
} else {
val path: Path = args(0)
val file = new File(path)
val analyzer = args.find(_.startsWith("-p")).map { _ =>
logger.info("using par collection mode")
new CodebaseAnalyzerParImpl with DirectoryScanner with SourceCodeAnalyzer with AnalyzeHistoryRepository with H2DB
}.getOrElse {
logger.info("using sequence collection mode")
new CodebaseAnalyzerSeqImpl with DirectoryScanner with SourceCodeAnalyzer with AnalyzeHistoryRepository with H2DB
}
val rs = if (file.isFile) {
analyzer.processFile(file.getAbsolutePath).map(format).getOrElse(s"error processing $path")
} else {
BenchmarkUtil.record(s"analyze code under $path") {
analyzer.analyze(path, knownFileTypes, ignoreFolders).map(format).getOrElse("not result found")
}
}
args.find(_.startsWith("-o")).foreach { opt =>
val output = opt.drop(2)
withWriter(output) {
_.write(rs)
}
println(s"report saved into $output")
}
println(rs)
}
}
开发者ID:notyy,项目名称:CodeAnalyzerTutorial,代码行数:42,代码来源:MainApp.scala
示例12: BenchmarkUtil
//设置package包名称以及导入依赖的类
package tutor.utils
import java.text.SimpleDateFormat
import java.util.Date
import com.typesafe.scalalogging.StrictLogging
object BenchmarkUtil extends StrictLogging {
def record[T](actionDesc: String)(action: => T): T = {
val beginTime = new Date
logger.info(s"begin $actionDesc")
val rs = action
logger.info(s"end $actionDesc")
val endTime = new Date
val elapsed = new Date(endTime.getTime - beginTime.getTime)
val sdf = new SimpleDateFormat("mm:ss.SSS")
logger.info(s"$actionDesc total elapsed ${sdf.format(elapsed)}")
rs
}
def recordStart(actionDesc: String):Date = {
logger.info(s"$actionDesc begin")
new Date
}
def recordElapse(actionDesc: String, beginFrom: Date):Unit = {
logger.info(s"$actionDesc ended")
val endTime = new Date
val elapsed = new Date(endTime.getTime - beginFrom.getTime)
val sdf = new SimpleDateFormat("mm:ss.SSS")
logger.info(s"$actionDesc total elapsed ${sdf.format(elapsed)}")
}
}
开发者ID:notyy,项目名称:CodeAnalyzerTutorial,代码行数:33,代码来源:BenchmarkUtil.scala
示例13: CodebaseAnalyzerStreamApp
//设置package包名称以及导入依赖的类
package tutor
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.stream.scaladsl._
import com.typesafe.scalalogging.StrictLogging
import tutor.utils.BenchmarkUtil
import scala.collection.mutable.ArrayBuffer
import scala.concurrent.Future
import scala.util.{Failure, Success}
object CodebaseAnalyzerStreamApp extends App with DirectoryScanner with SourceCodeAnalyzer with ReportFormatter with StrictLogging {
implicit val system = ActorSystem("CodebaseAnalyzer")
implicit val materializer = ActorMaterializer()
implicit val ec = system.dispatcher
val path = args(0)
val beginTime = BenchmarkUtil.recordStart(s"analyze $path with akka stream")
val files = scan(path, PresetFilters.knownFileTypes, PresetFilters.ignoreFolders).iterator
var errorProcessingFiles: ArrayBuffer[Throwable] = ArrayBuffer.empty
val done = Source.fromIterator(() => files).mapAsync(8)(path => Future {
processFile(path)
}).fold(CodebaseInfo.empty) {
(acc, trySourceCodeInfo) =>
trySourceCodeInfo match {
case Success(sourceCodeInfo) => acc + sourceCodeInfo
case Failure(e) => {
errorProcessingFiles += e
acc
}
}
}.runForeach(codebaseInfo => {
println(format(codebaseInfo))
println(s"there are ${errorProcessingFiles.size} files failed to process.")
})
done.onComplete { _ =>
BenchmarkUtil.recordElapse(s"analyze $path with akka stream", beginTime)
system.terminate()
}
}
开发者ID:notyy,项目名称:CodeAnalyzerTutorial,代码行数:44,代码来源:CodebaseAnalyzerStreamApp.scala
示例14: scan
//设置package包名称以及导入依赖的类
package tutor
import java.io.File
import com.typesafe.scalalogging.StrictLogging
import tutor.utils.FileUtil
import tutor.utils.FileUtil.Path
trait DirectoryScanner extends StrictLogging {
def scan(path: Path, knownFileTypes: Set[String], ignoreFolders: Set[String]): Seq[Path] = {
scan(path)(Vector[Path](), ignoreFolders) {
(acc, f) =>
val filePath = f.getAbsolutePath
if (f.isFile && shouldAccept(f.getPath, knownFileTypes)) {
acc :+ filePath
} else acc
}
}
def scan[T](path: Path)(initValue: T, ignoreFolders: Set[String])(processFile: (T, File) => T): T = {
val files = new File(path).listFiles()
if (files == null) {
logger.warn(s"$path is not a legal directory")
initValue
} else {
files.foldLeft(initValue) { (acc, file) =>
val filePath = file.getAbsolutePath
if (file.isFile) {
processFile(acc, file)
} else if (file.isDirectory && (!ignoreFolders.contains(FileUtil.extractLocalPath(file.getPath)))) {
scan(filePath)(acc, ignoreFolders)(processFile)
} else {
acc
}
}
}
}
def foreachFile(path: Path, knownFileTypes: Set[String], ignoreFolders: Set[String])(processFile: File => Unit): Unit = {
scan(path)((), ignoreFolders) {
(acc, f) =>
val filePath = f.getAbsolutePath
if (f.isFile && shouldAccept(f.getPath, knownFileTypes)) {
processFile(f)
} else ()
}
}
private def shouldAccept(path: Path, knownFileTypes: Set[String]): Boolean = {
knownFileTypes.contains(FileUtil.extractExtFileName(path))
}
}
开发者ID:notyy,项目名称:CodeAnalyzerTutorial,代码行数:54,代码来源:DirectoryScanner.scala
示例15: IndexUCHandler
//设置package包名称以及导入依赖的类
package scaps.eclipse.ui.handlers
import org.eclipse.jface.dialogs.MessageDialog
import org.eclipse.jface.wizard.WizardDialog
import org.eclipse.ui.IWorkbenchWindow
import org.eclipse.ui.IWorkingSet
import org.eclipse.ui.PlatformUI
import com.typesafe.scalalogging.StrictLogging
import scaps.eclipse.ScapsPlugin
import scaps.eclipse.core.services.ScapsIndexService
import scaps.eclipse.core.services.ScapsService
import scaps.eclipse.core.services.ScapsSettingsService
object IndexUCHandler {
def apply(): IndexUCHandler = new IndexUCHandler(ScapsService.createIndexService)
}
class IndexUCHandler(scapsIndexService: ScapsIndexService) extends StrictLogging {
lazy val workingSetManager = PlatformUI.getWorkbench.getWorkingSetManager
def runIndexer(window: IWorkbenchWindow): Unit = {
if (ScapsSettingsService.isIndexerRunning) {
MessageDialog.openInformation(window.getShell(),
"Scaps Indexer",
"The Scaps Indexer is already running, please wait until it's done.");
} else {
val scapsWorkingSet = Option(workingSetManager.getWorkingSet(ScapsPlugin.WORKING_SET_NAME))
if (scapsWorkingSet.isEmpty) {
configureIndexer(window)
} else {
scapsIndexService(scapsWorkingSet.get)
}
}
}
def configureIndexer(window: IWorkbenchWindow): IWorkingSet = {
val scapsWorkingSet = Option(workingSetManager.getWorkingSet(ScapsPlugin.WORKING_SET_NAME)).getOrElse {
val newScapsWorkingSet = workingSetManager.createWorkingSet(ScapsPlugin.WORKING_SET_NAME, Array())
newScapsWorkingSet.setId(ScapsPlugin.WORKING_SET_PAGE)
workingSetManager.addWorkingSet(newScapsWorkingSet)
newScapsWorkingSet
}
val workingSetWizard = workingSetManager.createWorkingSetEditWizard(scapsWorkingSet)
val dialog = new WizardDialog(window.getShell, workingSetWizard)
dialog.create()
dialog.open()
scapsWorkingSet
}
}
开发者ID:scala-search,项目名称:scala-ide-scaps,代码行数:54,代码来源:IndexUCHandler.scala
示例16: PriceUpdateMessage
//设置package包名称以及导入依赖的类
package rl.position.model
import java.time.LocalDateTime
import com.typesafe.scalalogging.StrictLogging
import rl.time.LocalDateTimeCompanion
final case class PriceUpdateMessage(
messageType: MessageType,
time: LocalDateTime,
symbol: StockSymbol,
currentPrice: Money
)
object PriceUpdateMessage extends StrictLogging {
def unapply(in: String): Option[PriceUpdateMessage] =
in.split(' ').toList match {
case messageType :: LocalDateTimeCompanion(dateTime) :: StockSymbol(symbol) :: Money(currentPrice) :: Nil =>
Some(PriceUpdateMessage(messageType, dateTime, symbol, currentPrice))
case unrecognized =>
// If we find an unrecognized patter, log it and continue.
logger.error("Unrecognized Price Update message: {}", in)
None
}
}
开发者ID:rmleon,项目名称:sample.scala.apache_flink.1,代码行数:27,代码来源:PriceUpdateMessage.scala
示例17: AuthTokenStore
//设置package包名称以及导入依赖的类
package authentication
import authentication.entities.{AuthToken, BearerToken}
import com.typesafe.scalalogging.StrictLogging
object AuthTokenStore extends StrictLogging {
private var authToken: Option[AuthToken] = None
def updateToken(token: AuthToken): Unit = token match {
case BearerToken(bearer) if bearer.nonEmpty => authToken = Some(token)
case _ => throw new RuntimeException("Received Authentication Token is empty!")
}
def getBearerToken: String = authToken match {
case Some(BearerToken(bearer)) => bearer
case _ => throw new RuntimeException("Bearer Token is empty!")
}
def clear(): Unit = authToken = None
}
开发者ID:lymr,项目名称:fun-chat,代码行数:22,代码来源:AuthTokenStore.scala
示例18: ClientCommandsLoop
//设置package包名称以及导入依赖的类
package commands.runner
import akka.actor.ActorRef
import com.typesafe.scalalogging.StrictLogging
import commands.ClientCommands._
import commands.entities._
import utils.{HelpPrinter, UserInformer}
import scala.io.StdIn.readLine
import scala.util.Try
class ClientCommandsLoop(executor: ActorRef, exitCallback: (Int) => Unit) extends StrictLogging with UserInformer {
def start(): Unit = {
informUserCallback(
"Hey, welcome to fun-chat! \n" +
"Type 'help' to show demo client commands.")
Try {
do {
val input: String = readLine()
input match {
case cmd if cmd.startsWith(HELP) => HelpPrinter.print()
case cmd if cmd.startsWith(SIGN_IN) => executor ! SignInCommand(cmd)
case cmd if cmd.startsWith(SIGN_UP) => executor ! SignUpCommand(cmd)
case cmd if cmd.startsWith(SIGN_OUT) => executor ! SignOutCommand(cmd)
case cmd if cmd.startsWith(UPDATE_CREDENTIALS) => executor ! UpdateCredentialsCommand(cmd)
case cmd if cmd.startsWith(ONLINE_USERS) => executor ! ListOnlineUsersCommand(cmd)
case cmd if cmd.startsWith(USER_INFO) => executor ! GetUserInfoCommand(cmd)
case cmd if cmd.startsWith(SEND_MESSAGE) => executor ! SendMessageCommand(cmd)
case cmd if cmd.startsWith(EXIT) => exitCallback(0)
case other => informUserCallback(s"Unsupported command ! $other")
}
} while (true)
}.recover {
case ex: Exception =>
informUserCallback("Unexpected error occurred!")
logger.error("Unexpected error occurred!", ex)
}
}
}
开发者ID:lymr,项目名称:fun-chat,代码行数:42,代码来源:ClientCommandsLoop.scala
示例19: SecretKeyHashUtils
//设置package包名称以及导入依赖的类
package core.authentication
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.PBEKeySpec
import com.typesafe.scalalogging.StrictLogging
import core.entities.CredentialSet
import utils.StringUtils.{ByteArrayFromBase64StringExtensions, ByteArrayToBase64StringExtensions}
import scala.util.{Failure, Success, Try}
object SecretKeyHashUtils extends StrictLogging {
private val HASH_ALGORITHM: String = "PBKDF2WithHmacSHA512"
private val ITERATIONS: Int = 64
private val SECRET_KEY_LENGTH: Int = 512
def validate(storedCredentials: CredentialSet, secret: String): Boolean = {
val given = calculateHash(secret.toCharArray, storedCredentials.salt.fromBase64()).map(_.asBase64())
given match {
case Some(givenPassword) => storedCredentials.password.equals(givenPassword)
case None => false
}
}
def generate(password: Array[Char], salt: Array[Byte]): Option[CredentialSet] = {
val result = calculateHash(password, salt)
result.map(pw => CredentialSet(pw.asBase64(), salt.asBase64(), HASH_ALGORITHM))
}
private def calculateHash(password: Array[Char],
salt: Array[Byte],
iterations: Int = ITERATIONS,
keyLength: Int = SECRET_KEY_LENGTH): Option[Array[Byte]] = {
val hashCalculation = Try[Array[Byte]] {
val keyFactory = SecretKeyFactory.getInstance(HASH_ALGORITHM)
val keySpec = new PBEKeySpec(password, salt, iterations, keyLength)
val secretKey = keyFactory.generateSecret(keySpec)
secretKey.getEncoded()
}
hashCalculation match {
case Success(value) => Some(value)
case Failure(err) => logger.error("Operation failed!", err); None
}
}
}
开发者ID:lymr,项目名称:fun-chat,代码行数:50,代码来源:SecretKeyHashUtils.scala
示例20: MessageConstants
//设置package包名称以及导入依赖的类
package messages.parser
import com.typesafe.scalalogging.StrictLogging
import messages.parser.MessageConstants._
import messages.parser.error._
import utils.StringUtils._
import scala.util.Try
import scala.util.parsing.combinator.{JavaTokenParsers, PackratParsers}
object MessageConstants {
val SendOperator = "send"
val MessageOperator = "message"
val AttachmentOperator = "attachment"
val SubjectOperator = "to"
val CommaOperator = ","
val SemicolonOperator = ";"
}
class MessageParser extends JavaTokenParsers with PackratParsers with StrictLogging {
private val delimiterOperator: PackratParser[String] = literal(CommaOperator) | literal(SemicolonOperator)
private val subjectOperator: PackratParser[String] = literal(SubjectOperator)
private val contentOperator: PackratParser[String] = literal(MessageOperator) | literal(AttachmentOperator)
private val sendOperator: PackratParser[String] = literal(SendOperator)
private val entity: PackratParser[Entity] = stringLiteral ^^ { e => Entity(e.stripMargins("\"")) }
private val contentEntity: PackratParser[Content] = (contentOperator ~ entity) ^^ {
case op ~ en => Content(en, op)
}
private val contentEntities: PackratParser[Seq[Content]] = repsep(contentEntity, delimiterOperator)
private val subjectEntities: PackratParser[Seq[Entity]] = repsep(entity, delimiterOperator)
private val toEntity: PackratParser[To] = (subjectOperator ~> subjectEntities) ^^ { subjects => To(subjects) }
private val sendOperation: PackratParser[Operation] = (sendOperator ~> toEntity ~ contentEntities) ^^ {
case subjects ~ content => Send(content, subjects)
}
def parse(text: String): Try[Operation] = Try {
val parsedResult = parseAll(sendOperation, text)
parsedResult match {
case Success(r, _) => r
case Failure(cause, _) =>
logger.error("ParsingError: Failed parsing message.", cause)
throw new MessageParsingFailure(s"Failed parsing message, Cause:= $cause")
case Error(cause, _) =>
logger.error("ParsingError: An Error occurred while parsing message", cause)
throw new MessageParsingError(s"An Error occurred while parsing message, Cause:= $cause")
}
}
}
开发者ID:lymr,项目名称:fun-chat,代码行数:58,代码来源:MessageParser.scala
注:本文中的com.typesafe.scalalogging.StrictLogging类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论