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

Scala Properties类代码示例

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

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



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


示例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
} 
开发者ID:cakesolutions,项目名称:strictify,代码行数:44,代码来源:ProjectPlugin.scala


示例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
} 
开发者ID:s22s,项目名称:avro2spark,代码行数:45,代码来源:TestEnvironment.scala


示例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
  }
} 
开发者ID:FuriKuri,项目名称:cloud-proxy,代码行数:22,代码来源:ProxyConfiguration.scala


示例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))
  }
} 
开发者ID:magott,项目名称:refpay,代码行数:43,代码来源:Web.scala


示例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)
  }
} 
开发者ID:dougsleite,项目名称:oak,代码行数:49,代码来源:Server.scala


示例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)
      )
    })
  }
} 
开发者ID:malaman,项目名称:scala-weather-app,代码行数:40,代码来源:WeatherService.scala


示例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)
        }
      )
    })
  }
} 
开发者ID:malaman,项目名称:scala-weather-app,代码行数:53,代码来源:WeatherForecastService.scala


示例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
  )
} 
开发者ID:s12v,项目名称:sns,代码行数:50,代码来源:Main.scala


示例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)
  }
} 
开发者ID:jasoet,项目名称:play-product-example,代码行数:37,代码来源:DatabaseConfig.scala


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

} 
开发者ID:cregg,项目名称:flhserver,代码行数:36,代码来源:RedisService.scala


示例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()
  }
} 
开发者ID:bwsw,项目名称:sj-platform,代码行数:53,代码来源:StartFramework.scala


示例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
  }
} 
开发者ID:felipecao,项目名称:top10hashtags,代码行数:52,代码来源:TwitterConnection.scala


示例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
    }
} 
开发者ID:geotrellis,项目名称:geotrellis-osm-elevation,代码行数:29,代码来源:Dependencies.scala


示例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")
    }
  }
} 
开发者ID:greghxc,项目名称:shakespeare,代码行数:57,代码来源:GooglePlacesClient.scala


示例16: ApiModule

//设置package包名称以及导入依赖的类
package org.globalnames
package index
package api

import com.google.inject.{Provides, Singleton}
import com.twitter.app.Flag
import com.twitter.finagle.ThriftMux
import com.twitter.inject.TwitterModule
import thrift.nameresolver.{Service => NameResolverService}

import scala.util.Properties

object ApiModule extends TwitterModule {
  val nameresolverServiceAddress: Flag[String] = flag(
    name = "nameresolverServiceAddress",
    help = "Host and port of nameresolver service",
    default = Properties.envOrElse("NAMERESOLVER_ADDRESS", "")
  )

  @Singleton
  @Provides
  def provideNameResolverClient: NameResolverService.FutureIface =
    ThriftMux.client.newIface[NameResolverService.FutureIface](nameresolverServiceAddress())

} 
开发者ID:GlobalNamesArchitecture,项目名称:gnindex,代码行数:26,代码来源:ApiModule.scala


示例17: NameResolverModule

//设置package包名称以及导入依赖的类
package org.globalnames
package index
package nameresolver

import com.google.inject.{Provides, Singleton}
import com.twitter.app.Flag
import com.twitter.finagle.ThriftMux
import com.twitter.inject.TwitterModule
import thrift.matcher.{Service => MatcherService}
import slick.jdbc.PostgresProfile.api._
import scala.util.Properties

object NameResolverModule extends TwitterModule {
  val matcherServiceAddress: Flag[String] = flag(
    name = "matcherServiceAddress",
    help = "Host and port of matcher service",
    default = Properties.envOrElse("MATCHER_ADDRESS", "")
  )

  @Singleton
  @Provides
  def provideDatabase: Database = {
    val host = Properties.envOrElse("DB_HOST", "localhost")
    val port = Properties.envOrElse("DB_PORT", "5432")
    val database = Properties.envOrElse("DB_DATABASE", "development")
    val url = s"jdbc:postgresql://$host:$port/$database"
    Database.forURL(
      url = url,
      user = Properties.envOrElse("DB_USER", "postgres"),
      password = Properties.envOrElse("DB_USER_PASS", ""),
      driver = "org.postgresql.Driver"
    )
  }

  @Singleton
  @Provides
  def provideMatcherClient: MatcherService.FutureIface =
    ThriftMux.client.newIface[MatcherService.FutureIface](matcherServiceAddress())

} 
开发者ID:GlobalNamesArchitecture,项目名称:gnindex,代码行数:41,代码来源:NameResolverModule.scala


示例18: Config

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

import scala.util.Properties

object Config {

  private def prop(k: String): String =
    Properties.envOrNone(k) getOrElse {
      throw new RuntimeException(s"No property '$k'")
    }

  object lottery {
    val url: String       = "https://freepostcodelottery.com/"
    val userEmail: String = prop("LOTTERY_USER_EMAIL")
  }

  val ocrApiKey: String        = prop("OCR_API_KEY")
  val makerKey: String         = prop("MAKER_KEY")
  val expectedPostcode: String = prop("POSTCODE")
} 
开发者ID:kchapl,项目名称:lotto,代码行数:21,代码来源:Config.scala


示例19: SQLint

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

import codacy.docker.api.Result.Issue
import codacy.docker.api.utils.ToolHelper
import codacy.docker.api.{Pattern, Result, Source, Tool}
import codacy.dockerApi.utils.CommandRunner

import scala.util.{Failure, Properties, Success, Try}

object SQLint extends Tool {

  override def apply(source: Source.Directory, configuration: Option[List[Pattern.Definition]], files: Option[Set[Source.File]])
                    (implicit specification: Tool.Specification): Try[List[Result]] = {
    Try {
      val dockerResults = for {
        patterns <- ToolHelper.patternsToLint(configuration)
        //This tool returns all messages mapped to only one pattern
        pattern <- patterns.headOption
      } yield {
        val path = new java.io.File(source.path)
        val filesToLint: Set[String] = ToolHelper.filesToLint(source, files)

        val command = List("sqlint") ++ filesToLint

        CommandRunner.exec(command, Some(path)) match {
          case Right(resultFromTool) if resultFromTool.exitCode < 2 =>
            Success(parseToolResult(resultFromTool.stdout, pattern))
          case Right(resultFromTool) =>
            val msg =
              s"""
                 |SQLint exited with code ${resultFromTool.exitCode}
                 |stdout: ${resultFromTool.stdout.mkString(Properties.lineSeparator)}
                 |stderr: ${resultFromTool.stderr.mkString(Properties.lineSeparator)}
                """.stripMargin
            Failure(new Exception(msg))
          case Left(e) =>
            Failure(e)
        }
      }
      dockerResults.getOrElse(Success(List.empty[Result]))
    }.flatten
  }

  private def parseToolResult(outputLines: List[String], pattern: Pattern.Definition): List[Result] = {
    outputLines.flatMap(parseLineResult(_, pattern))
  }

  private def parseLineResult(resultLine: String, pattern: Pattern.Definition): Option[Result] = {
    val LineRegex = """(.*?):([0-9]+):[0-9]*:?(ERROR|WARNING)\s*(.*)""".r

    Option(resultLine).collect { case LineRegex(filename, lineNumber, _, message) =>
      Issue(
        Source.File(filename),
        Result.Message(message),
        pattern.patternId,
        Source.Line(lineNumber.toInt)
      )
    }
  }
} 
开发者ID:codacy,项目名称:codacy-sqlint,代码行数:61,代码来源:SQLint.scala


示例20: EasyFiles

//设置package包名称以及导入依赖的类
package se.uu.it.easymr

import java.io.File
import java.io.FileNotFoundException
import java.io.PrintWriter
import java.util.UUID
import java.util.regex.Pattern

import scala.io.Source
import scala.util.Properties
import org.apache.log4j.Logger

private[easymr] object EasyFiles {

  // Set temporary directory
  private val tmpDir = new File(Properties.envOrElse("TMPDIR", "/tmp"))
  if (!tmpDir.exists) {
    throw new FileNotFoundException(
      s"temporary directory ${tmpDir.getAbsolutePath} doesn't extist")
  }
  if (!tmpDir.isDirectory) {
    throw new FileNotFoundException(
      s"${tmpDir.getAbsolutePath} is not a directory")
  }
  
  // Logger
  private lazy val log = Logger.getLogger(getClass.getName)

  private def newTmpFile = new File(tmpDir, "easymr_" + UUID.randomUUID.toString)

  def createTmpFile = {
    val file = EasyFiles.newTmpFile
    log.info(s"Creating new file: ${file.getAbsolutePath}")
    file.createNewFile
    log.info(s"New file '${file.getAbsolutePath}' created")
    file
  }

  def writeToTmpFile(it: Iterator[String], recordDelimiter: String): File = {
    val file = EasyFiles.newTmpFile
    log.info(s"Writing to: ${file.getAbsolutePath}")
    val pw = new PrintWriter(file)
    it.foreach(r => pw.write(r + recordDelimiter))
    pw.close
    log.info(s"Successfully wrote to: ${file.getAbsolutePath}")
    file
  }

  def readFromFile(file: File, recordDelimiter: String) = {
    val delimiterRegex = Pattern.quote(recordDelimiter)
    log.info(s"Reading from: ${file.getAbsolutePath}")
    val source = Source.fromFile(file)
    val recordsIteratior = source.mkString.split(delimiterRegex).iterator
    source.close
    log.info(s"Successfully read from: ${file.getAbsolutePath}")
    recordsIteratior
  }

} 
开发者ID:mcapuccini,项目名称:EasyMapReduce,代码行数:60,代码来源:EasyFiles.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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