本文整理汇总了Scala中scala.util.Properties类的典型用法代码示例。如果您正苦于以下问题:Scala Properties类的具体用法?Scala Properties怎么用?Scala Properties使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Properties类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: Util
//设置package包名称以及导入依赖的类
package org.hammerlab.test.version
import scala.util.Properties
object Util {
// cf. http://www.scala-lang.org/old/node/7532.html#comment-31160.
lazy val version: String =
Properties.scalaPropOrNone("version.number") match {
case Some(versionNumber) => versionNumber
case None => throw new Exception("No Scala 'version.number' property set")
}
lazy val versionPrefix = {
if (version.startsWith("2.10")) "2.10"
else if (version.startsWith("2.11")) "2.11"
else if (version.startsWith("2.12")) "2.12"
else throw new Exception(s"Unrecognized Scala version: $version")
}
lazy val is2_10 = versionPrefix == "2.10"
lazy val is2_11 = versionPrefix == "2.11"
lazy val is2_12 = versionPrefix == "2.12"
}
示例2: ProjectPlugin
//设置package包名称以及导入依赖的类
import scala.util.Properties
import sbt._
import sbt.Keys._
object ProjectPlugin extends AutoPlugin {
override def requires = net.cakesolutions.CakePlatformPlugin
override def trigger = allRequirements
val autoImport = ProjectPluginKeys
import autoImport._
// NOTE: everything in here is applied once, to the entire build
override val buildSettings = Seq(
organization := "net.cakesolutions",
scalaVersion := "2.12.2",
maxErrors := 1,
fork := true,
cancelable := true,
sourcesInBase := false,
javaOptions += s"-Dcake.sbt.root=${(baseDirectory in ThisBuild).value.getCanonicalFile}",
// WORKAROUND https://github.com/dwijnand/sbt-dynver/issues/23
version := {
val v = version.value
if (!v.contains("+")) v
else v + "-SNAPSHOT"
},
concurrentRestrictions := {
val limited = Properties.envOrElse("SBT_TASK_LIMIT", "4").toInt
Seq(Tags.limitAll(limited))
}
)
// NOTE: everything in here is applied to every project (a better `commonSettings`)
override val projectSettings = Seq(
scalacOptions in (Compile, console) := Seq()
)
}
object ProjectPluginKeys {
// NOTE: anything in here is automatically visible in build.sbt
}
示例3: Of
//设置package包名称以及导入依赖的类
package astraea.spark
import geotrellis.spark.testkit.{TestEnvironment => GeoTrellisTestEnvironment}
import org.apache.spark.SparkContext
import org.apache.spark.serializer.KryoSerializer
import org.apache.spark.sql.{SQLContext, SparkSession}
import org.scalatest._
import scala.util.Properties
trait TestEnvironment extends GeoTrellisTestEnvironment { self: Suite with BeforeAndAfterAll ?
val _spark: SparkSession = {
System.setProperty("spark.driver.port", "0")
System.setProperty("spark.hostPort", "0")
System.setProperty("spark.ui.enabled", "false")
val session = SparkSession.builder()
.master("local")
.appName("Test Context")
.getOrCreate()
// Shortcut out of using Kryo serialization if we want to test against
// java serialization.
if(Properties.envOrNone("GEOTRELLIS_USE_JAVA_SER").isEmpty) {
val conf = session.sparkContext.getConf
conf
.set("spark.serializer", classOf[KryoSerializer].getName)
.set("spark.kryoserializer.buffer.max", "500m")
.set("spark.kryo.registrationRequired", "false")
setKryoRegistrator(conf)
}
System.clearProperty("spark.driver.port")
System.clearProperty("spark.hostPort")
System.clearProperty("spark.ui.enabled")
session
}
override implicit def sc: SparkContext = _spark.sparkContext
lazy val sql: SQLContext = _spark.sqlContext
}
示例4: ProxyConfiguration
//设置package包名称以及导入依赖的类
package net.furikuri.cproxy.client
import scala.util.Properties
object ProxyConfiguration {
def targetHost(): String = {
Properties.envOrElse("CPROXY_TARGET_HOST", "localhost")
}
def targetPort(): Int = {
Properties.envOrElse("CPROXY_TARGET_PORT", "8080").toInt
}
def serverHost(): String = {
Properties.envOrElse("CPROXY_SERVER_HOST", "localhost")
}
def serverPort(): Int = {
Properties.envOrElse("CPROXY_SERVER_PORT", "4444").toInt
}
}
示例5: Web
//设置package包名称以及导入依赖的类
import java.io.File
import java.util
import java.util.Locale
import javax.servlet.DispatcherType
import org.eclipse.jetty.server.Server
import org.eclipse.jetty.servlet.FilterHolder
import org.eclipse.jetty.util.resource.{Resource, ResourceCollection}
import org.eclipse.jetty.webapp.WebAppContext
import refpay.RefPayPlan
import unfiltered.filter.Plan
import scala.util.Properties
object Web extends App{
Locale.setDefault(new Locale("no_NO"))
val port = Properties.envOrElse("PORT", "9998").toInt
val resources = new ResourceCollection(
Resource.newResource(new File("src/main/webapp"))
)
val server = new Server(port)
val context = new WebAppContext()
// context.setContextPath("/api")
context.setBaseResource(resources)
registerPlan(new RefPayPlan, "Dommerbetaling", context)
server.setHandler(context)
server.setSendDateHeader(true)
server.setStopAtShutdown(true)
server.start()
def registerPlan(plan: Plan, name: String, context: WebAppContext) {
val holder = new FilterHolder(plan)
holder.setName(name)
context.addFilter(holder, "/*", util.EnumSet.of(DispatcherType.REQUEST,DispatcherType.ASYNC,DispatcherType.ERROR,DispatcherType.FORWARD,DispatcherType.INCLUDE))
}
}
示例6: Server
//设置package包名称以及导入依赖的类
package simple
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.directives.FileAndResourceDirectives.getFromResourceDirectory
import akka.stream.ActorMaterializer
import service.MongoQueryParser
import service.MongoService
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.Properties
object Server {
val mongoService = new MongoService(new MongoQueryParser())
def main(args: Array[String]): Unit = {
implicit val system = ActorSystem()
implicit val materializer = ActorMaterializer()
val port = Properties.envOrElse("PORT", "8080").toInt
val route = {
get {
pathSingleSlash {
complete {
HttpEntity(
ContentTypes.`text/html(UTF-8)`,
Page.skeleton.render
)
}
} ~
getFromResourceDirectory("")
} ~
post {
path("mongo" / "data") {
entity(as[String]) { query =>
complete {
upickle.default.write(mongoService.executeQuery(query))
}
}
}
}
}
Http().bindAndHandle(route, "0.0.0.0", port = port)
}
}
示例7: WeatherService
//设置package包名称以及导入依赖的类
package services
import javax.inject.{Inject, Singleton}
import models.{FindWeatherResponse}
import play.api.libs.json.Json
import play.api.libs.ws._
import scala.concurrent._
import scala.util.Properties
import play.api.libs.json.JsValue
@Singleton
class WeatherService (ws: WSClient, baseUrl: String)(implicit ec: ExecutionContext) {
@Inject() def this(ws: WSClient, ec: ExecutionContext) = this(ws, "http://api.openweathermap.org")(ec)
val API_KEY: String = Properties.envOrElse("WEATHER_API_KEY", "WEATHER_API_KEY")
def getWeather(city: String): Future[WSResponse] = {
val url = s"$baseUrl/data/2.5/weather?q=$city&appid=$API_KEY&units=metric"
ws.url(url).get()
}
def getWeatherList(city: String): Future[WSResponse] = {
val url = s"$baseUrl/data/2.5/find?q=$city&appid=$API_KEY&units=metric&type=like"
ws.url(url).get()
}
def getWeatherForCity(city: String): Future[JsValue] = {
getWeatherList(city).map(response => {
val resp = Json.parse(response.body)
val jsresp = resp.validate[FindWeatherResponse]
jsresp.fold(
err => Json.obj("error" -> err.toString()),
list => Json.toJson(list.list)
)
})
}
}
示例8: WeatherForecastService
//设置package包名称以及导入依赖的类
package services
import javax.inject.{Inject, Singleton}
import scala.concurrent._
import scala.util.Properties
import play.api.libs.json.Json
import play.api.libs.ws._
import play.api.libs.json.JsValue
import models.{WeatherForecast, WeatherForecastResponse}
import utils.WeatherUtils
@Singleton
class WeatherForecastService (ws: WSClient, baseUrl: String)(implicit ec: ExecutionContext) {
@Inject() def this (ws: WSClient, ec: ExecutionContext) = this(ws, "http://api.openweathermap.org")(ec)
val API_KEY: String = Properties.envOrElse("WEATHER_API_KEY", "WEATHER_API_KEY")
def getForecastByCityID(cityID: String): Future[WSResponse] = {
val url = s"$baseUrl/data/2.5/forecast?id=$cityID&appid=$API_KEY&units=metric"
ws.url(url).get()
}
def getForecastByCityName(cityName: String): Future[WSResponse] = {
val url = s"$baseUrl/data/2.5/forecast?q=$cityName&appid=$API_KEY&units=metric"
ws.url(url).get()
}
def getForecastForCityByID(id: String): Future[JsValue] = {
val forecastFuture = getForecastByCityID(id)
forecastFuture.map(response => {
val resp = Json.parse(response.body)
val jsresp = resp.validate[WeatherForecastResponse]
jsresp.fold(
err => Json.obj("error" -> err.toString()),
forecast => {
val daily = WeatherUtils.getDailyWeather(forecast)
val result = WeatherForecast(
forecast.cod,
forecast.message,
forecast.cnt,
forecast.list,
forecast.city,
daily
)
Json.toJson(result)
}
)
})
}
}
示例9: Main
//设置package包名称以及导入依赖的类
package me.snov.sns
import akka.actor.ActorSystem
import akka.event.{Logging, LoggingAdapter}
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server._
import akka.stream.ActorMaterializer
import akka.util.Timeout
import com.typesafe.config.ConfigFactory
import me.snov.sns.actor._
import me.snov.sns.api._
import me.snov.sns.service.DbService
import me.snov.sns.util.ToStrict
import scala.concurrent.ExecutionContext
import scala.concurrent.duration._
import scala.util.Properties
object Main extends App with ToStrict {
implicit val system = ActorSystem("sns")
implicit val executor: ExecutionContext = system.dispatcher
implicit val materializer: ActorMaterializer = ActorMaterializer()
implicit val logger: LoggingAdapter = Logging(system, getClass)
implicit val timeout = new Timeout(1.second)
val config = ConfigFactory.load()
val dbService = new DbService(Properties.envOrElse("DB_PATH", config.getString("db.path")))
val dbActor = system.actorOf(DbActor.props(dbService), name = "DbActor")
val homeActor = system.actorOf(HomeActor.props, name = "HomeActor")
val subscribeActor = system.actorOf(SubscribeActor.props(dbActor), name = "SubscribeActor")
val publishActor = system.actorOf(PublishActor.props(subscribeActor), name = "PublishActor")
val routes: Route =
toStrict {
TopicApi.route(subscribeActor) ~
SubscribeApi.route(subscribeActor) ~
PublishApi.route(publishActor) ~
HealthCheckApi.route ~
HomeApi.route(homeActor)
}
Http().bindAndHandle(
handler = logRequestResult("akka-http-sns")(routes),
interface = Properties.envOrElse("HTTP_INTERFACE", config.getString("http.interface")),
port = Properties.envOrElse("HTTP_PORT", config.getString("http.port")).toInt
)
}
示例10: DatabaseConfig
//设置package包名称以及导入依赖的类
package functional
import play.api.db.{Database, Databases}
import scala.util.Properties
object DatabaseConfig {
val url = Properties.envOrElse("PLAY_PRODUCT_DB_TEST_URL", "jdbc:postgresql://localhost:15432/product-test")
val username = Properties.envOrElse("PLAY_PRODUCT_DB_TEST_USERNAME", "root")
val password = Properties.envOrElse("PLAY_PRODUCT_DB_TEST_PASSWORD", "localhost")
val database = Databases(
driver = "org.postgresql.Driver",
url = url,
name = "Product-Test",
config = Map(
"username" -> username,
"password" -> password,
"logStatements" -> true
)
)
def withDatabase[T](block: Database => T): T = {
Databases.withDatabase(
driver = "org.postgresql.Driver",
url = url,
name = "Product-Test",
config = Map(
"username" -> username,
"password" -> password,
"logStatements" -> true
)
)(block)
}
}
示例11: RedisService
//设置package包名称以及导入依赖的类
package services
import java.net.URI
import com.github.scribejava.core.model.OAuth1AccessToken
import com.redis.RedisClient
import models.{DraftPick, Player}
import play.api.libs.json.{JsArray, Json}
import v1.JSParsers._
import scala.util.{Properties, Try}
object RedisService {
// val redis = if(System.getenv("heroku") == null) new RedisClient("localhost", 6379) else new RedisClient("redis://h:p9[email protected]ec2-34-198-124-158.compute-1.amazonaws.com", 40769)
val redis = Properties.envOrNone("REDIS_URL") match {
case Some(redisUrl) =>
val redisUri = new URI(redisUrl)
val host = redisUri.getHost
val port = redisUri.getPort
val secret = Try(redisUri.getUserInfo.split(":",2).last).toOption
new RedisClient(host, port, secret = secret)
case _ => new RedisClient("localhost", 6379)
}
def checkDraftResults(oAuth1AccessToken: OAuth1AccessToken): Seq[DraftPick] = {
if(redis.get("363.l.63462_draft").isDefined) Json.parse(redis.get("363.l.63462_draft").get).as[JsArray].value.map(_.as[DraftPick]) else new YahooOauthService().updateLeagueDraft(oAuth1AccessToken)
}
def getPlayerRankings(oAuth1AccessToken: OAuth1AccessToken): Seq[Player] = {
if(redis.get("363.l.63462").isDefined) Json.parse(redis.get("363.l.63462").get).as[JsArray].value.map(_.as[Player]) else new YahooOauthService().updatePlayerRankings(oAuth1AccessToken)
}
}
示例12: StartFramework
//设置package包名称以及导入依赖的类
package com.bwsw.sj.mesos.framework
import com.bwsw.sj.mesos.framework.rest.Rest
import com.bwsw.sj.mesos.framework.schedule.FrameworkScheduler
import com.bwsw.sj.common.DAL.repository.ConnectionRepository
import com.bwsw.sj.common.utils.ConfigLiterals
import org.apache.mesos.MesosSchedulerDriver
import org.apache.mesos.Protos.FrameworkInfo
import org.apache.mesos.Protos.Credential
import scala.util.Properties
object StartFramework {
def main(args: Array[String]): Unit = {
val port = if (args.nonEmpty) args(0).toInt else 8080
Rest.start(port)
val framework = FrameworkInfo.newBuilder.
setName("JugglerFramework").
setUser("root").
setCheckpoint(false).
setFailoverTimeout(0.0d).
setRole("*").
setPrincipal("sherman").
build()
val frameworkPrincipal = ConnectionRepository.getConfigService.get(ConfigLiterals.frameworkPrincipalTag)
val frameworkSecret = ConnectionRepository.getConfigService.get(ConfigLiterals.frameworkSecretTag)
var credential: Option[Credential] = None
if (frameworkPrincipal.isDefined && frameworkSecret.isDefined) {
credential = Some(Credential.newBuilder.
setPrincipal(frameworkPrincipal.get.value).
setSecret(frameworkSecret.get.value).
build())
}
val scheduler = new FrameworkScheduler
val master_path = Properties.envOrElse("MESOS_MASTER", "zk://127.0.0.1:2181/mesos")
val driver: MesosSchedulerDriver = {
if (credential.isDefined) new MesosSchedulerDriver(scheduler, framework, master_path, credential.get)
else new MesosSchedulerDriver(scheduler, framework, master_path)
}
driver.start()
driver.join()
}
}
示例13: retrieveTweets
//设置package包名称以及导入依赖的类
package services
import javax.inject.Singleton
import twitter4j.conf.ConfigurationBuilder
import twitter4j._
import play.api.Logger
import collection.JavaConverters._
import scala.collection.mutable.ListBuffer
import scala.util.Properties
trait TwitterConnection {
val MaxTweets = 2000
val FirstPage = 1
def retrieveTweets(handle: String, limit: Int): Seq[Status]
}
@Singleton
class TwitterConnectionImpl extends TwitterConnection{
def retrieveTweets(handle: String, total: Int): Seq[Status] = {
val limit = math.min(total, MaxTweets)
var page = FirstPage
val tweets = ListBuffer.empty[Status]
tweets.++=(fetchTweets(handle, page, limit))
while(tweets.size < limit) {
page += 1
tweets.++=(fetchTweets(handle, page, limit))
}
return tweets
}
private def fetchTweets(handle: String, page: Int, limit: Int): Seq[Status] = {
val cb = new ConfigurationBuilder()
cb.setDebugEnabled(true)
.setOAuthConsumerKey(Properties.envOrElse("consumerKey", sys.props("consumerKey")))
.setOAuthConsumerSecret(Properties.envOrElse("consumerSecret", sys.props("consumerSecret")))
.setOAuthAccessToken(Properties.envOrElse("accessToken", sys.props("accessToken")))
.setOAuthAccessTokenSecret(Properties.envOrElse("accessTokenSecret", sys.props("accessTokenSecret")))
val tf = new TwitterFactory(cb.build())
val twitter = tf.getInstance()
return twitter.getUserTimeline(handle, new Paging(page, limit)).asScala
}
}
示例14: Dependencies
//设置package包名称以及导入依赖的类
import scala.util.Properties
import sbt._
object Dependencies {
def either(environmentVariable: String, default: String): String =
Properties.envOrElse(environmentVariable, default)
private val sprayVersion = Properties.envOrElse("SPRAY_VERSION", "1.3.3")
// Cloudera's distribution of Spark 1.5 is built with Akka 2.2.x,
// as opposed to the official release, which is built with Akka 2.3.x.
// We need to have the spray version match the Akka version of Spark
// or else MethodNotFound pain will ensue.
val sprayRouting =
if(sprayVersion == "1.2.3") {
"io.spray" % "spray-routing" % sprayVersion
} else {
"io.spray" %% "spray-routing" % sprayVersion
}
val sprayCan =
if(sprayVersion == "1.2.3") {
"io.spray" % "spray-can" % sprayVersion
} else {
"io.spray" %% "spray-can" % sprayVersion
}
}
示例15: GooglePlacesClientSingleton
//设置package包名称以及导入依赖的类
package clients
import com.google.maps.{DistanceMatrixApi, GeoApiContext, GeocodingApi}
import com.google.maps.model.{AddressComponent, AddressComponentType, Distance, Unit}
import exceptions.InvalidZipException
import models.AddressResult
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.util.Properties
object GooglePlacesClientSingleton extends GooglePlacesClient {
val apiKey: String = Properties.envOrElse("GOOGLE_API_KEY", "")
override val context: GeoApiContext = new GeoApiContext().setApiKey(apiKey)
}
trait GooglePlacesClient {
val context: GeoApiContext
def getDistance(origin: String, destination: String): Future[Distance] = {
Future {
DistanceMatrixApi.newRequest(context)
.destinations(destination)
.origins(origin)
.units(Unit.IMPERIAL)
.await
.rows(0)
.elements(0)
.distance
}
}
def getAddress(address: String): Future[AddressResult] = {
Future {
val resolvedAddress = GeocodingApi.geocode(context, address).await()(0)
val postalCode = getPostalCodeFromComponents(resolvedAddress.addressComponents)
AddressResult(
originalQuery = address,
formattedAddress = resolvedAddress.formattedAddress,
postalCode = postalCode
)
}
}
def getPostalCodeFromComponents(components: Array[AddressComponent]): String = {
val zips = for {
component <- components.filter(_.types.contains(AddressComponentType.POSTAL_CODE))
zip = component.longName
} yield zip
zips match {
case Array(zip: String) => zip
case _ => throw new InvalidZipException("Unable to determine zip")
}
}
}