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

Scala Logger类代码示例

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

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



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

示例1: SourceTrackingMonitorTest

//设置package包名称以及导入依赖的类
package com.twitter.finagle.builder

import com.twitter.finagle.{Failure, RequestException}
import java.io.IOException
import java.util.logging.{Level, Logger}
import org.junit.runner.RunWith
import org.mockito.Matchers.{any, eq => mockitoEq}
import org.mockito.Mockito.{never, verify}
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.scalatest.mock.MockitoSugar

@RunWith(classOf[JUnitRunner])
class SourceTrackingMonitorTest extends FunSuite with MockitoSugar {
  test("handles unrolling properly") {
    val logger = mock[Logger]
    val monitor = new SourceTrackingMonitor(logger, "qux")
    val e = new Exception
    val f1 = new Failure("foo", Some(e), sources = Map(Failure.Source.Service -> "tweet"))
    val f2 = new Failure("bar", Some(f1))
    val exc = new RequestException(f2)
    exc.serviceName = "user"
    monitor.handle(exc)
    verify(logger).log(
      Level.SEVERE,
      "The 'qux' service " +
        Seq("user", "tweet").mkString(" on behalf of ") +
        " threw an exception",
      exc
    )
  }

  test("logs IOExceptions at Level.FINE") {
    val logger = mock[Logger]
    val ioEx = new IOException("hi")
    val monitor = new SourceTrackingMonitor(logger, "umm")
    monitor.handle(ioEx)
    verify(logger).log(mockitoEq(Level.FINE), any(), mockitoEq(ioEx))
  }

  test("logs Failure.rejected at Level.FINE") {
    val logger = mock[Logger]
    val monitor = new SourceTrackingMonitor(logger, "umm")
    val rejected = Failure.rejected("try again")
    monitor.handle(rejected)

    verify(logger).log(mockitoEq(Level.FINE), any(), mockitoEq(rejected))
    verify(logger, never()).log(mockitoEq(Level.WARNING), any(), mockitoEq(rejected))
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:51,代码来源:SourceTrackingMonitorTest.scala


示例2: RandomAuthService

//设置package包名称以及导入依赖的类
package com.rndmi.messaging.auth

import java.util.logging.Logger

import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.http.scaladsl.unmarshalling.Unmarshaller
import akka.stream.ActorMaterializer
import com.typesafe.config.ConfigFactory
import io.bigfast.messaging.MessagingServer._
import io.bigfast.messaging.auth.AuthService
import io.grpc.Metadata
import spray.json.{JsonParser, ParserInput}


class RandomAuthService extends AuthService {

  import RandomAuthService._

  override def doAuth(metadata: Metadata) = {

    val authorization = metadata.get[String](authorizationKey)
    val session = metadata.get[String](sessionKey)

    logger.info(s"Checking auth for $authorization, $session")

    val httpResponse = http.singleRequest(
      HttpRequest(uri = uri).withHeaders(
        AuthorizationHeader(authorization),
        SessionHeader(session)
      )
    )(materializer)

    httpResponse flatMap { response =>
      val responseEntity = response.entity
      val eventualRandomResponse = unmarshaller.apply(responseEntity)

      logger.info(s"Parsed this response: $eventualRandomResponse")
      eventualRandomResponse
    } map { resp =>
      resp.data.userId.toString
    }
  }
}

object RandomAuthService extends JsonSupport {
  val authorizationKey = Metadata.Key.of("AUTHORIZATION", Metadata.ASCII_STRING_MARSHALLER)
  val sessionKey = Metadata.Key.of("X-AUTHENTICATION", Metadata.ASCII_STRING_MARSHALLER)
  val http = Http()
  val uri = ConfigFactory.load().getString("auth.uri")
  implicit val materializer = ActorMaterializer()

  val logger = Logger.getLogger(this.getClass.getName)

  val unmarshaller: Unmarshaller[HttpEntity, RandomResponse] = {
    Unmarshaller.byteArrayUnmarshaller mapWithCharset { (data, charset) =>
      JsonParser(ParserInput(data)).asJsObject.convertTo[RandomResponse]
    }
  }
} 
开发者ID:kykl,项目名称:mva,代码行数:61,代码来源:RandomAuthService.scala


示例3: AmDecoder

//设置package包名称以及导入依赖的类
package org.argus.amandroid.core.decompile

import java.io.File

import org.argus.jawa.core.util._
import java.util.logging.Logger
import java.util.logging.LogManager

import brut.androlib.ApkDecoder
import brut.androlib.err.CantFindFrameworkResException
import org.argus.amandroid.core.util.ApkFileUtil

object AmDecoder {
  final private val TITLE = "AmDecoder"
  
  def decode(sourcePathUri: FileResourceUri, outputUri: FileResourceUri, forceDelete: Boolean = true, createFolder: Boolean = true, srcFolder: String): FileResourceUri = {
    // make it as quiet mode
    val logger = Logger.getLogger("")
    logger.getHandlers.foreach {
      h =>
        logger.removeHandler(h)
    }
    LogManager.getLogManager.reset()

    val apkFile = FileUtil.toFile(sourcePathUri)
    val outputDir = 
      if(createFolder) FileUtil.toFile(ApkFileUtil.getOutputUri(sourcePathUri, outputUri))
      else FileUtil.toFile(outputUri)
    if(new File(outputDir, srcFolder).exists() && !forceDelete) return FileUtil.toUri(outputDir)
    try {
      val decoder = new ApkDecoder
      decoder.setDecodeSources(0x0000) // DECODE_SOURCES_NONE = 0x0000
      decoder.setApkFile(apkFile)
      decoder.setOutDir(outputDir)
      decoder.setForceDelete(true)
      decoder.decode()
    } catch {
      case ie: InterruptedException => throw ie
      case fe: CantFindFrameworkResException =>
        System.err.println(TITLE + ": Can't find framework resources for package of id: " + fe.getPkgId + ". You must install proper framework files, see apk-tool website for more info.")
      case e: Exception =>
        System.err.println(TITLE + ": " + e.getMessage + ". See apk-tool website for more info.")
    }
    FileUtil.toUri(outputDir)
  }
} 
开发者ID:arguslab,项目名称:Argus-SAF,代码行数:47,代码来源:AmDecoder.scala


示例4: Delorean

//设置package包名称以及导入依赖的类
package delorean

import java.nio.file._
import java.util.logging.{Level, Logger}

import delorean.FileOps.{getCurrentPitstop, getTempPitstopFileLocation}

object Delorean {
    val logger: Logger = Logger.getLogger(this.getClass.getName)

    def main(args: Array[String]): Unit = {
        val start: Long = System.currentTimeMillis()
        configureLogger()
        logger.fine(s"Length of Arguments = ${args.length}")

        // Call to configuration singleton to prepare the configuration map
        Configuration

        if (Files.exists(Paths.get(TIME_MACHINE))) deleteTempFileIfNotNeeded()

        if (args.length == 0) Usage("full")
        else ParseOption(args.toList)
        val end: Long = System.currentTimeMillis()
        val timeTaken = end - start
        println(s"Time taken: $timeTaken ms")
    }

    // Because of file stream not getting closed, the temp file which should have been deleted ideally is not getting deleted.
    // This will make sure we will delete it based on the modified Times
    def deleteTempFileIfNotNeeded(): Unit = {
        val lastPitstop = PITSTOPS_FOLDER + getCurrentPitstop
        val tempFile = getTempPitstopFileLocation

        if (lastPitstop.nonEmpty && tempFile.nonEmpty) {
            val lastPitstopTime = Files.getLastModifiedTime(Paths.get(lastPitstop))
            val tempFileTime = Files.getLastModifiedTime(Paths.get(tempFile))

            lastPitstopTime compareTo tempFileTime match {
                case 1 ? Files.delete(Paths.get(getTempPitstopFileLocation))
                case _ ?
            }
        }
    }

    def configureLogger(): Unit = {
        val rootLogger: Logger = Logger.getLogger("")
        rootLogger.getHandlers.foreach(handler ? handler.setLevel(Level.FINEST))
        System.getenv("DELOREAN_LOG_LEVEL") match {
            case "INFO" ? rootLogger.setLevel(Level.INFO)
            case "FINE" ? rootLogger.setLevel(Level.FINE)
            case _ ? rootLogger.setLevel(Level.SEVERE)
        }
    }
} 
开发者ID:durgaswaroop,项目名称:delorean,代码行数:55,代码来源:Delorean.scala


示例5: Reconstruct

//设置package包名称以及导入依赖的类
package delorean

import java.util.logging.Logger

import delorean.FileOps.{getFileAsMap, getLinesOfFile, writeToFile}

import scala.collection.mutable

/**
  * Class to reconstruct the files based on the hashes.
  */
object Reconstruct {

    /**
      * Reconstructs a file.
      *
      * Will take the file hash we want to reconstruct/reset and will look for that hash in the hashes directory.
      * Once the file is found, it will look at the hashes of individual lines in the file and
      * gets the corresponding lines from the String pool file
      *
      * @param fileHash hash of the file
      */
    def file(fileName: String, fileHash: String): Unit = {
        val logger = Logger.getLogger(this.getClass.getName)
        logger.fine(s"filename: $fileName, fileHash: $fileHash")

        val lineHashesOfFile: List[String] = getLinesOfFile(s"$HASHES_FOLDER$fileHash")
        logger.fine(s"Line hashes: $lineHashesOfFile")

        val stringPoolMap: mutable.LinkedHashMap[String, String] = getFileAsMap(STRING_POOL)

        var reconstructedLines: String = ""
        lineHashesOfFile.foreach(lineHash ? reconstructedLines += stringPoolMap(lineHash) + "\n")
        logger.finest(reconstructedLines)

        // Store it in to the fileName given. Overwrite existing content
        writeToFile(fileName, reconstructedLines)
    }
} 
开发者ID:durgaswaroop,项目名称:delorean,代码行数:40,代码来源:Reconstruct.scala


示例6: Unstage

//设置package包名称以及导入依赖的类
package delorean

import java.io.File
import java.util.logging.Logger

import delorean.FileOps._

import scala.collection.mutable

case class Unstage(files: List[String]) {
    val logger: Logger = Logger.getLogger(this.getClass.getName)
    logger.fine(s"Unstaging list of files $files.")

    // If temp pitstop file is empty it means that no files are currently staged
    val tempPitstopFile: String = getTempPitstopFileLocation
    if (tempPitstopFile.isEmpty) {
        println(
            """|delorean: No files staged
               |
               |For more: delorean --help
               |."""
                .stripMargin)
        System.exit(1)
    }

    // real files exist and imaginary files don't.
    val (realFiles, imaginaryFiles) = files.span(file ? new File(file).exists())
    imaginaryFiles.foreach(file ? println(s"delorean: File $file does not exist"))
    if (realFiles.isEmpty) System.exit(1)

    var filesToUnstage: List[String] = realFiles
    logger.fine(s"Files to unstage: $filesToUnstage")

    val currentStagedFileMap: mutable.LinkedHashMap[String, String] = getFileAsMap(tempPitstopFile)
    var newStagedFileMap: mutable.LinkedHashMap[String, String] = currentStagedFileMap
    logger.fine(s"New files after unstage: $newStagedFileMap")
    filesToUnstage foreach (newStagedFileMap -= _)
    writeMapToFile(newStagedFileMap, tempPitstopFile)
} 
开发者ID:durgaswaroop,项目名称:delorean,代码行数:40,代码来源:Unstage.scala


示例7: Stage

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

import java.io.File
import java.util.logging.Logger

import delorean.FileOps._
import delorean.Hasher

/**
  * For the command 'stage'.
  */
case class Stage(files: List[String]) {
    val logger: Logger = Logger.getLogger(this.getClass.getName)
    logger.fine(s"Staging list of files $files.")

    // realFiles exist and imaginaryFiles don't
    val (realFiles, imaginaryFiles) = files.partition(file ? new File(file).exists())

    imaginaryFiles.foreach(file ? println(s"delorean: File $file does not exist"))

    if (realFiles.isEmpty) System.exit(1)
    logger.fine(s"Real files = $realFiles")

    var filesToStage: List[String] = Nil

    // If a directory is staged, get all the files of that directory
    realFiles.foreach(f ?
        if (new File(f).isDirectory) {
            logger.fine(s"In if for file $f")
            val directoryFiles: List[String] = getFilesRecursively(f)
            filesToStage = filesToStage ++ directoryFiles
        }
        else {
            logger.fine(s"File $f is not a directory. Entered else.")
            filesToStage ::= f
        }
    )

    // In the list only keep the names of files and remove the directories.
    filesToStage = filesToStage.filterNot(file ? new File(file).isDirectory)
    logger.fine(s"After resolving all the files to be staged (after deleting the directories) are: $filesToStage")
    Hasher.computeHashOfStagedFiles(filesToStage)
} 
开发者ID:durgaswaroop,项目名称:delorean,代码行数:44,代码来源:Stage.scala


示例8: GoTo

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

import java.io.File
import java.nio.file.{Files, Paths}
import java.util.logging.Logger

import delorean.FileOps._
import delorean.Hasher.computeShaHash
import delorean._

import scala.collection.mutable

/**
  * Class for the goto command.
  * The input can be a timeline or a pitstop
  */
case class GoTo(timeLine: String) {
    val logger: Logger = Logger.getLogger(this.getClass.getName)

    val (isTimeLine, isPitstop) = if (new File(INDICATORS_FOLDER + timeLine).exists) (true, false) else (false, true)

    /*
        If 'timeline' is in-fact a timeline we get the pitstop that timeline is pointing to or else timeline is a pitstop hash
        which we get by resolving the full pitstop
    */
    val pitstopToGoTo: String = if (isTimeLine) resolveTheHashOfTimeline(timeLine) else resolveTheCorrectPitstop(timeLine)
    logger.fine(s"Pitstop to goto: $pitstopToGoTo")

    val pitstopFileMap: mutable.LinkedHashMap[String, String] = getFileAsMap(PITSTOPS_FOLDER + pitstopToGoTo)
    pitstopFileMap foreach (kv ? {
        val (fileKnown, hashKnown) = kv
        logger.fine(s"(${kv._1}, ${kv._2})")

        // If file exists we check if the current hash is same as the hash we have saved
        if (Files.exists(Paths.get(fileKnown))) {
            val hashComputed = computeShaHash(fileKnown)
            logger.fine(s"computed hash = $hashComputed")

            // If the hashes are not same, we replace the existing file with the file from the pitstop we are 'going to'
            if (hashComputed != hashKnown) Reconstruct.file(fileKnown, hashKnown)
        }
        else {
            logger.fine(s"File $fileKnown does not exist in the current repository")
            Files.createFile(Paths.get(fileKnown))
            Reconstruct.file(fileKnown, hashKnown)
        }
    })

    /*
        Once everything is done, we need to update the 'current' indicator.
        Whether its called with a timeline or a pitstop hash, once we 'goto' that, we will add that in the current file.
     */
    writeToFile(CURRENT_INDICATOR, timeLine)
} 
开发者ID:durgaswaroop,项目名称:delorean,代码行数:55,代码来源:GoTo.scala


示例9: Config

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

import java.util.logging.Logger

import delorean.CONFIG
import delorean.FileOps._

import scala.collection.mutable

/**
  * Class for 'config' command.
  */
case class Config(configArgs: List[String]) {
    val logger: Logger = Logger.getLogger(this.getClass.getName)
    logger.fine(s"Configuration called with args: $configArgs")

    if (configArgs.length == 1) { // Only when the argument is "--list" or "list"
        val configMap = getFileAsMap(CONFIG)
        configMap.foreach(kv ? println(s"${kv._1} = ${kv._2}"))
    } else { // When a key value pair is provided
        writeMapToFile(mutable.LinkedHashMap(configArgs.head ? configArgs(1)), CONFIG, append = true)
    }
} 
开发者ID:durgaswaroop,项目名称:delorean,代码行数:24,代码来源:Config.scala


示例10: CreateTimeLine

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

import java.nio.file.{Files, Paths}
import java.util.logging.Logger

import delorean.FileOps._
import delorean._

/**
  * Class for create-timeline command.
  */
case class CreateTimeLine(newTimeLine: String) {

    val logger: Logger = Logger.getLogger(this.getClass.getName)

    logger.fine(s"New timeline to create: $newTimeLine")

    val newTimeLineFileLocation: String = INDICATORS_FOLDER + newTimeLine

    // First check if that timeline already exists
    if (Files.exists(Paths.get(newTimeLineFileLocation))) {
        println(s"Timeline '$newTimeLine' already exists in the current repository")
        println("Science Fiction 101: You cannot 're-create' an existing timeline")
        System.exit(1)
    }

    // If the timeline doesn't already exist, create a file with the name of the timeline in the Indicators folder
    Files.createFile(Paths.get(newTimeLineFileLocation))

    // Then, copy the current pitstop hash (the contents of the indicator file) to the current timeline file
    val currentPitstop: String = getCurrentPitstop
    writeToFile(newTimeLineFileLocation, currentPitstop)

    // Then, point the 'current' branch pointer to point to the new branch
    writeToFile(CURRENT_INDICATOR, newTimeLine)

    println(s"New timeline $newTimeLine created")
} 
开发者ID:durgaswaroop,项目名称:delorean,代码行数:39,代码来源:CreateTimeLine.scala


示例11: BansDB

//设置package包名称以及导入依赖的类
package us.illyohs.bansdb

import java.nio.file.{Files, Path, Paths}
import java.util.logging.Logger

import com.google.inject.Inject
import org.spongepowered.api.event.game.state.GameStartingServerEvent
import org.spongepowered.api.plugin.Plugin
import us.illyohs.bansdb.util.ConfigUtil
import us.illyohs.bansdb.util.InfoUtil._

@Plugin(
  id = PLUGIN_ID,
  name = PLUGIN_NAME,
  version = PLUGIN_VERSION,
  authors = AUTHORS
)
object BansDB {

  @Inject
  var logger:Logger = null


  def onStart(e:GameStartingServerEvent): Unit = {
    val folder:Path = Paths.get("config/bansdb")
    if (!Files.exists(folder)) Files.createDirectory(folder)
    ConfigUtil.init
  }

} 
开发者ID:DragonTechMC,项目名称:BansDB,代码行数:31,代码来源:BansDB.scala


示例12: ClientUtilServer

//设置package包名称以及导入依赖的类
package com.squarecode.axia

import java.net.InetSocketAddress
import java.util.logging.Logger

import com.twitter.finagle.axia.user.UserService$FinagleClient
import com.twitter.finagle.builder.ClientBuilder
import com.twitter.finagle.thrift.ThriftClientFramedCodec
import org.apache.thrift.protocol.TBinaryProtocol


object ClientUtilServer {
  def server(address: InetSocketAddress) = {

    val serve = ClientBuilder()
      .hosts(address)
      .codec(ThriftClientFramedCodec())
      .hostConnectionLimit(1)
      .retries(3)
      .logger(Logger.getLogger("http"))
      .build()
    new UserService$FinagleClient(serve, new TBinaryProtocol.Factory())
  }
} 
开发者ID:dynastymasra,项目名称:ScalaGolangThirft,代码行数:25,代码来源:ClientUtilServer.scala


示例13: Sender

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

import scalaj.http._
import spray.json._

object Sender {
  import json._
  import entities.Result
  import java.util.logging.Logger

  def uuid = java.util.UUID.randomUUID().toString

  final val _timeout = 10000

  val log = Logger.getLogger(getClass.getName)
  def send(
           p: NotifyBuilder[Level],
           url: String = "https://api.rollbar.com/api/1/item/"
  )(implicit timeout: Int = _timeout) = {
    val u = uuid
    val json = p.payload.toJson.toString
    log.info(s"Send [$u]: $json to $url")
    val result = Http(url)
      .timeout(connTimeoutMs = _timeout, readTimeoutMs = _timeout)
      .postData(json).asString.body.parseJson.convertTo[Result]
    log.info(s"Response [$u] given: $result")
    result
  }
} 
开发者ID:truerss,项目名称:rollbar-scala,代码行数:30,代码来源:Sender.scala


示例14: ServerApplication

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

import com.mildlyskilled.core.{ConsoleAction, Network}
import java.util.logging.Logger

import akka.actor.{ActorSystem, Props}
import com.mildlyskilled.actors.Server
import com.mildlyskilled.protocol.Message._
import com.typesafe.config.ConfigFactory

import scala.tools.jline.console.ConsoleReader

object ServerApplication extends App {
  implicit val logger = Logger.getLogger("Server Logger")
  logger.info(Console.GREEN_B + "Starting server" + Console.RESET)

  val ipSelection = ConsoleAction.promptSelection(Network.addressMap, "Select an IP address", Some("127.0.0.1"))
  val serverName = ConsoleAction.clean(ConsoleAction.promptInput("Name this server"))

  val serverConfiguration = ConfigFactory.parseString(s"""akka.remote.netty.tcp.hostname="$ipSelection" """)
  val defaultConfig = ConfigFactory.load.getConfig("server")
  val completeConfig = serverConfiguration.withFallback(defaultConfig)

  val system = ActorSystem("sIRC", completeConfig)
  val server = system.actorOf(Props[Server], serverName)
  val cReader = new ConsoleReader()

  Iterator.continually(cReader.readLine("> ")).takeWhile(_ != "/exit").foreach {
    case "/start" =>
      server ! Start
    case "/users" =>
      server.tell(RegisteredUsers, server)
    case "/channels" =>
      server.tell(ListChannels, server)
    case "/stop" =>
      server ! Stop
    case "/shutdown" =>
      system.terminate()
    case userCommandMessageRegex("add", c) =>
      server.tell(RegisterChannel(ConsoleAction.clean(c)), server)
    case msg =>
      server ! Info(msg)
  }

  system.terminate()
} 
开发者ID:mildlyskilled,项目名称:sIRC,代码行数:47,代码来源:ServerApplication.scala


示例15: ClientApplication

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


import akka.actor.{ActorSystem, Props}
import com.mildlyskilled.actors.Client
import com.mildlyskilled.core.{ConsoleAction, Network}
import com.mildlyskilled.protocol.Message._
import com.typesafe.config.ConfigFactory

import java.util.logging.Logger
import scala.tools.jline.console.ConsoleReader

object ClientApplication extends App {

  implicit val logger = Logger.getLogger("Client Logger")
  logger.info(Console.GREEN_B + "Starting client" + Console.RESET)
  val username = ConsoleAction.promptInput("Username")
  val serverName = ConsoleAction.promptInput("Server Name")
  val ipSelection = ConsoleAction.promptSelection(Network.addressMap, "Select an IP address", Some("127.0.0.1"))

  val clientConfig = ConfigFactory.parseString(s"""akka.remote.netty.tcp.hostname="$ipSelection" """)
  val defaultConfig = ConfigFactory.load.getConfig("client")
  val completeConfig = clientConfig.withFallback(defaultConfig)

  val system = ActorSystem("sIRC", completeConfig)
  val client = system.actorOf(Props[Client], username)

  val serverconfig = ConfigFactory.load.getConfig("server")
  val serverAddress = ConsoleAction.promptInput(s"Server IP Address or hostname [$ipSelection]", s"$ipSelection")
  val serverPort = serverconfig.getString("akka.remote.netty.tcp.port")
  val serverPath = s"akka.tcp://[email protected]$serverAddress:$serverPort/user/$serverName"
  val server = system.actorSelection(serverPath) // <-- this is where we get the server reference

  server.tell(Login("username", "password"), client)

  val cReader = new ConsoleReader

  Iterator.continually(cReader.readLine("> ")).takeWhile(_ != "/exit").foreach {
    case "/start" =>
      server ! Start
    case "/users" =>
      server.tell(RegisteredUsers, client)
    case "/channels" =>
      server.tell(ListChannels, client)
    case "/leave" =>
      server.tell(Leave, client)
    case msg =>
      server ! Info(msg)
    case userCommandMessageRegex("join", c) =>
      server.tell(JoinChannel(ConsoleAction.clean(c)), client)
  }

  system.terminate()
} 
开发者ID:mildlyskilled,项目名称:sIRC,代码行数:55,代码来源:ClientApplication.scala


示例16: AuthTest

//设置package包名称以及导入依赖的类
package com.mildlyskilled.core

import java.util.logging.Logger

import akka.actor.{ActorSystem, Props}
import com.mildlyskilled.actors.Client
import org.scalatest.{BeforeAndAfterAll, FunSuite}


class AuthTest extends FunSuite with BeforeAndAfterAll {

  val system = ActorSystem("fakesys")
  val logger = Logger.getLogger("testlogger")

  override def afterAll() {
    system.terminate()
    logger.info("System brought down")
  }

  test("testIsAuthenticated") {
    val auth = new Auth
    val testActor = system.actorOf(Props[Client], "tc")
    assert(auth.isAuthenticated(testActor))
  }

  test("testLogin") {
    val auth = new Auth
    assert(auth.login("test", "test"))
  }

} 
开发者ID:mildlyskilled,项目名称:sIRC,代码行数:32,代码来源:AuthTest.scala


示例17: AdminServlet

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

import java.util.logging.Logger
import javax.servlet.http.{HttpServletResponse, HttpServletRequest, HttpServlet}

import com.google.gson.JsonParser
import org.eck.entities.Settings

class AdminServlet extends HttpServlet {
  val logger = Logger.getLogger("AdminServlet")

  override def doGet(req: HttpServletRequest, resp: HttpServletResponse) = {
    if (req.getParameter("json") != null) {
      val json = new JsonParser().parse(req.getParameter("json")).getAsJsonObject
      logger.info("Updating settings data " + json.toString)
      Settings.fromJson(json)
    }

    printForm(resp)
  }

  def printForm(resp: HttpServletResponse) = {
    resp.setContentType("text/html")
    resp.getWriter.append("<form action=\"/admin\">")
    resp.getWriter.append(" <textarea name=\"json\" rows=\"30\">")
    resp.getWriter.append(Settings.asJson.toString)
    resp.getWriter.append(" </textarea>")
    resp.getWriter.append(" <br/>")
    resp.getWriter.append(" <button type=\"submit\">Save</button>")
  }
} 
开发者ID:erickzanardo,项目名称:spammer,代码行数:32,代码来源:AdminServlet.scala


示例18: CountryClientTest

//设置package包名称以及导入依赖的类
package id.dynastymasra.sanskerta.area

import java.net.InetSocketAddress

import com.twitter.finagle.builder.ClientBuilder
import com.twitter.finagle.thrift.ThriftClientFramedCodec
import id.co.squarecode.common.contract.area.CountryService$FinagleClient
import org.apache.thrift.protocol.TCompactProtocol
import java.util.logging.Logger


object CountryClientTest {
  def serverCountry(address: InetSocketAddress) = {
    val protocol = new TCompactProtocol.Factory()
    val serve = ClientBuilder()
      .failFast(false)
      .keepAlive(true)
      .hosts(address)
      .codec(ThriftClientFramedCodec().protocolFactory(protocol))
      .hostConnectionCoresize(1)
      .retries(3)
      .logger(Logger.getLogger("Country Test"))
      .build()
    new CountryService$FinagleClient(serve, protocol)
  }
} 
开发者ID:dynastymasra,项目名称:SanskertaService,代码行数:27,代码来源:CountryClientTest.scala


示例19: AreaClientTest

//设置package包名称以及导入依赖的类
package id.dynastymasra.sanskerta.area

import java.net.InetSocketAddress
import java.util.logging.Logger

import com.twitter.finagle.builder.ClientBuilder
import com.twitter.finagle.thrift.ThriftClientFramedCodec
import id.co.squarecode.common.contract.area.AreaService$FinagleClient
import org.apache.thrift.protocol.TCompactProtocol


object AreaClientTest {
  def server(address: InetSocketAddress) = {
    val protocol = new TCompactProtocol.Factory()
    val serve = ClientBuilder()
      .failFast(false)
      .keepAlive(true)
      .hosts(address)
      .codec(ThriftClientFramedCodec().protocolFactory(protocol))
      .hostConnectionLimit(1)
      .retries(3)
      .logger(Logger.getLogger("Area Test"))
      .build()
    new AreaService$FinagleClient(serve, protocol)
  }
} 
开发者ID:dynastymasra,项目名称:SanskertaService,代码行数:27,代码来源:AreaClientTest.scala


示例20: configureClient

//设置package包名称以及导入依赖的类
package com.twitter.finagle.mysql.integration

import com.twitter.finagle.Mysql
import com.twitter.finagle.mysql._
import com.twitter.util.NonFatal
import java.io.{File, FileInputStream}
import java.net.{ServerSocket, BindException}
import java.util.logging.{Level, Logger}
import java.util.Properties

trait IntegrationClient {
  private val logger = Logger.getLogger("integration-client")

  // Check if default mysql port is available.
  val isPortAvailable = try {
    val socket = new ServerSocket(3306)
    socket.close()
    true
  } catch {
    case e: BindException => false
  }

  val propFile = new File(System.getProperty("user.home") +
    "/.finagle-mysql/integration-test.properties")

  val p = new Properties
  val propFileExists = try {
    val fis = new FileInputStream(propFile)
    p.load(fis)
    fis.close()
    true
  } catch {
    case NonFatal(e) =>
      logger.log(Level.WARNING, "Error loading integration.properties, skipping integration test")
      false
  }

  // It's likely that we can run this test
  // if a mysql instance is running and a valid
  // properties file is found which contains
  // mysql credentials.
  val isAvailable = !isPortAvailable && propFileExists

  protected def configureClient(username: String, password: String, db: String) = Mysql.client
    .withCredentials(username, password)
    .withDatabase(db)

  val client: Option[Client with Cursors] = if (isAvailable) {
    logger.log(Level.INFO, "Attempting to connect to mysqld @ localhost:3306")
    val username = p.getProperty("username", "<user>")
    val password = p.getProperty("password", null)
    val db = p.getProperty("db", "test")
    Some(configureClient(username, password, db)
      .newRichClient("localhost:3306"))
  } else {
    None
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:59,代码来源:IntegrationClient.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala ArrayBasedMapData类代码示例发布时间:2022-05-23
下一篇:
Scala Await类代码示例发布时间: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