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

Scala Closeable类代码示例

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

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



在下文中一共展示了Closeable类的17个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
  }
} 
开发者ID:UKHomeOffice,项目名称:drt-passenger-splits,代码行数:50,代码来源:ZipUtils.scala


示例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)
  }
} 
开发者ID:brthanmathwoag,项目名称:jancy,代码行数:31,代码来源:JarClassSource.scala


示例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()
  }
} 
开发者ID:ovotech,项目名称:comms-burrow-polling-lambda,代码行数:41,代码来源:LibratoClient.scala


示例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()
    }
  }
} 
开发者ID:ovotech,项目名称:comms-burrow-polling-lambda,代码行数:15,代码来源:ConnectionHelpers.scala


示例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
} 
开发者ID:getquill,项目名称:play-quill-jdbc,代码行数:38,代码来源:AppLoader.scala


示例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
} 
开发者ID:mindfulmachines,项目名称:unus,代码行数:57,代码来源:AppLoader.scala


示例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()
      }
    }

  }

} 
开发者ID:ThoughtWorksInc,项目名称:Compute.scala,代码行数:44,代码来源:Closeables.scala


示例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)
      }
  }
} 
开发者ID:kafka-web-console,项目名称:service,代码行数:26,代码来源:package.scala


示例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
        }
      }
    }
  }
} 
开发者ID:pico-works,项目名称:pico-event-shim-scalaz,代码行数:55,代码来源:SimpleSinkSource.scala


示例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
  }
} 
开发者ID:pico-works,项目名称:pico-event-shim-scalaz,代码行数:21,代码来源:SinkSource.scala


示例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)
          }
      }
    })
} 
开发者ID:morgen-peschke,项目名称:scala-scraps,代码行数:28,代码来源:TryWith.scala


示例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)
  }
} 
开发者ID:UKHomeOffice,项目名称:drt-scalajs-spa-exploration,代码行数:50,代码来源:ZipUtils.scala


示例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;
} 
开发者ID:eklavya,项目名称:activeGrid,代码行数:54,代码来源:SSHSession1.scala


示例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()
      }
    }
} 
开发者ID:jheyd,项目名称:FlinkNetflow,代码行数:15,代码来源:TryWith.scala


示例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 
开发者ID:shuji-koike,项目名称:scala-util,代码行数:17,代码来源:LoanPattern.scala


示例16: AppLoader

//设置package包名称以及导入依赖的类
import java.io.Closeable
import javax.sql.DataSource

import controllers.EventsController
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.{Events, Users}

class AppLoader extends ApplicationLoader {
  override def load(context: Context): Application = new BuiltInComponentsFromContext(context) with DBComponents with HikariCPComponents {

    lazy val db = new JdbcContext[H2Dialect, SnakeCase](dbApi.database("default").dataSource.asInstanceOf[DataSource with Closeable])


    lazy val users = new Users(db)
    lazy val events = new Events(db)

    lazy val usersController = new UsersController(users)
    lazy val eventsController = new EventsController(events)

    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)
        // Events Routes
      case POST(p"/events") => eventsController.push
      case GET(p"/events/${long(id)}") => eventsController.get(id)
    }

    override lazy val injector: Injector =
      new SimpleInjector(NewInstanceInjector) + users + events + router + cookieSigner + csrfTokenSigner + httpConfiguration + tempFileCreator + global

    Evolutions.applyEvolutions(dbApi.database("default"))

  }.application
} 
开发者ID:a605269,项目名称:play-multitenant,代码行数:45,代码来源:AppLoader.scala


示例17: closing

//设置package包名称以及导入依赖的类
package com.landoop.kafka.ws.utils

import java.io.Closeable

trait Using {
  def closing[T <: AutoCloseable, R](instance: => T)(thunk: T => R): R = {
    val t = instance
    try {
      thunk(t)
    } finally {
      t.close()
    }
  }

  def using[T <: Closeable, R](instance: => T)(thunk: T => R): R = {
    val t = instance
    try {
      thunk(t)
    } finally {
      t.close()
    }
  }
} 
开发者ID:Landoop,项目名称:kafka-ws,代码行数:24,代码来源:Using.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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