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

Scala Level类代码示例

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

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



在下文中一共展示了Level类的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: 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


示例3: LastFmConnection

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

import java.util.logging.Level

import de.umass.lastfm.Caller
import de.umass.lastfm.Chart

object LastFmConnection {
    val apiRootUrlHttps:String = "https://ws.audioscrobbler.com/2.0/"
    val apiRootUrlHttp:String = "http://ws.audioscrobbler.com/2.0/"
    
    private def check(): Boolean = {
        !Chart.getTopTracks(Conf.key).isEmpty
    }
    
    def init(): Unit = {
        val inst = Caller.getInstance()
        inst.setApiRootUrl(apiRootUrlHttps)
        inst.setUserAgent(Conf.userAgent)
        inst.getLogger.setLevel(
            if (Conf.dbgFlag) Level.ALL
            else Level.OFF)

        if (!check()) {
            Caller.getInstance().setApiRootUrl(apiRootUrlHttp)
            if (!check()) {
                throw new Error("No response from ws.audioscrobbler.com/2.0")
            }
        }
    }
} 
开发者ID:sentenzo,项目名称:sub-scrobbler,代码行数:32,代码来源:LastFmConnection.scala


示例4: 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


示例5: close

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

import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.atomic.AtomicInteger
import java.util.logging.{Logger, Level}

trait Chan[-T] {
  def !(elem: T)
  def close()
}


trait Proc[-T] extends Chan[T] {
  private[this] val q = new ConcurrentLinkedQueue[T]
  private[this] val nq = new AtomicInteger(0)
  @volatile private[this] var closed = false

  def close() { closed = true }

  def !(elem: T) {
    q.offer(elem)
    if (nq.getAndIncrement() == 0)
      do {
        val elem = q.poll()
        // Swallow exceptions as these would cause
        // unbounded queue growth.
        if (!closed) {
          try receiver(elem) catch {
             case exc: Throwable =>
               Logger.getLogger("").log(Level.WARNING, "Exception thrown in proc", exc)
           }
        }
      } while (nq.decrementAndGet() > 0)
  }

  def receive: T => Unit
  private[this] val receiver = receive
}

object Proc {
  def apply[T](iteratee: T => Unit): Proc[T] = new Proc[T] {
    def receive = iteratee
  }

  val nil: Proc[Any] = new Proc[Any] { def receive = Function.const(()) }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:47,代码来源:Chan.scala


示例6: SourceTrackingMonitor

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

import com.twitter.finagle.{Failure, SourcedException}
import com.twitter.logging.HasLogLevel
import com.twitter.util.Monitor
import java.io.IOException
import java.util.logging.{Level, Logger}


class SourceTrackingMonitor(logger: Logger, which: String) extends Monitor {
  def handle(exc: Throwable): Boolean = {
    // much like ChannelStatsHandler.exceptionCaught,
    // we don't want these noisy IOExceptions leaking into the logs.
    val level = exc match {
      case _: IOException => Level.FINE
      case f: HasLogLevel => f.logLevel
      case _ => Level.SEVERE
    }
    val unrolled = unrollCauses(exc)
    val msg = if (unrolled.isEmpty)
      s"The '$which' service threw an exception"
    else
      s"The '$which' service ${unrolled.mkString(" on behalf of ")} threw an exception"

    logger.log(level, msg, exc)
    false
  }

  private[this] def unrollCauses(exc: Throwable, res: Seq[String] = Nil): Seq[String] = exc match {
    case null => res.reverse
    case se: SourcedException => unrollCauses(se.getCause, se.serviceName +: res)
    case fail: Failure => fail.getSource(Failure.Source.Service) match {
      case Some(name) => unrollCauses(fail.getCause, name.toString +: res)
      case _ => unrollCauses(fail.getCause, res)
    }
    case _ => unrollCauses(exc.getCause, res)
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:39,代码来源:SourceTrackingMonitor.scala


示例7: GarbageCollector

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

import java.util.logging.Level

private[lease] object GarbageCollector {
  private val log = java.util.logging.Logger.getLogger("GarbageCollector")

  val forceNewGc: () => Unit = try {
    // This is a method present in Twitter's JVMs to force
    // a minor collection.
    val meth = Class.forName("com.twitter.hotspot.System").getMethod("minorGc")
    log.log(Level.INFO, "Found com.twitter.hotspot.System.minorGc")
    () => meth.invoke(null)
  } catch {
    case exc: ClassNotFoundException =>
      log.log(
        Level.INFO,
        "Failed to resolve com.twitter.hotspot.System; falling "+
          "back to full GC",
        exc)
      () => System.gc()
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:24,代码来源:GarbageCollector.scala


示例8: PayloadSizeHandler

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

import com.twitter.finagle.http.Fields
import com.twitter.util.StorageUnit
import io.netty.buffer.ByteBufHolder
import io.netty.channel.{ChannelFutureListener, ChannelHandlerContext, ChannelInboundHandlerAdapter}
import io.netty.handler.codec.http._
import java.util.logging.{Level, Logger}

private object PayloadSizeHandler {
  def mk413(v: HttpVersion): FullHttpResponse = {
    val resp = new DefaultFullHttpResponse(v, HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE)
    resp.headers().set(Fields.Connection, "close")
    resp.headers().set(Fields.ContentLength, "0")
    resp
  }
}


private[http] class PayloadSizeHandler(limit: StorageUnit, log: Option[Logger])
  extends ChannelInboundHandlerAdapter {

  def this(limit: StorageUnit) = this(limit, None)

  private[this] val limitBytes = limit.inBytes

  // we don't worry about thread-safety because netty guarantees that reads are
  // serialized and on the same-thread.
  private[this] var discarding = false

  import PayloadSizeHandler.mk413

  override def channelRead(ctx: ChannelHandlerContext, msg: Any): Unit = msg match {
    case http: HttpMessage if HttpUtil.getContentLength(http, -1) > limitBytes =>
      discarding = true
      if (http.isInstanceOf[ByteBufHolder]) {
        http.asInstanceOf[ByteBufHolder].release()
      }
      ctx.writeAndFlush(mk413(http.protocolVersion))
        .addListener(ChannelFutureListener.CLOSE)

      log match {
        case Some(l) if l.isLoggable(Level.FINE) =>
          l.log(Level.FINE, s"rejected an oversize payload (${HttpUtil.getContentLength(http)} bytes) from ${ctx.channel.remoteAddress}")
        case _ =>
      }

    // the session is doomed so we reject chunks
    case chunk: HttpContent if discarding =>
      chunk.release()

    case _ =>
      super.channelRead(ctx, msg)
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:56,代码来源:PayloadSizeHandler.scala


示例9: ValidateThriftService

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

import com.twitter.finagle.{Status, ServiceProxy, Service, WriteException, ServiceException}
import java.util.logging.{Logger, Level}
import org.apache.thrift.TApplicationException
import org.apache.thrift.protocol.{TProtocolFactory, TMessageType}
import org.apache.thrift.transport.TMemoryInputTransport
import com.twitter.util.Future


class ValidateThriftService(
  self: Service[ThriftClientRequest, Array[Byte]],
  protocolFactory: TProtocolFactory
) extends ServiceProxy[ThriftClientRequest, Array[Byte]](self)
{
  @volatile private[this] var isValid = true

  override def apply(req: ThriftClientRequest) =
    if (!isValid) Future.exception(WriteException(InvalidThriftConnectionException()))
    else self(req) onSuccess { bytes =>
      if (!req.oneway && !isResponseValid(bytes)) {
        isValid = false
        Logger.getLogger("finagle-thrift").log(Level.WARNING,
          "Thrift connection was invalidated!")
      }
    }

  override def status = 
    if (!isValid) Status.Closed 
    else self.status
  
  private def isResponseValid(bytes: Array[Byte]) = try {
    val memoryTransport = new TMemoryInputTransport(bytes)
    val iprot = protocolFactory.getProtocol(memoryTransport)
    val reply = iprot.readMessageBegin()
    reply.`type` != TMessageType.EXCEPTION || {
      val exc = TApplicationException.read(iprot)
      iprot.readMessageEnd()
      exc.getType == TApplicationException.INTERNAL_ERROR ||
        exc.getType == TApplicationException.UNKNOWN_METHOD
    }
  } catch {
    case exc: Throwable =>
      Logger.getLogger("finagle-thrift").log(Level.WARNING,
        "Exception while validating connection", exc)
      false
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:49,代码来源:ValidateThriftService.scala


示例10: MainRandScheds

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

import java.util.logging.Logger
import polyite.schedule.DomainCoeffInfo
import polyite.config.ConfigRand
import polyite.schedule.Schedule
import polyite.schedule.ScheduleUtils
import java.util.logging.Level
import polyite.schedule.Dependence
import polyite.config.Config
import polyite.config.MinimalConfig.NumGeneratorsLimit
import polyite.config.MinimalConfig.NumGeneratorsLimit

object MainRandScheds {

  val myLogger : Logger = Logger.getLogger("")

  def main(args : Array[String]) : Unit = {

    def buildRandSchedGen(s : ScopInfo) : ((DomainCoeffInfo, Set[Dependence],
        Int, Set[Schedule], NumGeneratorsLimit, NumGeneratorsLimit, ConfigRand) => Set[Schedule]) = {
      ScheduleUtils.genRandSchedules
    }

    try {
    MainUtil.runRandExpl[ConfigRand](args, ConfigRand.loadAndValidateConfig,
      buildRandSchedGen)
    } catch {
      case t : Throwable => {
        val logger : Logger = Logger.getLogger("")
        logger.log(Level.SEVERE, "Unhandled throwable", t)
      }
    }
  }
} 
开发者ID:stganser,项目名称:polyite,代码行数:36,代码来源:MainRandScheds.scala


示例11: Main

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

import polyite.evolution.SelectionStrategies
import java.util.logging.Logger
import java.util.logging.Level

object Main {
  def main(args : Array[String]) {
    try {
    MainUtil.runGA(args, SelectionStrategies.takeKBestSchedules)
    } catch {
      case t : Throwable => {
        val logger : Logger = Logger.getLogger("")
        logger.log(Level.SEVERE, "Unhandled throwable", t)
      }
    }
  }
} 
开发者ID:stganser,项目名称:polyite,代码行数:19,代码来源:Main.scala


示例12: MainRandSchedsLeTSeE

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

import java.util.logging.Logger
import polyite.schedule.DomainCoeffInfo
import polyite.config.ConfigRand
import polyite.schedule.Schedule
import polyite.schedule.ScheduleUtils
import polyite.schedule.CoeffSpaceLeTSeEStyle
import polyite.config.ConfigRandLeTSeEStyle
import java.util.logging.Level
import polyite.schedule.Dependence
import polyite.config.MinimalConfig.NumGeneratorsLimit

object MainRandSchedsLeTSeE {

  val myLogger : Logger = Logger.getLogger("")

  def main(args : Array[String]) : Unit = {

    def buildRandSchedGen(s : ScopInfo) : ((DomainCoeffInfo, Set[Dependence], Int, Set[Schedule], NumGeneratorsLimit, NumGeneratorsLimit, ConfigRandLeTSeEStyle) => Set[Schedule]) = {
      return {
        (domInfo : DomainCoeffInfo, deps : Set[Dependence], numScheds : Int, basis : Set[Schedule], maxNumRays : NumGeneratorsLimit, maxNumLines : NumGeneratorsLimit, conf : ConfigRandLeTSeEStyle) =>
          {
            CoeffSpaceLeTSeEStyle.genRandSchedules(s)(domInfo, deps, numScheds, basis, conf) match {
              case None => {
                myLogger.warning("The search space is empty.")
                throw new RuntimeException()
              }
              case Some(scheds) => scheds
            }
          }
      }
    }

    try {
      MainUtil.runRandExpl[ConfigRandLeTSeEStyle](args,
        ConfigRandLeTSeEStyle.loadAndValidateConfig, buildRandSchedGen)
    } catch {
      case t : Throwable => {
        val logger : Logger = Logger.getLogger("")
        logger.log(Level.SEVERE, "Unhandled throwable", t)
      }
    }
  }
} 
开发者ID:stganser,项目名称:polyite,代码行数:46,代码来源:MainRandSchedsLeTSeE.scala


示例13: SingleGeoCoordinateParser

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

import java.util.logging.{Level, Logger}

import dbpedia.config.GeoCoordinateParserConfig
import dbpedia.dataparsers.coordinate.{Latitude, Longitude, SingleGeoCoordinate}
import dbpedia.dataparsers.util.Language
import dbpedia.dataparsers.util.wikiparser.Node

import scala.language.reflectiveCalls
import scala.util.control.ControlThrowable


class SingleGeoCoordinateParser(context : { def language : Language }) extends DataParser
{
    private val logger = Logger.getLogger(classOf[GeoCoordinateParser].getName)
    private val language = context.language.wikiCode
    
    private val lonHemLetterMap = GeoCoordinateParserConfig.longitudeLetterMap.getOrElse(language,GeoCoordinateParserConfig.longitudeLetterMap("en"))
    private val latHemLetterMap = GeoCoordinateParserConfig.latitudeLetterMap.getOrElse(language,GeoCoordinateParserConfig.latitudeLetterMap("en"))
    
	private val lonHemRegex = lonHemLetterMap.keySet.mkString("|")
	private val LongitudeRegex = ("""([0-9]{1,2})/([0-9]{1,2})/([0-9]{0,2}(?:.[0-9]{1,2})?)[/]?[\s]?("""+ lonHemRegex +""")""").r
	
	private val latHemRegex = latHemLetterMap.keySet.mkString("|")
	private val LatitudeRegex = ("""([0-9]{1,2})/([0-9]{1,2})/([0-9]{0,2}(?:.[0-9]{1,2})?)[/]?[\s]?("""+ latHemRegex +""")""").r
	

    override def parse(node : Node) : Option[SingleGeoCoordinate] =
    {
        try
        {
            for( text <- StringParser.parse(node);
                 coordinate <- parseSingleCoordinate(text) )
            {
                return Some(coordinate)
            }
        }
        catch
        {
            case ex : ControlThrowable => throw ex
            case ex : Exception => logger.log(Level.FINE, "Could not extract coordinates", ex)
        }

        None
    }

    
    def parseSingleCoordinate(coordStr : String) : Option[SingleGeoCoordinate] = 
    {
    	coordStr match {
    	  case LatitudeRegex(latDeg, latMin, latSec, latHem) => Some(new Latitude(latDeg.toDouble, latMin.toDouble, ("0"+latSec).toDouble, latHemLetterMap.getOrElse(latHem,"N")))
    	  case LongitudeRegex(lonDeg, lonMin, lonSec, lonHem) => Some(new Longitude(lonDeg.toDouble, lonMin.toDouble, ("0"+lonSec).toDouble, lonHemLetterMap.getOrElse(lonHem,"E")))
    	  case _ => None
    	}
    }
        
} 
开发者ID:FnOio,项目名称:dbpedia-parsing-functions-scala,代码行数:59,代码来源:SingleGeoCoordinateParser.scala


示例14: update

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

import java.util.concurrent.{Executors, TimeUnit}
import java.util.logging.{Level, Logger}

//TODO write tests and move to its own file
trait Listener[T]{

  
  @volatile private var lastMessage: Option[T] = None

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

  protected def update(value: T) {
    if(scheduled) {
      lastMessage = Some(value)
    } else {
      val time = System.currentTimeMillis() - lastUpdateTime
      if (time > maxFrequency) {
        onUpdate(value)
        lastUpdateTime = System.currentTimeMillis()
      } else {
        scheduled = true
        lastMessage = Some(value)
        delayedUpdate(maxFrequency)
      }
    }
  }

  protected def onUpdate(value: T)

  private def delayedUpdate(delay: Long) {
    Listener.executor.schedule(new Runnable {
      def run() {
        try {
          scheduled = false
          lastUpdateTime = System.currentTimeMillis()
          onUpdate(lastMessage.get)
        } catch {
          case ex: Exception => logger.log(Level.WARNING, "Error on update", ex)
        }
      }
    }, delay, TimeUnit.MILLISECONDS)
  }
}

object Listener {
  private val executor = Executors.newScheduledThreadPool(1)
} 
开发者ID:petrovskip,项目名称:silk.2.6-GenLinkSA,代码行数:50,代码来源:Listener.scala


示例15: TaskStatusListener

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

import de.fuberlin.wiwiss.silk.runtime.task.ValueTask
import java.util.logging.Level
import de.fuberlin.wiwiss.silk.runtime.task.HasStatus
import de.fuberlin.wiwiss.silk.runtime.task.TaskStatus

abstract class TaskStatusListener(task: HasStatus) extends Listener[TaskStatus] {
  task.onUpdate(Listener)

  private object Listener extends (TaskStatus => Unit) {
    def apply(status: TaskStatus) {
      update(status)
    }
  }
}

abstract class TaskDataListener[T](userData: TaskData[T]) extends Listener[T] {
  userData.onUpdate(Listener)

  private object Listener extends (T => Unit) {
    def apply(value: T) {
      update(value)
    }
  }
}


abstract class CurrentTaskStatusListener[TaskType <: HasStatus](taskHolder: TaskData[TaskType]) extends Listener[TaskStatus] with HasStatus {

  //Deactivate logging
  statusLogLevel = Level.FINEST
  progressLogLevel = Level.FINEST

  //Listen to changes of the current task
  taskHolder.onUpdate(Listener)

  //Set current task
  @volatile protected var task = taskHolder()

  //Listen to changes of the status of the current task.
  task.onUpdate(StatusListener)
  updateStatus(task.status)

  private object Listener extends (TaskType => Unit) {
    def apply(newTask: TaskType) {
      task = newTask
      task.onUpdate(StatusListener)
    }
  }

  private object StatusListener extends (TaskStatus => Unit) {
    def apply(status: TaskStatus) {
      update(status)
      updateStatus(status)
    }
  }
} 
开发者ID:petrovskip,项目名称:silk.2.6-GenLinkSA,代码行数:59,代码来源:Listeners.scala


示例16: LoadingThread

//设置package包名称以及导入依赖的类
package de.fuberlin.wiwiss.silk.workspace.modules

import de.fuberlin.wiwiss.silk.workspace.Project
import de.fuberlin.wiwiss.silk.runtime.task.{TaskFinished, TaskStarted, HasStatus}
import java.util.logging.Level
import xml.{Node, NodeSeq}
import de.fuberlin.wiwiss.silk.workspace.modules.linking.LinkingTask
import de.fuberlin.wiwiss.silk.workspace.modules.source.SourceTask
import de.fuberlin.wiwiss.silk.workspace.modules.transform.TransformTask


  private class LoadingThread(project: Project, task: TaskType) extends Thread {
    override def run() {
      val startTime = System.currentTimeMillis
      try {
        update(project, task)
        updateStatus(TaskFinished("Loading cache", true, System.currentTimeMillis - startTime, None))
        // Commit to the project
        //TODO  Make project modules (e.g. the linking module) register a callback
        if(!isInterrupted) {
          task match {
            case transformTask: TransformTask => project.transformModule.update(transformTask)
            case linkingTask: LinkingTask => project.linkingModule.update(linkingTask)
            case sourceTask: SourceTask => project.sourceModule.update(sourceTask)
          }
        }
      } catch {
        case ex: InterruptedException =>
          logger.log(Level.WARNING, "Loading cache stopped")
          updateStatus(TaskFinished("Loading stopped", false, System.currentTimeMillis - startTime, None))
        case ex: Exception =>
          logger.log(Level.WARNING, "Loading cache failed", ex)
          updateStatus(TaskFinished("Loading cache", false, System.currentTimeMillis - startTime, Some(ex)))
      }
      loadingThread = None
    }
  }
} 
开发者ID:petrovskip,项目名称:silk.2.6-GenLinkSA,代码行数:39,代码来源:Cache.scala


示例17: QSLogger

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

import java.util.logging.{Logger, Level}

private[sdk] object QSLogger {
  private val logger = Logger.getLogger(this.getClass.getName)
  private var level = "warn"
  logger.setLevel(Level.WARNING)

  def getLevel: String =  this.level

  def setLevel(level: String): Unit = {
    level match {
      case "debug" => logger.setLevel(Level.ALL)
      case "info" => logger.setLevel(Level.INFO)
      case "warn" => logger.setLevel(Level.WARNING)
      case "error" => logger.setLevel(Level.SEVERE)
      case "fatal" => logger.setLevel(Level.SEVERE)
      case _ => fatal("Log level invalid: " + level)
    }
    this.level = level
  }

  def debug(msg: String): Unit = logger.log(Level.ALL, msg)

  def info(msg: String): Unit = logger.log(Level.INFO, msg)

  def warn(msg: String): Unit = logger.log(Level.WARNING, msg)

  def error(msg: String): Unit = logger.log(Level.SEVERE, msg)

  def fatal(msg: String): Unit = {
    logger.log(Level.SEVERE, msg)
    scala.sys.exit(-1)
  }
} 
开发者ID:yunify,项目名称:qingstor-sdk-scala,代码行数:37,代码来源:QSLogger.scala


示例18: close

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

import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.atomic.AtomicInteger
import java.util.logging.{Logger, Level}

trait Chan[-T] {
  def !(elem: T)
  def close()
}


trait Proc[-T] extends Chan[T] {
  private[this] val q = new ConcurrentLinkedQueue[T]
  private[this] val nq = new AtomicInteger(0)
  @volatile private[this] var closed = false

  def close() { closed = true }

  def !(elem: T) {
    q.offer(elem)
    if (nq.getAndIncrement() == 0)
      do {
        val elem = q.poll()
        // Swallow exceptions as these would cause
        // unbounded queue growth.
        if (!closed) {
          try receiver(elem) catch {
             case exc =>
               Logger.getLogger("").log(Level.WARNING, "Exception thrown in proc", exc)
           }
        }
      } while (nq.decrementAndGet() > 0)
  }

  def receive: T => Unit
  private[this] val receiver = receive
}

object Proc {
  def apply[T](iteratee: T => Unit): Proc[T] = new Proc[T] {
    def receive = iteratee
  }

  val nil: Proc[Any] = new Proc[Any] { def receive = Function.const(()) }
} 
开发者ID:deenar,项目名称:fintest,代码行数:47,代码来源:Chan.scala


示例19: SourceTrackingMonitor

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

import com.twitter.finagle.SourcedException
import com.twitter.util.Monitor
import java.util.logging.{Level, Logger}


class SourceTrackingMonitor(logger: Logger, which: String) extends Monitor {
  def handle(exc: Throwable) = {
    logger.log(
      Level.SEVERE,
      "A " + which + " service " +
        unrollCauses(exc).mkString(" on behalf of ") + " threw an exception", exc)
    false
  }

  private[this] def unrollCauses(exc: Throwable, res: Seq[String] = Seq()): Seq[String] = exc match {
    case null => res.reverse
    case se: SourcedException => unrollCauses(se.getCause, se.serviceName +: res)
    case _ => unrollCauses(exc.getCause, res)
  }
} 
开发者ID:deenar,项目名称:fintest,代码行数:23,代码来源:SourceTrackingMonitor.scala


示例20: InvalidThriftConnectionException

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

import com.twitter.finagle.{ServiceProxy, Service, WriteException, ServiceException}
import java.util.logging.{Logger, Level}
import org.apache.thrift.TApplicationException
import org.apache.thrift.protocol.{TProtocolFactory, TMessageType}
import org.apache.thrift.transport.TMemoryInputTransport
import com.twitter.util.Future

case class InvalidThriftConnectionException() extends ServiceException {
  override def getMessage = "the thrift connection was invalidated"
}


class ValidateThriftService(
  self: Service[ThriftClientRequest, Array[Byte]],
  protocolFactory: TProtocolFactory
) extends ServiceProxy[ThriftClientRequest, Array[Byte]](self)
{
  @volatile private[this] var isValid = true

  override def apply(req: ThriftClientRequest) =
    if (!isValid) Future.exception(WriteException(InvalidThriftConnectionException()))
    else self(req) onSuccess { bytes =>
      if (!req.oneway && !isResponseValid(bytes)) {
        isValid = false
        Logger.getLogger("finagle-thrift").log(Level.WARNING,
          "Thrift connection was invalidated!")
      }
    }

  override def isAvailable = isValid && self.isAvailable

  private def isResponseValid(bytes: Array[Byte]) = try {
    val memoryTransport = new TMemoryInputTransport(bytes)
    val iprot = protocolFactory.getProtocol(memoryTransport)
    val reply = iprot.readMessageBegin()
    reply.`type` != TMessageType.EXCEPTION || {
      val exc = TApplicationException.read(iprot)
      iprot.readMessageEnd()
      exc.getType == TApplicationException.INTERNAL_ERROR ||
        exc.getType == TApplicationException.UNKNOWN_METHOD
    }
  } catch {
    case exc =>
      Logger.getLogger("finagle-thrift").log(Level.WARNING,
        "Exception while validating connection", exc)
      false
  }
} 
开发者ID:deenar,项目名称:fintest,代码行数:51,代码来源:ValidateThriftService.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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