本文整理汇总了Scala中java.util.concurrent.Callable类的典型用法代码示例。如果您正苦于以下问题:Scala Callable类的具体用法?Scala Callable怎么用?Scala Callable使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Callable类的19个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: Server
//设置package包名称以及导入依赖的类
package com.scala.examples.datagurn.lesson08
import com.scala.examples.datagurn.lesson07.Teacher
import java.util.concurrent.Callable
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import scala.concurrent.impl.Future
import java.util.concurrent.FutureTask
import scala.concurrent.impl.Future
import com.scala.examples.datagurn.lesson07.Teacher
object Server {
// ????????????
val executorService: ExecutorService = Executors.newFixedThreadPool(10);
val teachers: List[Teacher] = List(
new Teacher("t1", 20),
new Teacher("t2", 30),
new Teacher("t1", 25),
new Teacher("t1", 21)
);
def concurrentFilterByName(name: String): FutureTask[List[Teacher]] = {
val futures = new FutureTask[List[Teacher]](new Callable[List[Teacher]]() {
def call(): List[Teacher] = {
return filterByName(name);
}
})
executorService.execute(futures);
return futures; // ?? Future
}
def filterByName(name: String) : List[Teacher] = {
teachers.synchronized {
for {
item <- teachers
if item.name == name
} yield item
}
}
def main(args: Array[String]): Unit = {
val teachers : List[Teacher] = concurrentFilterByName("t1").get
println(teachers)
executorService.shutdown();
}
}
开发者ID:walle-liao,项目名称:scala-examples,代码行数:51,代码来源:Server.scala
示例2: 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
示例3: Blocking
//设置package包名称以及导入依赖的类
package org.zalando.benchmarks
import java.util.concurrent.{Callable, Executors}
import akka.actor.ActorSystem
import scala.concurrent.Await
import scala.concurrent.duration._
class Blocking(system: ActorSystem) {
import ComputationFollowedByAsyncPublishing._
def benchmark(coreFactor: Int): Unit = {
// let's do this Ye Olde Schoole Way
val exec = Executors newFixedThreadPool numWorkers(coreFactor)
try {
val futures = 1 to numTasks map Job map { job =>
exec.submit(new Callable[PublishResult] {
// explicitly turn async publishing operation into a blocking operation
override def call(): PublishResult = Await.result(Publisher publish (Computer compute job, system), 1 hour)
})
}
printResult(futures map (_.get))
} finally {
// never forget
exec.shutdown()
}
}
}
开发者ID:narayana-glassbeam,项目名称:scala-concurrency-playground,代码行数:32,代码来源:Blocking.scala
示例4: FailingKafkaStorage
//设置package包名称以及导入依赖的类
package io.amient.affinity.testutil.storage
import java.nio.ByteBuffer
import java.util.concurrent.{Callable, Executors, Future}
import com.typesafe.config.Config
import io.amient.affinity.core.storage.kafka.KafkaStorage
import org.apache.kafka.clients.producer.{ProducerRecord, RecordMetadata}
class FailingKafkaStorage(config: Config, partition: Int) extends KafkaStorage(config, partition) {
val executor = Executors.newFixedThreadPool(1)
override def write(key: ByteBuffer, value: ByteBuffer): Future[RecordMetadata] = {
val javaFuture: Future[RecordMetadata] = kafkaProducer.send(new ProducerRecord(topic, partition, key, value))
return executor.submit(new Callable[RecordMetadata]() {
override def call(): RecordMetadata = {
if (System.currentTimeMillis() % 10 == 0) {
throw new RuntimeException("Simulated Exception in FailingKafkaStorage")
} else {
javaFuture.get
}
}
})
}
}
开发者ID:amient,项目名称:affinity,代码行数:30,代码来源:FailingKafkaStorage.scala
示例5: DelegatingScheduledExecutorService
//设置package包名称以及导入依赖的类
package one.lockstep.util.concurrent
import java.util
import java.util.concurrent.{Callable, ScheduledExecutorService, ScheduledFuture}
import one.lockstep.util.japi._
import scala.concurrent.duration._
class DelegatingScheduledExecutorService(service: ScheduledExecutorService)
extends ScheduledExecutorService {
def prepareSchedule(delay: Long, unit: TimeUnit): Unit = ()
override def scheduleAtFixedRate(command: Runnable, initialDelay: Long, period: Long, unit: TimeUnit): ScheduledFuture[_] = {
prepareSchedule(List(initialDelay, period).max, unit)
service.scheduleAtFixedRate(command, initialDelay, period, unit)
}
override def schedule(command: Runnable, delay: Long, unit: TimeUnit): ScheduledFuture[_] = {
prepareSchedule(delay, unit)
service.schedule(command, delay, unit)
}
override def schedule[V](callable: Callable[V], delay: Long, unit: TimeUnit): ScheduledFuture[V] = {
prepareSchedule(delay, unit)
service.schedule(callable, delay, unit)
}
override def scheduleWithFixedDelay(command: Runnable, initialDelay: Long, delay: Long, unit: TimeUnit): ScheduledFuture[_] = {
prepareSchedule(List(initialDelay, delay).max, unit)
service.scheduleWithFixedDelay(command, initialDelay, delay, unit)
}
override def shutdown(): Unit = service.shutdown()
override def isTerminated: Boolean = service.isTerminated
override def awaitTermination(timeout: Long, unit: TimeUnit): Boolean =
service.awaitTermination(timeout, unit)
override def shutdownNow(): util.List[Runnable] = service.shutdownNow()
override def invokeAll[T](tasks: util.Collection[_ <: Callable[T]]): util.List[JFuture[T]] =
service.invokeAll(tasks)
override def invokeAll[T](tasks: util.Collection[_ <: Callable[T]], timeout: Long, unit: TimeUnit): util.List[JFuture[T]] =
service.invokeAll(tasks, timeout, unit)
override def invokeAny[T](tasks: util.Collection[_ <: Callable[T]]): T = service.invokeAny(tasks)
override def invokeAny[T](tasks: util.Collection[_ <: Callable[T]], timeout: Long, unit: TimeUnit): T =
service.invokeAny(tasks, timeout, unit)
override def isShutdown: Boolean = service.isShutdown
override def submit[T](task: Callable[T]): JFuture[T] = service.submit(task)
override def submit[T](task: Runnable, result: T): JFuture[T] = service.submit(task, result)
override def submit(task: Runnable): JFuture[_] = service.submit(task)
override def execute(command: Runnable): Unit = service.execute(command)
}
开发者ID:lockstep-one,项目名称:vault,代码行数:47,代码来源:DelegatingScheduledExecutorService.scala
示例6: ImmediateExecutorService
//设置package包名称以及导入依赖的类
package one.lockstep.util.concurrent
import java.util.concurrent.{AbstractExecutorService, Callable, RunnableFuture}
import scala.concurrent.duration._
import one.lockstep.util.japi._
object ImmediateExecutorService extends AbstractExecutorService {
override def shutdown(): Unit = ()
override def isTerminated: Boolean = false
override def awaitTermination(timeout: Long, unit: TimeUnit): Boolean = true
override def shutdownNow(): JList[Runnable] = JCollections.emptyList()
override def isShutdown: Boolean = false
override def execute(command: Runnable): Unit = command.run()
override def newTaskFor[T](callable: Callable[T]): RunnableFuture[T] = new RunnableFuture[T] {
var result: Option[T] = None
override def run(): Unit = { result = Some(callable.call()) }
override def isCancelled: Boolean = false
override def get(): T = result.get
override def get(timeout: Long, unit: TimeUnit): T = result.get
override def cancel(mayInterruptIfRunning: Boolean): Boolean = ???
override def isDone: Boolean = result.isDefined
}
override def newTaskFor[T](runnable: Runnable, value: T): RunnableFuture[T] = new RunnableFuture[T] {
var result: Option[T] = None
override def run(): Unit = { runnable.run(); result = Some(value) }
override def isCancelled: Boolean = false
override def get(): T = result.get
override def get(timeout: Long, unit: TimeUnit): T = result.get
override def cancel(mayInterruptIfRunning: Boolean): Boolean = ???
override def isDone: Boolean = result.isDefined
}
}
开发者ID:lockstep-one,项目名称:vault,代码行数:35,代码来源:ImmediateExecutorService.scala
示例7: FlatZincResultFormatter
//设置package包名称以及导入依赖的类
package yuck.flatzinc.runner
import java.util.concurrent.Callable
import scala.collection._
import yuck.core._
import yuck.flatzinc.ast._
import yuck.flatzinc.compiler.FlatZincCompilerResult
final class FlatZincResultFormatter(result: Result) extends Callable[Seq[String]] {
private val compilerResult = result.maybeUserData.get.asInstanceOf[FlatZincCompilerResult]
override def call = {
var sortedMap = new immutable.TreeMap[String, String]() // id -> value
for (decl <- compilerResult.ast.varDecls) {
for (annotation <- decl.annotations) {
annotation match {
case Annotation(Term("output_var", Nil)) =>
val x = compilerResult.vars(decl.id)
sortedMap = sortedMap + (decl.id -> value(x, decl).toString)
case Annotation(Term("output_array", List(ArrayConst(dimensions)))) =>
val ArrayType(Some(IntRange(1, n)), _) = decl.varType
val a =
"array%dd(%s, [%s])".format(
dimensions.size,
(for (IntSetConst(IntRange(lb, ub)) <- dimensions) yield
"%d..%d".format(lb, ub)).mkString(", "),
(for (idx <- 1 to n) yield
value(compilerResult.arrays(decl.id)(idx - 1), decl).toString).mkString(", "))
sortedMap = sortedMap + (decl.id -> a)
case _ =>
}
}
}
val lines = mutable.ArrayBuffer[String]()
for ((id, value) <- sortedMap) lines += "%s = %s;".format(id, value)
if (result.isSolution) {
lines += FLATZINC_SOLUTION_SEPARATOR
if (result.objective.isInstanceOf[HierarchicalObjective] && result.isGoodEnough) {
lines += FLATZINC_BEST_SOLUTION_FOUND_INDICATOR
}
} else {
lines += FLATZINC_NO_SOLUTION_FOUND_INDICATOR
}
lines.toSeq
}
private def value(x: AnyVariable, decl: VarDecl): AnyValue = decl.varType match {
case BoolType | ArrayType(_, BoolType) =>
if (result.bestProposal.value(IntegerValue.Traits.staticCast(x)) == Zero) True else False
case _ => result.bestProposal.anyValue(x)
}
}
开发者ID:informarte,项目名称:yuck,代码行数:58,代码来源:FlatZincResultFormatter.scala
示例8: StandardAnnealingScheduleFactory
//设置package包名称以及导入依赖的类
package yuck.annealing
import java.util.concurrent.Callable
import scala.collection._
import scala.math._
import yuck.core._
final class StandardAnnealingScheduleFactory
(numberOfSearchVariables: Int, randomGenerator: RandomGenerator)
extends Callable[AnnealingSchedule]
{
private val numberOfMovesPerVariableAndRound =
(numberOfSearchVariables * 256.0 / (log(numberOfSearchVariables) * log(2))).toInt
private val finalTemperature = 0.0001
private val maximumUphillAcceptanceRatio = 0.15
private val minimumUphillAcceptanceRatio = 0.0001
private val heatingRate = 1.2
private val coolingRate = 0.95
private def createAnnealingSchedule(divisor: Int): AnnealingSchedule = {
new AnnealingScheduleLoop(
new AnnealingScheduleSequence(
Vector(
new AdaptiveCoolingSchedule(
finalTemperature, minimumUphillAcceptanceRatio, coolingRate,
numberOfMovesPerVariableAndRound / divisor, 4 / divisor),
new GeometricHeatingSchedule(
maximumUphillAcceptanceRatio, heatingRate,
numberOfMovesPerVariableAndRound / divisor))),
4 / divisor)
}
override def call = {
val fastSchedule = createAnnealingSchedule(2)
val slowSchedule = createAnnealingSchedule(1)
val schedule = randomGenerator.nextInt(3) match {
case 0 => fastSchedule
case 1 => slowSchedule
case 2 => new AnnealingScheduleSequence(Vector(fastSchedule, slowSchedule))
}
def startTemperatures: Stream[Double] = Stream.cons(randomGenerator.nextProbability / 10, startTemperatures)
val startTemperature = startTemperatures.dropWhile(_ <= finalTemperature).head
schedule.start(startTemperature, 0)
schedule
}
}
开发者ID:informarte,项目名称:yuck,代码行数:52,代码来源:StandardAnnealingScheduleFactory.scala
示例9: ProcessRunner
//设置package包名称以及导入依赖的类
package yuck.util.testing
import scala.collection.JavaConversions
import java.util.concurrent.Callable
import yuck.util.logging.LazyLogger
class ProcessRunner(logger: LazyLogger, commandLine: Seq[String]) extends Callable[(List[String], List[String])] {
override def call = {
val processBuilder = new java.lang.ProcessBuilder(JavaConversions.seqAsJavaList(commandLine))
logger.log(JavaConversions.asScalaBuffer(processBuilder.command).toIterator.mkString(" "))
val process = processBuilder.start
val stdout = scala.io.Source.fromInputStream(process.getInputStream)
val stderr = scala.io.Source.fromInputStream(process.getErrorStream)
val outputLines = stdout.mkString.lines.toList
val (errorLines, warningLines) = stderr.mkString.lines.toList.partition(_.toLowerCase.contains("error"))
outputLines.foreach(logger.log(_))
warningLines.foreach(logger.log(_))
errorLines.foreach(logger.log(_))
(outputLines, errorLines)
}
}
开发者ID:informarte,项目名称:yuck,代码行数:26,代码来源:ProcessRunner.scala
示例10: withTime
//设置package包名称以及导入依赖的类
package io.github.maxkorolev.task
import java.util.concurrent.Callable
import scala.concurrent.duration.FiniteDuration
trait Task extends Callable[Any] with Serializable {
val time: Long
val timeout: FiniteDuration
def withTime(t: Long): Task = new Task {
val time: Long = t
val timeout: FiniteDuration = timeout
override def call(): AnyRef = call _
}
override def equals(any: Any): Boolean = {
any match {
case t: Task => time == t.time && timeout == t.timeout
case _ => false
}
}
override def hashCode: Int = {
val prime = 31
var result = 1
result = prime * result + time.toInt
result = prime * result + timeout.hashCode()
result
}
override def toString: String = s"Task(time: $time, timeout: ${timeout.toString})"
}
开发者ID:maxkorolev,项目名称:pix,代码行数:35,代码来源:Task.scala
示例11: inetSocketAddress
//设置package包名称以及导入依赖的类
package com.wavesplatform
import java.net.{InetSocketAddress, SocketAddress, URI}
import java.util.concurrent.Callable
import com.wavesplatform.state2.ByteStr
import io.netty.channel.group.{ChannelGroup, ChannelMatchers}
import io.netty.channel.local.LocalAddress
import io.netty.channel.socket.SocketChannel
import io.netty.channel.{Channel, ChannelHandlerContext}
import io.netty.util.NetUtil.toSocketAddressString
import io.netty.util.concurrent.{EventExecutorGroup, ScheduledFuture}
import scorex.block.Block
import scorex.utils.ScorexLogging
import scala.concurrent.duration._
package object network extends ScorexLogging {
def inetSocketAddress(addr: String, defaultPort: Int): InetSocketAddress = {
val uri = new URI(s"node://$addr")
if (uri.getPort < 0) new InetSocketAddress(addr, defaultPort)
else new InetSocketAddress(uri.getHost, uri.getPort)
}
implicit class EventExecutorGroupExt(val e: EventExecutorGroup) extends AnyVal {
def scheduleWithFixedDelay(initialDelay: FiniteDuration, delay: FiniteDuration)(f: => Unit): ScheduledFuture[_] =
e.scheduleWithFixedDelay((() => f): Runnable, initialDelay.toNanos, delay.toNanos, NANOSECONDS)
def schedule[A](delay: FiniteDuration)(f: => A): ScheduledFuture[A] =
e.schedule((() => f): Callable[A], delay.length, delay.unit)
}
private def formatAddress(sa: SocketAddress) = sa match {
case null => ""
case l: LocalAddress => s" ${l.toString}"
case isa: InetSocketAddress => s" ${toSocketAddressString(isa)}"
}
def id(ctx: ChannelHandlerContext): String = id(ctx.channel())
def id(chan: Channel, prefix: String = ""): String = s"[$prefix${chan.id().asShortText()}${formatAddress(chan.remoteAddress())}]"
def formatBlocks(blocks: Seq[Block]): String = formatSignatures(blocks.view.map(_.uniqueId))
def formatSignatures(signatures: Seq[ByteStr]): String = if (signatures.isEmpty) ""
else if (signatures.size == 1) s"[${signatures.head}]"
else s"[${signatures.head}..${signatures.last}]"
implicit class ChannelHandlerContextExt(val ctx: ChannelHandlerContext) extends AnyVal {
def remoteAddress: InetSocketAddress = ctx.channel().asInstanceOf[SocketChannel].remoteAddress()
}
implicit class ChannelGroupExt(val allChannels: ChannelGroup) extends AnyVal {
def broadcast(message: AnyRef, except: Option[Channel] = None): Unit = {
log.trace(s"Broadcasting $message to ${allChannels.size()} channels${except.fold("")(c => s" (except ${id(c)})")}")
allChannels.writeAndFlush(message, except.fold(ChannelMatchers.all())(ChannelMatchers.isNot))
}
}
}
开发者ID:wavesplatform,项目名称:Waves,代码行数:60,代码来源:package.scala
示例12: InputStreamingServer
//设置package包名称以及导入依赖的类
package com.bwsw.sj.engine.input.connection.tcp.server
import java.util.concurrent.{Callable, ArrayBlockingQueue}
import com.bwsw.sj.engine.core.input.InputStreamingExecutor
import io.netty.bootstrap.ServerBootstrap
import io.netty.buffer.ByteBuf
import io.netty.channel._
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.nio.NioServerSocketChannel
import io.netty.handler.logging.{LogLevel, LoggingHandler}
import org.slf4j.LoggerFactory
import scala.collection.concurrent
class InputStreamingServer(host: String,
port: Int,
executor: InputStreamingExecutor,
channelContextQueue: ArrayBlockingQueue[ChannelHandlerContext],
bufferForEachContext: concurrent.Map[ChannelHandlerContext, ByteBuf]) extends Callable[Unit] {
private val logger = LoggerFactory.getLogger(this.getClass)
override def call() = {
logger.info(s"Launch input streaming server on: '$host:$port'\n")
val bossGroup: EventLoopGroup = new NioEventLoopGroup()
val workerGroup = new NioEventLoopGroup()
try {
val bootstrapServer = new ServerBootstrap()
bootstrapServer.group(bossGroup, workerGroup)
.channel(classOf[NioServerSocketChannel])
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new InputStreamingChannelInitializer(executor, channelContextQueue, bufferForEachContext))
bootstrapServer.bind(host, port).sync().channel().closeFuture().sync()
} finally {
workerGroup.shutdownGracefully()
bossGroup.shutdownGracefully()
}
}
}
开发者ID:bwsw,项目名称:sj-platform,代码行数:44,代码来源:InputStreamingServer.scala
示例13: ArbitraryCompilationTest
//设置package包名称以及导入依赖的类
package com.avsystem.scex
package compiler
import java.util.concurrent.Callable
import java.{lang => jl, util => ju}
import org.scalatest.FunSuite
class ArbitraryCompilationTest extends FunSuite {
val compiler = new DefaultScexCompiler(new ScexSettings)
test("arbitrary source code compilation test") {
val code =
"""
|package com.avsystem.scex
|package test
|
|class Stuff extends java.util.concurrent.Callable[String] {
| def call = "stuff"
|}
|
""".stripMargin
val clazz = compiler.compileClass(code, "com.avsystem.scex.test.Stuff")
val callable = clazz.newInstance.asInstanceOf[Callable[String]]
assert("stuff" === callable.call())
}
}
开发者ID:AVSystem,项目名称:scex,代码行数:31,代码来源:ArbitraryCompilationTest.scala
示例14: MockScheduledExecutorService
//设置package包名称以及导入依赖的类
package com.twitter.jvm
import java.util.concurrent.{AbstractExecutorService, Callable, ScheduledExecutorService, ScheduledFuture, TimeUnit}
import scala.collection.mutable
// A mostly empty implementation so that we can successfully
// mock it.
class MockScheduledExecutorService extends AbstractExecutorService with ScheduledExecutorService {
val schedules = mutable.Buffer[(Runnable, Long, Long, TimeUnit)]()
def schedule[V](c: Callable[V], delay: Long, unit: TimeUnit) = throw new Exception
def schedule(command: Runnable, delay: Long, unit: TimeUnit) = throw new Exception
def scheduleWithFixedDelay(command: Runnable, initialDelay: Long, delay: Long, unit: TimeUnit) =
throw new Exception
def execute(command: Runnable) = throw new Exception
def awaitTermination(timeout: Long, unit: TimeUnit) = throw new Exception
def isTerminated() = throw new Exception
def isShutdown() = throw new Exception
def shutdownNow() = throw new Exception
def shutdown() = throw new Exception
def scheduleAtFixedRate(r: Runnable, initialDelay: Long, period: Long, unit: TimeUnit): ScheduledFuture[_] = {
schedules += ((r, initialDelay, period, unit))
null
}
}
开发者ID:lanshuijuntuan,项目名称:Java.util,代码行数:28,代码来源:MockScheduledExecutorService.scala
示例15: TempFileWebCrawler
//设置package包名称以及导入依赖的类
package org.zella.web
import java.util.concurrent.Callable
import com.gargoylesoftware.htmlunit.WebClient
import com.gargoylesoftware.htmlunit.html.{HtmlAnchor, HtmlPage, HtmlSubmitInput}
import io.reactivex.Observable
class TempFileWebCrawler(webClient: WebClient) extends ITempFileWebCrawler {
override def clickButton(page: HtmlPage): HtmlPage = {
page
.getByXPath("//*[@id=\"cntMainCenterText\"]/form/table/tbody/tr/td/input[2]")
.get(0)
.asInstanceOf[HtmlSubmitInput]
.click()
.asInstanceOf[HtmlPage]
}
override def clickDownloadLink(page: HtmlPage): String = {
page
.getByXPath("//*[@id=\"cntMainCenterText\"]/center/b/a")
.get(0)
.asInstanceOf[HtmlAnchor]
.getHrefAttribute
}
override def clickButtonAsync(page: HtmlPage): Observable[HtmlPage] = {
Observable.fromCallable(new Callable[HtmlPage] {
override def call() = clickButton(page)
})
}
override def clickDownloadLinkAsync(page: HtmlPage): Observable[String] = {
Observable.fromCallable(new Callable[String] {
override def call() = clickDownloadLink(page)
})
}
}
开发者ID:zella,项目名称:Mp3SpbDownloader,代码行数:45,代码来源:TempFileWebCrawler.scala
示例16: Mp3SpbWebCrawler
//设置package包名称以及导入依赖的类
package org.zella.web
import java.util
import java.util.concurrent.Callable
import com.gargoylesoftware.htmlunit.WebClient
import com.gargoylesoftware.htmlunit.html.{HtmlAnchor, HtmlDivision, HtmlPage}
import io.reactivex.Observable
import scala.collection.JavaConverters._
class Mp3SpbWebCrawler(webClient: WebClient) extends IMp3SpbWebCrawler {
override def albumInfo(albumUrl: String): AlbumInfo = {
val albumPage = webClient.getPage(albumUrl).asInstanceOf[HtmlPage]
val nameDiv = albumPage.querySelector("#cntCenter > div.cntAlbumMusician > div.albCover > div")
.asInstanceOf[HtmlDivision]
val (name, year) = nameDiv.asText().split("\n") match {
case Array(n, y) => (n.trim, y.trim)
}
val artist = albumPage.querySelector("#cntCenter > h1:nth-child(1) > a")
.asInstanceOf[HtmlAnchor]
.getAttribute("title")
.replace(" mp3", "")
val songs = albumPage.querySelector("#cntCenter > div.cntAlbumMusician > div.albSong")
.asInstanceOf[HtmlDivision]
.getChildElements
.asScala
.filter(_.isInstanceOf[HtmlDivision])
.map(htmlDiv => {
val anchors = htmlDiv.getChildElements.asScala
.filter(_.isInstanceOf[HtmlAnchor])
.toList
val base = albumPage.getBaseURL.getProtocol + "://" + albumPage.getBaseURL.getHost
val downloadLink = base + anchors(0).asInstanceOf[HtmlAnchor].getHrefAttribute
val name = anchors(0).asInstanceOf[HtmlAnchor].getTextContent
val playLink = base + anchors(2).asInstanceOf[HtmlAnchor].getHrefAttribute
SongInfo(name, downloadLink, playLink)
})
val songsMap = new util.HashMap[Integer, SongInfo]()
for ((song, i) <- songs.zipWithIndex) {
songsMap.put(i + 1, song)
}
AlbumInfo(artist, year, name, songsMap)
}
override def albumInfoAsync(albumUrl: String): Observable[AlbumInfo] = {
Observable.fromCallable(new Callable[AlbumInfo] {
override def call() = albumInfo(albumUrl)
})
}
}
开发者ID:zella,项目名称:Mp3SpbDownloader,代码行数:61,代码来源:Mp3SpbWebCrawler.scala
示例17: point
//设置package包名称以及导入依赖的类
package deaktator.advtut.futures.instances
import java.util.concurrent.Callable
import com.google.common.util.concurrent.{AsyncFunction, Futures, ListeningExecutorService, ListenableFuture}
import deaktator.advtut.futures.cats.Monad
import com.google.common.base.{Function => GFunction}
import deaktator.advtut.futures.instances.ListenableFutureInstances._
override def point[A](asyncExecutedValue: => A): ListenableFuture[A] = {
exSvc.submit(new Callable[A]{
override def call(): A = asyncExecutedValue
})
}
override def flatMap[A, B](ma: ListenableFuture[A])(f: A => ListenableFuture[B]): ListenableFuture[B] =
Futures.transform(ma, GAsyncFn(f))
override def map[A, B](fa: ListenableFuture[A])(f: A => B): ListenableFuture[B] =
Futures.transform(fa, GFn(f)) // flatMap(fa)(a => point(f(a)))
override def ap[A, B](x: ListenableFuture[A])(f: ListenableFuture[A => B]): ListenableFuture[B] =
flatMap(f)(g => map(x)(y => g(y))) // map2(x, f)((y, g) => g(y))
override def map2[A, B, C](x: ListenableFuture[A], y: ListenableFuture[B])(f: (A, B) => C): ListenableFuture[C] =
flatMap(y)(b => map(x)(a => f(a, b))) // ap(y)(map(x)(f.curried))
}
object ListenableFutureInstances {
object Implicits {
implicit def listenableFutureInstances(implicit exSvc: ListeningExecutorService): ListenableFutureInstances =
ListenableFutureInstances(exSvc)
}
case class GFn[A, B](f: A => B) extends GFunction[A, B] {
def apply(a: A): B = f(a)
}
case class GAsyncFn[A, B](f: A => ListenableFuture[B]) extends AsyncFunction[A, B] {
def apply(a: A): ListenableFuture[B] = f(a)
}
}
开发者ID:deaktator,项目名称:advanced-scala-tutorial,代码行数:44,代码来源:ListenableFutureInstances.scala
示例18: inetSocketAddress
//设置package包名称以及导入依赖的类
package com.wavesplatform
import java.net.{InetSocketAddress, SocketAddress, URI}
import java.util.concurrent.Callable
import io.netty.channel.group.{ChannelGroup, ChannelMatchers}
import io.netty.channel.local.LocalAddress
import io.netty.channel.socket.SocketChannel
import io.netty.channel.{Channel, ChannelHandlerContext}
import io.netty.util.NetUtil.toSocketAddressString
import io.netty.util.concurrent.{EventExecutorGroup, ScheduledFuture}
import scorex.utils.ScorexLogging
import scala.concurrent.duration._
package object network extends ScorexLogging {
def inetSocketAddress(addr: String, defaultPort: Int): InetSocketAddress = {
val uri = new URI(s"node://$addr")
if (uri.getPort < 0) new InetSocketAddress(addr, defaultPort)
else new InetSocketAddress(uri.getHost, uri.getPort)
}
implicit class EventExecutorGroupExt(val e: EventExecutorGroup) extends AnyVal {
def scheduleWithFixedDelay(initialDelay: FiniteDuration, delay: FiniteDuration)(f: => Unit): ScheduledFuture[_] =
e.scheduleWithFixedDelay((() => f): Runnable, initialDelay.toNanos, delay.toNanos, NANOSECONDS)
def schedule[A](delay: FiniteDuration)(f: => A): ScheduledFuture[A] =
e.schedule((() => f): Callable[A], delay.length, delay.unit)
}
private def formatAddress(sa: SocketAddress) = sa match {
case null => ""
case l: LocalAddress => s" ${l.toString}"
case isa: InetSocketAddress => s" ${toSocketAddressString(isa)}"
}
def id(ctx: ChannelHandlerContext): String = id(ctx.channel())
def id(chan: Channel): String = s"[${chan.id().asShortText()}${formatAddress(chan.remoteAddress())}]"
implicit class ChannelHandlerContextExt(val ctx: ChannelHandlerContext) extends AnyVal {
def remoteAddress: InetSocketAddress = ctx.channel().asInstanceOf[SocketChannel].remoteAddress()
}
implicit class ChannelExt(val channel: Channel) extends AnyVal {
def declaredAddress: Option[InetSocketAddress] = Option(channel.attr(AttributeKeys.DeclaredAddress).get())
}
implicit class ChannelGroupExt(val allChannels: ChannelGroup) extends AnyVal {
def broadcast(message: AnyRef, except: Option[Channel] = None): Unit = {
log.trace(s"Broadcasting $message to ${allChannels.size()} channels${except.fold("")(c => s" (except ${id(c)})")}")
allChannels.writeAndFlush(message, except.fold(ChannelMatchers.all())(ChannelMatchers.isNot))
}
}
}
开发者ID:mikepijn,项目名称:wavesnode,代码行数:57,代码来源:package.scala
示例19: DummyServer
//设置package包名称以及导入依赖的类
package com.github.pheymann.mockit.util
import java.net.ServerSocket
import java.util.concurrent.Callable
import com.github.pheymann.mockit.core.core._
import com.github.pheymann.mockit.logging.Logger
import com.github.pheymann.mockit.util.TestUtil._
class DummyServer(
val resultNumber: Int,
val expected: Array[Byte]
) extends Callable[Boolean]
with Logger {
val server = new ServerSocket(DEFAULT_PORT)
override def call: Boolean = {
var failure = false
> (start)
for (i <- 0 until resultNumber) {
val result = new Array[Byte](expected.length)
val client = server.accept
val inStream = client.getInputStream
inStream.read(result, 0, result.length)
val check = checkArrayEquals(expected, result)
if (!check) {
error ("received data not as expected")
failure = true
}
client.close()
}
> (stop)
server.close()
failure
}
}
开发者ID:simonox,项目名称:MockIt,代码行数:45,代码来源:DummyServer.scala
注:本文中的java.util.concurrent.Callable类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论