本文整理汇总了Scala中java.io.Closeable类的典型用法代码示例。如果您正苦于以下问题:Scala Closeable类的具体用法?Scala Closeable怎么用?Scala Closeable使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Closeable类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: ZipUtils
//设置package包名称以及导入依赖的类
package core
import java.io.Closeable
import java.nio.charset.StandardCharsets._
import java.util.zip.{ZipEntry, ZipInputStream}
import scala.collection.JavaConversions._
import scala.collection.mutable.ArrayBuffer
object ZipUtils {
case class UnzippedFileContent(filename: String, content: String)
def usingZip[R <: Closeable, T](unzippedStream: R)(f: (R) => T) = {
try {
f(unzippedStream)
} finally {
unzippedStream.close()
}
}
def unzipAllFilesInStream(unzippedStream: ZipInputStream): Stream[UnzippedFileContent] = {
unzipAllFilesInStream(unzippedStream, Option(unzippedStream.getNextEntry))
}
def unzipAllFilesInStream(unzippedStream: ZipInputStream, ze: Option[ZipEntry]): Stream[UnzippedFileContent] = {
ze match {
case None => Stream.empty
case Some(ze) =>
val name: String = ze.getName
val entry: String = ZipUtils.getZipEntry(unzippedStream)
val maybeEntry1: Option[ZipEntry] = Option(unzippedStream.getNextEntry)
UnzippedFileContent(name, entry) #::
unzipAllFilesInStream(unzippedStream, maybeEntry1)
}
}
def getZipEntry(zis: ZipInputStream): String = {
val buffer = new Array[Byte](4096)
val stringBuffer = new ArrayBuffer[Byte]()
var len: Int = zis.read(buffer)
while (len > 0) {
stringBuffer ++= buffer.take(len)
len = zis.read(buffer)
}
val content: String = new String(stringBuffer.toArray, UTF_8)
(content)
}
}
示例2: JarClassSource
//设置package包名称以及导入依赖的类
package eu.tznvy.jancy.transpiler.discovery
import java.io.File
import java.net.URLClassLoader
import java.util.zip.ZipFile
import java.io.Closeable
import scala.collection.JavaConverters._
class JarClassSource(file: File) extends Closeable {
lazy val zipFile = new ZipFile(file.getPath)
override def close(): Unit = {
zipFile.close()
}
def iterate: Iterator[Class[_]] = {
val classLoader = new URLClassLoader(Array(file.toURI.toURL))
zipFile
.stream
.iterator
.asScala
.map(_.getName)
.filter(_.endsWith(".class"))
.map(_.replace(".class", "").replace('/', '.'))
.map(classLoader.loadClass)
}
}
示例3: LibratoClient
//设置package包名称以及导入依赖的类
package com.ovoenergy.lambda.client
import java.io.Closeable
import java.util.concurrent.TimeUnit
import scala.collection.JavaConverters._
import com.librato.metrics._
import com.ovoenergy.lambda.domain.KafkaMetrics
class LibratoClient(email: String, apiToken: String, apiUrl:String, environment: String) extends Closeable {
val poster = new DefaultHttpPoster(apiUrl, email, apiToken)
val batchSize = 300
val timeout = 10L
val timeoutUnit = TimeUnit.SECONDS
val agent = "BENZAITEN"
val sanitizer = Sanitizer.NO_OP
val batch = new LibratoBatch(batchSize, sanitizer, timeout, timeoutUnit, agent, poster)
def addMetrics(metrics: KafkaMetrics) = {
metrics.partitionMetrics.map { metric =>
batch.addCounterMeasurement(s"$environment.kafka.${metrics.consumerGroup}.partition${metric.partition}.lag", metric.lag)
}
}
def submitMetrics() = {
val source = s"$environment-kafka-metrics-lambda"
val result: BatchResult = batch.post(source, System.currentTimeMillis() / 1000)
if (!result.success()) {
result.getFailedPosts.asScala.foreach { failedRes =>
println(s"Failed: $failedRes")
}
}
}
override def close() = {
poster.close()
}
}
示例4: using
//设置package包名称以及导入依赖的类
package com.ovoenergy.lambda
import java.io.Closeable
trait ConnectionHelpers {
def using[R <: Closeable, T](create: => R)(f: R => T): T = {
val resource = create
try {
f(resource)
} finally {
resource.close()
}
}
}
示例5: AppLoader
//设置package包名称以及导入依赖的类
import java.io.Closeable
import javax.sql.DataSource
import controllers.UsersController
import io.getquill._
import play.api.ApplicationLoader.Context
import play.api._
import play.api.db.evolutions.Evolutions
import play.api.db.{DBComponents, HikariCPComponents}
import play.api.inject.{Injector, NewInstanceInjector, SimpleInjector}
import play.api.routing.Router
import play.api.routing.sird._
import models.{Users}
class AppLoader extends ApplicationLoader {
override def load(context: Context): Application = new BuiltInComponentsFromContext(context) with DBComponents with HikariCPComponents {
lazy val db = new H2JdbcContext[SnakeCase](dbApi.database("default").dataSource.asInstanceOf[DataSource with Closeable])
lazy val users = new Users(db)
lazy val usersController = new UsersController(users)
val router = Router.from {
case GET(p"/users/${long(id)}") => usersController.get(id)
case POST(p"/users") => usersController.create
case DELETE(p"/users/${long(id)}") => usersController.delete(id)
case PUT(p"/users/${long(id)}") => usersController.update(id)
}
override lazy val injector: Injector =
new SimpleInjector(NewInstanceInjector) + users + router + cookieSigner + csrfTokenSigner + httpConfiguration + tempFileCreator + global
Evolutions.applyEvolutions(dbApi.database("default"))
}.application
}
示例6: AppLoader
//设置package包名称以及导入依赖的类
import java.io.Closeable
import javax.sql.DataSource
import controllers.MainController
import io.getquill._
import models.Services
import unus.db._
import unus.helpers.Conf
import unus.model.FeatureBuilder
import unus.stage.{BlockerCacher, DatabaseBackup, PatientCacher, PatientDatabase}
import org.flywaydb.play.FlywayPlayComponents
import play.api.ApplicationLoader.Context
import play.api._
import play.api.db.{DBComponents, HikariCPComponents}
import play.api.inject.{Injector, NewInstanceInjector, SimpleInjector}
import play.api.routing.Router
import play.filters.csrf._
import router.Routes
class AppLoader extends ApplicationLoader {
override def load(context: Context): Application = new BuiltInComponentsFromContext(context)
with DBComponents with HikariCPComponents with CSRFComponents
with FlywayPlayComponents with play.filters.HttpFiltersComponents with _root_.controllers.AssetsComponents {
lazy val db = new PostgresJdbcContext[PostgresEscape](dbApi.database("default").dataSource.asInstanceOf[DataSource with Closeable])
lazy val services = new Services(db)
lazy val patientCacher = new PatientCacher
lazy val repo = new Repository(db)
lazy val blockerCachers = Conf.blockers.map(new BlockerCacher(repo, patientCacher.value, _))
lazy val features = Conf.features
lazy val controller = new MainController(services, repo, patientCacher, blockerCachers, features)(controllerComponents)
lazy val router: Router = new Routes(httpErrorHandler, controller)
override lazy val injector: Injector =
new SimpleInjector(NewInstanceInjector) + cookieSigner + csrfTokenSigner + httpConfiguration + tempFileCreator + router
override lazy val httpFilters = Seq(csrfFilter)
flywayPlayInitializer
new PatientDatabase(repo, patientCacher).run()
if(services.getLabelCount == 0) {
new DatabaseBackup[Label]("Label").load()
}
if(services.getBlockedRowCount == 0) {
new DatabaseBackup[BlockedRow]("BlockedRow").load()
}
}.application
}
示例7: Closeables
//设置package包名称以及导入依赖的类
package com.thoughtworks.compute
import java.io.Closeable
object Closeables {
trait IsClosed {
protected final var closed = false
}
trait AssertionFinalizer { this: IsClosed =>
override protected final def finalize(): Unit = {
if (!closed) {
throw new IllegalStateException("close() must be called before garbage collection.")
}
}
}
trait IdempotentFinalizer { this: Closeable =>
override protected final def finalize(): Unit = close()
}
@throws(classOf[IllegalStateException])
override final def close(): Unit = {
val wasClosed = synchronized {
val wasClosed = closed
if (!wasClosed) {
closed = true
}
wasClosed
}
if (wasClosed) {
throw new IllegalStateException("Can't close more than once.")
} else {
forceClose()
}
}
}
}
示例8: TaskExtensions
//设置package包名称以及导入依赖的类
package kafka.console
import java.io.Closeable
import javax.management.MBeanServerConnection
import javax.management.remote.{JMXConnectorFactory, JMXServiceURL}
import scalaz.{-\/, \/-}
import scalaz.concurrent.Task
package object extensions extends Conversions with MBeanServerConnectionExtensions {
implicit final class TaskExtensions(val self: Task.type) extends AnyVal {
def use[A,B](obj: => A)(close: A => Unit)(body: A => Task[B]) =
Task.delay(obj).flatMap { body }.attempt.flatMap {
case \/-(content) => close(obj); Task.now(content)
case -\/(failure) => close(obj); Task.fail(failure)
}
def bracket[A<:Closeable,B](obj: A)(body: A => Task[B]) =
Task.now(obj).flatMap{body}.attempt.flatMap{
case \/-(content) => obj.close(); Task.now(content)
case -\/(failure) => obj.close(); Task.fail(failure)
}
}
}
示例9: transform
//设置package包名称以及导入依赖的类
package org.pico.event
import java.io.Closeable
import java.lang.ref.WeakReference
import java.util.concurrent.atomic.{AtomicInteger, AtomicReference}
import org.pico.atomic.syntax.std.atomicReference._
import org.pico.disposal.OnClose
trait SimpleSinkSource[A, B] extends SinkSource[A, B] {
private final val subscribers = new AtomicReference(List.empty[WeakReference[B => Unit]])
private final val garbage = new AtomicInteger(0)
def transform: A => B
final override def publish(event: A): Unit = {
subscribers.get().foreach { subscriberRef =>
val subscriber = subscriberRef.get()
if (subscriber != null) {
subscriber(transform(event))
} else {
garbage.incrementAndGet()
}
}
houseKeep()
}
final override def subscribe(subscriber: B => Unit): Closeable = {
val subscriberRef = new WeakReference(subscriber)
subscribers.update(subscriberRef :: _)
houseKeep()
OnClose {
identity(subscriber)
subscriberRef.clear()
houseKeep()
}
}
final def houseKeep(): Unit = {
if (garbage.get() > subscribers.get().size) {
garbage.set(0)
subscribers.update { subscriptions =>
subscriptions.filter { subscription =>
subscription.get() != null
}
}
}
}
}
示例10: map
//设置package包名称以及导入依赖的类
package org.pico.event
import java.io.Closeable
import org.pico.disposal.std.autoCloseable._
override def map[C](f: B => C): SinkSource[A, C] = new SinkSource[A, C] { temp =>
val that = SinkSource[B, C](f)
temp.disposes(self.subscribe(that.publish))
override def subscribe(subscriber: C => Unit): Closeable = that.subscribe(subscriber)
override def publish(event: A): Unit = self.publish(event)
}
}
object SinkSource {
def apply[A, B](f: A => B): SinkSource[A, B] = new SimpleSinkSource[A, B] {
override val transform = f
}
}
示例11: TryWith
//设置package包名称以及导入依赖的类
package com.peschke.codeReview
import java.io.Closeable
import scala.util.control.NonFatal
import scala.util.{Failure, Try}
object TryWith {
def apply[C <: Closeable, R](resource: => C)(f: C => R): Try[R] =
Try(resource).flatMap(resourceInstance => {
try {
val returnValue = f(resourceInstance)
Try(resourceInstance.close()).map(_ => returnValue)
}
catch {
case NonFatal(exceptionInFunction) =>
try {
resourceInstance.close()
Failure(exceptionInFunction)
}
catch {
case NonFatal(exceptionInClose) =>
exceptionInFunction.addSuppressed(exceptionInClose)
Failure(exceptionInFunction)
}
}
})
}
示例12: ZipUtils
//设置package包名称以及导入依赖的类
package passengersplits.core
import java.io.Closeable
import java.nio.charset.StandardCharsets._
import java.util.zip.{ZipEntry, ZipInputStream}
import scala.collection.JavaConversions._
import scala.collection.mutable.ArrayBuffer
object ZipUtils {
case class UnzippedFileContent( filename: String, content: String, zipFilename: Option[String] = None)
def usingZip[R <: Closeable, T](unzippedStream: R)(f: (R) => T) = {
try {
f(unzippedStream)
} finally {
unzippedStream.close()
}
}
def unzipAllFilesInStream(unzippedStream: ZipInputStream): Stream[UnzippedFileContent] = {
unzipAllFilesInStream(unzippedStream, Option(unzippedStream.getNextEntry))
}
def unzipAllFilesInStream(unzippedStream: ZipInputStream, ze: Option[ZipEntry]): Stream[UnzippedFileContent] = {
ze match {
case None => Stream.empty
case Some(ze) =>
val name: String = ze.getName
val entry: String = ZipUtils.getZipEntry(unzippedStream)
val maybeEntry1: Option[ZipEntry] = Option(unzippedStream.getNextEntry)
UnzippedFileContent(name, entry) #::
unzipAllFilesInStream(unzippedStream, maybeEntry1)
}
}
def getZipEntry(zis: ZipInputStream): String = {
val buffer = new Array[Byte](4096)
val stringBuffer = new ArrayBuffer[Byte]()
var len: Int = zis.read(buffer)
while (len > 0) {
stringBuffer ++= buffer.take(len)
len = zis.read(buffer)
}
val content: String = new String(stringBuffer.toArray, UTF_8)
(content)
}
}
示例13: SSHSession1
//设置package包名称以及导入依赖的类
package com.imaginea.activegrid.core.models
import java.io.Closeable
import com.jcraft.jsch.{ChannelExec, JSch}
case class SSHSession1(serverIp: String,
userName: String,
keyLocation:String,
port: Option[Int],
passPhrase: Option[String],
sessionTimeout: Int = SSHSession1.defaultSessionTimeout
) extends Closeable {
val jsch = new JSch()
val session = jsch.getSession(userName, serverIp)
def executeCommand(command: String): Option[String]={
val channelExec: ChannelExec = session.openChannel("exec").asInstanceOf[ChannelExec]
channelExec.setPty(true)
channelExec.setCommand(command)
getOutputFromChange(channelExec)
}
def start(): Unit={
passPhrase match {
case Some(passPhrase) => jsch.addIdentity(keyLocation, passPhrase)
case None => jsch.addIdentity(keyLocation);
}
session.setTimeout(sessionTimeout)
port.foreach( p => session.setPort(p))
session.connect()
}
def getOutputFromChange(chanelExce: ChannelExec): Option[String] = {
val inputStream = chanelExce.getInputStream()
chanelExce.connect()
if (scala.io.Source.fromInputStream(inputStream).isEmpty) {
None
} else {
Some(scala.io.Source.fromInputStream(inputStream).getLines().mkString("\n"))
}
}
override def close(): Unit = {
this.session.disconnect()
}
}
object SSHSession1{
val defaultSessionTimeout = 15000;
}
示例14: TryWith
//设置package包名称以及导入依赖的类
package berlin.bbdc.inet.flink.netflow
import java.io.Closeable
object TryWith {
def tryWith[C <: Closeable, R](c: C)(function: C => R): R = {
try {
function(c)
} finally {
if (c != null)
c.close()
}
}
}
示例15: using
//设置package包名称以及导入依赖的类
package org.koike.shuji.util
import java.io.Closeable
trait LoanPattern {
def using[A <:Closeable, B](closeable: A)(f: A => B): B = {
try {
f(closeable)
} finally {
closeable.close()
}
}
}
object LoanPattern extends LoanPattern