当前位置: 首页>>代码示例>>Scala>>正文


Scala ConfigFactory类代码示例

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


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

示例1: Main

//设置package包名称以及导入依赖的类
package onextent.oemap.server

import com.typesafe.scalalogging.LazyLogging

import scala.concurrent.duration._
import akka.actor._
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import akka.util.Timeout
import com.typesafe.config.{Config, ConfigFactory}

object Main extends LazyLogging with App with RestInterface {

  val config: Config = ConfigFactory.load().getConfig("main")
  val logLevel: String = config.getString("logLevel")
  val appName: String = config.getString("appName")
  val host: String = config.getString("host")
  val port: Int = config.getInt("port")

  implicit val system = ActorSystem("map-management-service")
  implicit val materializer = ActorMaterializer()

  implicit val executionContext = system.dispatcher
  implicit val timeout = Timeout(10 seconds)

  val api = routes

  Http().bindAndHandle(handler = api, interface = host, port = port) map {
    binding =>
      logger.info(s"REST interface bound to ${binding.localAddress}")
  } recover {
    case ex =>
      logger.error(s"REST interface could not bind to $host:$port",
                   ex.getMessage)
  }
} 
开发者ID:navicore,项目名称:oemap-server,代码行数:37,代码来源:Main.scala

示例2: CustomApplicationLoader

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

import play.api.ApplicationLoader
import play.api.Configuration
import play.api.inject._
import play.api.inject.guice._
import play.api.ApplicationLoader.Context
import com.typesafe.config.ConfigFactory
import play.api.Mode._
import play.Logger

class CustomApplicationLoader extends GuiceApplicationLoader {

  override protected def builder(context: Context): GuiceApplicationBuilder = {
    val builder = initialBuilder.in(context.environment).overrides(overrides(context): _*)
    context.environment.mode match {
      case Prod => {
        // start mode
        val prodConf = Configuration(ConfigFactory.load("prod.conf"))
        builder.loadConfig(prodConf ++ context.initialConfiguration)
      }
      case Dev => {
        Logger.error("*** Custom Loader DEV****")
        // run mode
        val devConf = Configuration(ConfigFactory.load("dev.conf"))
        builder.loadConfig(devConf ++ context.initialConfiguration)
      }
      case Test => {
        Logger.error("*** Custom Loader TEST ****")
        // test mode
        val testConf = Configuration(ConfigFactory.load("test.conf"))
        builder.loadConfig(testConf ++ context.initialConfiguration)
      }
    }
  }
} 
开发者ID:Driox,项目名称:play-app-seed,代码行数:37,代码来源:CustomApplicationLoader.scala

示例3: JoinInProgressMultiJvmSpec

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

import com.typesafe.config.ConfigFactory
import org.scalatest.BeforeAndAfter
import akka.remote.testkit.MultiNodeConfig
import akka.remote.testkit.MultiNodeSpec
import akka.testkit._
import scala.concurrent.duration._

object JoinInProgressMultiJvmSpec extends MultiNodeConfig {
  val first = role("first")
  val second = role("second")

  commonConfig(
    debugConfig(on = false)
      .withFallback(ConfigFactory.parseString("""
          akka.cluster {
            # simulate delay in gossip by turning it off
            gossip-interval = 300 s
            failure-detector {
              threshold = 4
              acceptable-heartbeat-pause = 1 second
            }
          }""")
        .withFallback(MultiNodeClusterSpec.clusterConfig)))
}

class JoinInProgressMultiJvmNode1 extends JoinInProgressSpec
class JoinInProgressMultiJvmNode2 extends JoinInProgressSpec

abstract class JoinInProgressSpec
  extends MultiNodeSpec(JoinInProgressMultiJvmSpec)
  with MultiNodeClusterSpec {

  import JoinInProgressMultiJvmSpec._

  "A cluster node" must {
    "send heartbeats immediately when joining to avoid false failure detection due to delayed gossip" taggedAs LongRunningTest in {

      runOn(first) {
        startClusterNode()
      }

      enterBarrier("first-started")

      runOn(second) {
        cluster.join(first)
      }

      runOn(first) {
        val until = Deadline.now + 5.seconds
        while (!until.isOverdue) {
          Thread.sleep(200)
          cluster.failureDetector.isAvailable(second) should be(true)
        }
      }

      enterBarrier("after")
    }
  }
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:62,代码来源:JoinInProgressSpec.scala

示例4: Backend

//设置package包名称以及导入依赖的类
package it.codingjam.lagioconda.backend

import akka.actor._
import com.typesafe.config.ConfigFactory
import scala.concurrent.Await
import scala.concurrent.duration.Duration
import collection.JavaConversions._

object Backend extends App {

  // Simple cli parsing
  val port = args match {
    case Array() => "0"
    case Array(port) => port
    case args => throw new IllegalArgumentException(s"only ports. Args [ $args ] are invalid")
  }

  // System initialization
  val properties = Map(
    "akka.remote.netty.tcp.port" -> port
  )

  val system = ActorSystem("application",
                           (ConfigFactory
                             .parseMap(properties))
                             .withFallback(ConfigFactory.load()))

  // Deploy actors and services
  ServiceBackend.startOn(system)

  Await.result(system.whenTerminated, Duration.Inf)
} 
开发者ID:coding-jam,项目名称:lagioconda,代码行数:33,代码来源:Backend.scala

示例5: CreationApplication

//设置package包名称以及导入依赖的类
package sample.remote.calculator

import scala.concurrent.duration._
import com.typesafe.config.ConfigFactory
import scala.util.Random
import akka.actor.ActorSystem
import akka.actor.Props

object CreationApplication {
  def main(args: Array[String]): Unit = {
    if (args.isEmpty || args.head == "CalculatorWorker")
      startRemoteWorkerSystem()
    if (args.isEmpty || args.head == "Creation")
      startRemoteCreationSystem()
  }

  def startRemoteWorkerSystem(): Unit = {
    ActorSystem("CalculatorWorkerSystem", ConfigFactory.load("calculator"))
    println("Started CalculatorWorkerSystem")
  }

  def startRemoteCreationSystem(): Unit = {
    val system =
      ActorSystem("CreationSystem", ConfigFactory.load("remotecreation"))
    val actor = system.actorOf(Props[CreationActor],
      name = "creationActor")

    println("Started CreationSystem")
    import system.dispatcher
    system.scheduler.schedule(1.second, 1.second) {
      if (Random.nextInt(100) % 2 == 0)
        actor ! Multiply(Random.nextInt(20), Random.nextInt(20))
      else
        actor ! Divide(Random.nextInt(10000), (Random.nextInt(99) + 1))
    }

  }
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:39,代码来源:CreationApplication.scala

示例6: FactorialBackend

//设置package包名称以及导入依赖的类
package sample.cluster.factorial

import scala.annotation.tailrec
import scala.concurrent.Future
import com.typesafe.config.ConfigFactory
import akka.actor.Actor
import akka.actor.ActorLogging
import akka.actor.ActorSystem
import akka.actor.Props
import akka.pattern.pipe

//#backend
class FactorialBackend extends Actor with ActorLogging {

  import context.dispatcher

  def receive = {
    case (n: Int) =>
      Future(factorial(n)) map { result => (n, result) } pipeTo sender()
  }

  def factorial(n: Int): BigInt = {
    @tailrec def factorialAcc(acc: BigInt, n: Int): BigInt = {
      if (n <= 1) acc
      else factorialAcc(acc * n, n - 1)
    }
    factorialAcc(BigInt(1), n)
  }

}
//#backend

object FactorialBackend {
  def main(args: Array[String]): Unit = {
    // Override the configuration of the port when specified as program argument
    val port = if (args.isEmpty) "0" else args(0)
    val config = ConfigFactory.parseString(s"akka.remote.netty.tcp.port=$port").
      withFallback(ConfigFactory.parseString("akka.cluster.roles = [backend]")).
      withFallback(ConfigFactory.load("factorial"))

    val system = ActorSystem("ClusterSystem", config)
    system.actorOf(Props[FactorialBackend], name = "factorialBackend")

    system.actorOf(Props[MetricsListener], name = "metricsListener")
  }
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:47,代码来源:FactorialBackend.scala

示例7: Settings

//设置package包名称以及导入依赖的类
// Copyright (c) 2017 Grier Forensics. All Rights Reserved.

package com.grierforensics.greatdane.connector

import java.security.Security

import com.typesafe.config.ConfigFactory
import org.bouncycastle.jce.provider.BouncyCastleProvider

object Settings {

  private val config = {
    val cfg = ConfigFactory.load()
    cfg.getConfig("com.grierforensics.greatdane.connector")
  }

  // This must occur once, so this is a logical place to do it
  val SecurityProvider = new BouncyCastleProvider
  Security.addProvider(SecurityProvider)

  val Host: String = config.getString("host")
  val Port: Int = config.getInt("port")
  val ApiKey: String = config.getString("apiKey")

  case class ZoneFileDetails(origin: String, baseFile: String, outFile: String,
                             ttl: Long, writePeriod: Int)

  val ManageZone: Boolean = config.getBoolean("manageZone")

  val Zone = ZoneFileDetails(
    config.getString("zone.origin"),
    config.getString("zone.basefile"),
    config.getString("zone.outfile"),
    config.getLong("zone.ttl"),
    config.getInt("zone.write.period")
  )

  case class GeneratorDetails(keyAlgo: String, keyBits: Int, selfSign: Boolean,
                              signingKey: String, signingCert: String, signingAlgo: String,
                              expiryDays: Int)

  private val certs = config.getConfig("certificates")
  val Generator: Option[GeneratorDetails] = if (certs.getBoolean("generate")) {
    Some(
      GeneratorDetails(
        certs.getString("key.algorithm"),
        certs.getInt("key.bits"),

        certs.getBoolean("selfSign"),

        certs.getString("signing.key"),
        certs.getString("signing.certificate"),
        certs.getString("signing.algorithm"),

        certs.getInt("expiry.days")
      )
    )
  } else {
    None
  }
} 
开发者ID:grierforensics,项目名称:Great-DANE-Connector,代码行数:62,代码来源:Settings.scala

示例8: Config

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

import java.net.InetAddress

import com.datastax.driver.core.Cluster
import com.typesafe.config.ConfigFactory
import com.websudos.phantom.connectors.{KeySpace, SessionProvider}
import com.websudos.phantom.dsl.Session

import scala.collection.JavaConversions._



object Config {
  val config = ConfigFactory.load()

}

trait DefaultsConnector extends SessionProvider {
  val config = ConfigFactory.load()
  implicit val space: KeySpace = DataConnection.keySpace
  val cluster = DataConnection.cluster
  override implicit lazy val session: Session = DataConnection.session
}

object DataConnection {
  val config = ConfigFactory.load()
  val hosts: Seq[String] = Config.config.getStringList("cassandra.host").toList
  val inets = hosts.map(InetAddress.getByName)
  val keySpace: KeySpace = KeySpace(Config.config.getString("cassandra.keyspace"))
  val cluster =
    Cluster.builder()
      .addContactPoints(inets)
      .withClusterName(Config.config.getString("cassandra.cluster"))
//      .withCredentials(config.getString("cassandra.username"), config.getString("cassandra.password"))
      .build()
  val session: Session = cluster.connect(keySpace.name)
} 
开发者ID:Masebeni,项目名称:hwork,代码行数:39,代码来源:Connection.scala

示例9: Settings

//设置package包名称以及导入依赖的类
// Copyright (C) 2016 Grier Forensics. All Rights Reserved.

package com.grierforensics.greatdane

import com.typesafe.config.ConfigFactory

object Settings {
  import scala.collection.JavaConverters._

  val config = {
    val cfg = ConfigFactory.load()
    cfg.getConfig("com.grierforensics.greatdane.engine")
  }

  object Default {
    val Port = config.getInt("port")
    val DnsServers = config.getStringList("dns").asScala
  }
} 
开发者ID:grierforensics,项目名称:Great-DANE-Engine,代码行数:20,代码来源:Settings.scala

示例10: config

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

import java.io.File
import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory
import collection.JavaConversions._

object config {
  private val _config = {
    val _default = ConfigFactory.load("default")
    val _fallback = _default.getStringList("Config.Fallback").map(
      file => new File(file)
    ).filter( file => file.exists() && file.isFile() ).map( file => {
      val parseFile = ConfigFactory.parseFile(file)
      ConfigFactory.load(parseFile)
    })

    if( _fallback.length > 0 ) {
      _fallback.reduce( _.withFallback(_) ).withFallback( _default )
    } else {
      _default
    }
  }

  def getBoolean(_c:String):Boolean = {
    _config.getBoolean(_c)
  }

  def getString(_c:String):String = {
    _config.getString(_c)
  }

  def getStringList(_c:String):List[String] = {
    _config.getStringList(_c).toList
  }

  def getInt(_c:String):Int = {
    _config.getInt(_c)
  }

  def getLong(_c:String):Long= {
    _config.getLong(_c)
  }

  def getDouble(_c:String):Double = {
    _config.getDouble(_c)
  }

  def getConfig(_c:String):Config = {
    _config.getConfig(_c)
  }
} 
开发者ID:janzhou,项目名称:approxssd,代码行数:53,代码来源:Config.scala

示例11: memory

//设置package包名称以及导入依赖的类
package org.janzhou.nvmr.pmemory

import java.io.File
import com.typesafe.config.ConfigFactory
import collection.JavaConversions._


object memory {
  private val file = new File("src/main/resources/applications.conf")
  private val config = {
    if( file.exists() && file.isFile() ) {
      val parseFile = ConfigFactory.parseFile(file)
      ConfigFactory.load(parseFile)
    } else {
      ConfigFactory.load()
    }
  }
  private val workdir = config.getString("pmemory.workdir")
  val plogs = config.getStringList("pmemory.devices").toList.map(dev => new Plog(workdir + "/" + dev))

  val plog = plogs(0)
  val logs = plogs
} 
开发者ID:janzhou,项目名称:approxssd,代码行数:24,代码来源:Memory.scala

示例12: Lambda

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

import java.io.{Closeable, InputStreamReader}
import java.util.{Map => JMap}

import collection.JavaConverters._
import com.amazonaws.services.lambda.runtime.{Context, RequestHandler}
import com.amazonaws.services.s3.AmazonS3Client
import com.ovoenergy.lambda.client.{KafkaMetricsClient, LibratoClient}
import com.ovoenergy.lambda.domain.{ConsumerGroupMetricResponse, KafkaMetrics, PartitionData}
import com.squareup.okhttp.OkHttpClient
import com.typesafe.config.ConfigFactory

class Lambda extends RequestHandler[JMap[String, Object], Unit] with ConnectionHelpers{

  val s3Client = new AmazonS3Client

  override def handleRequest(event: JMap[String, Object], context: Context): Unit = {
    val environment = context.getFunctionName.split('-').last
    println(s"Hello, I'm a Lambda running in the $environment environment")

    val config = using(s3Client.getObject("ovo-comms-platform-config", s"comms-burrow-polling-lambda/$environment/application.conf")){ s3Obj =>
      using(new InputStreamReader(s3Obj.getObjectContent)){ configReader =>
        ConfigFactory.parseReader(configReader)
      }
    }

    val libratoEmail  = config.getString("librato.api.email")
    val libratoToken  = config.getString("librato.api.token")
    val libratoUrl    = config.getString("librato.api.url")
    val kafkaMetricsUrl = config.getString("kafka.metrics.url")
    val kafkaConsumerGroups   = config.getStringList("kafka.metrics.consumerGroups").asScala
    val httpClient    = new OkHttpClient()
    val metricsClient = new KafkaMetricsClient(kafkaMetricsUrl, "local", kafkaConsumerGroups, httpClient)
    val metrics       = metricsClient.getMetrics.map(genKafkaMetrics)

    using(new LibratoClient(libratoEmail, libratoToken, libratoUrl, environment)){ libratoClient =>
      metrics.foreach { metric =>
        libratoClient.addMetrics(metric)
      }
      libratoClient.submitMetrics()
    }
  }

  private def genKafkaMetrics(response :ConsumerGroupMetricResponse): KafkaMetrics = {
    val partitionData = response.status.partitions.map { partition =>
      PartitionData(partition.partition, partition.end.lag)
    }
    KafkaMetrics(response.status.group, partitionData)
  }
} 
开发者ID:ovotech,项目名称:comms-burrow-polling-lambda,代码行数:52,代码来源:Lambda.scala

示例13: Application

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

import java.io.File

import akka.actor.{Props, ActorSystem}
import com.sksamuel.scrimage.Image
import com.typesafe.config.ConfigFactory
import com.ulasakdeniz.image.{ImageUtil, ImageWriter}
import com.ulasakdeniz.kmeans.{Start, Processor}

object Application extends App {

  val config = ConfigFactory.load("concurrency")
  val system = ActorSystem("actor-system", config)

  val projectDirectory = System.getProperty("user.dir")
  val imagePath = s"$projectDirectory/image/wall-e.png"
  val imagePathToWrite = s"$projectDirectory/image/wall-e-clustered.png"
  val image = Image.fromFile(new File(imagePath))
  val imageDataList = ImageUtil.pixelDataList(image)

  val imageWriter = new ImageWriter(image.dimensions, imagePathToWrite)

  val k = 16
  val totalIteration = 50

  val kMeansProcessor = system.actorOf(Props(classOf[Processor], imageDataList, k, totalIteration, imageWriter), "processor")
  kMeansProcessor ! Start
} 
开发者ID:ulasakdeniz,项目名称:kmeans-akka,代码行数:30,代码来源:Application.scala

示例14: Server

//设置package包名称以及导入依赖的类
package net.ruippeixotog.scalafbp

import akka.actor.{ ActorSystem, Props }
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives._
import akka.stream.{ ActorMaterializer, ActorMaterializerSettings, Supervision }
import com.typesafe.config.ConfigFactory

import net.ruippeixotog.scalafbp.http._
import net.ruippeixotog.scalafbp.protocol.MainProtocolActor
import net.ruippeixotog.scalafbp.runtime.{ ComponentLoader, ComponentRegistry, GraphStore }

object Server extends App with WsRuntimeHttpService with RegisterHttpService with RegistryHttpService
    with UiHttpService {

  implicit val system = ActorSystem()
  implicit val ec = system.dispatcher

  val decider: Supervision.Decider = { e =>
    log.error("Unhandled exception in stream", e)
    Supervision.Stop
  }

  implicit val materializer = ActorMaterializer(
    ActorMaterializerSettings(system).withSupervisionStrategy(decider))

  val config = ConfigFactory.load.getConfig("scalafbp")
  val registryConfig = config.getConfig("registry")
  val runtimeConfig = config.getConfig("runtime")

  val runtimeId = config.getString("runtime-id")
  val secret = config.getString("secret")

  val host = config.getString("host")
  val port = config.getInt("port")

  val disableUi = config.getBoolean("disable-ui")

  // the registry of components that will be made available to clients
  val compRegistry = system.actorOf(ComponentRegistry.props(ComponentLoader.allInClasspath))

  // an object responsible for storing and managing the graph definitions currently in the runtime
  val graphStore = system.actorOf(Props(new GraphStore))

  // actor that receives incoming messages (as `Message` objects) and translates them into actions using the above
  // constructs
  val protocolActor = system.actorOf(Props(
    new MainProtocolActor(runtimeId, secret, compRegistry, graphStore, runtimeConfig)))

  // all the routes offered by this server
  val routes = registrationRoutes ~ registryRoutes ~ wsRuntimeRoutes ~ uiRoutes

  Http().bindAndHandle(routes, host, port).foreach { binding =>
    log.info(s"Bound to ${binding.localAddress}")
    onBind(binding)
  }
} 
开发者ID:ruippeixotog,项目名称:scalafbp,代码行数:58,代码来源:Server.scala

示例15: CmdConfig

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

import java.io.File

import com.typesafe.config.{Config, ConfigFactory}


case class CmdConfig(out: String = ".",
                     records: Int = 1,
                     datasetConfig: Option[Config] = None,
                     jsonTemplate: File = new File("template.json"))

object CmdParser {
  val parser = new scopt.OptionParser[CmdConfig]("fastgen") {
    head("fastgen", "0.2.1")

    //Option for getting the template as a sample format. Currently only supports json
    opt[File]("template")
      .required()
      .valueName("<template>")
      .action((x, c) => c.copy(jsonTemplate = x))
      .text("Template file path.")

    //Option for saving the output
    opt[String]("out")
      .valueName("<uri>")
      .action((x, c) => c.copy(out = x))
      .text("Output URI")

    //Option for reading the dataset configuration path
    opt[File]("config")
      .valueName("<config>")
      .action(
        (x, c) => c.copy(datasetConfig = Some(ConfigFactory.parseFile(x))))
      .text("Data set configuration file path")

    //Option for number of records
    opt[Int]("rows")
      .required()
      .valueName("<# records>")
      .action((x, c) => c.copy(records = x))
      .text("Number of samples to be generated.")

    help("help").text("Prints the usage.")

    override def showUsageOnError: Boolean = true
  }

}

object Main extends App {
  println("Hello World")
} 
开发者ID:amezng,项目名称:fastgen,代码行数:54,代码来源:CmdConfig.scala


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