package security

import be.objectify.deadbolt.scala.{ActionBuilders, AuthenticatedRequest, DeadboltHandler}
import be.objectify.deadbolt.scala.cache.HandlerCache
import com.google.inject.Inject
import play.api.mvc._

import scala.concurrent.Future

class DeadboltActionsAdapter @Inject()(actionBuilders: ActionBuilders, handlerCache: HandlerCache) {

  class RestrictActionBuilderAdapter(anyOfRoles: Seq[String]) {

    private val roleGroups = anyOfRoles.toList.map(Array(_))
    private val actionBuilder = actionBuilders.RestrictAction.RestrictActionBuilder(roleGroups)

    def apply[A](bodyParser: BodyParser[A])(block: AuthenticatedRequest[A] => Future[Result]): Action[A] = actionBuilder(bodyParser)(block)(handlerCache(AccessHandler))

    def apply(block: AuthenticatedRequest[AnyContent] => Future[Result]): Action[AnyContent] = actionBuilder(block)(handlerCache(AccessHandler))

    def apply(block: => Future[Result]): Action[AnyContent] = actionBuilder(block)(handlerCache(AccessHandler))
  }

  class SubjectPresentActionBuilderAdapter() {

    private val actionBuilder = actionBuilders.SubjectPresentAction.SubjectPresentActionBuilder()

    def apply(block: AuthenticatedRequest[Unit] => Future[Result]): Action[Unit] =
      actionBuilder(BodyParsers.parse.empty)(block)(handlerCache(RefreshHandler))
  }

  def restrictRefresh = new SubjectPresentActionBuilderAdapter()

  def restrictAccess(anyOfRoles: String*) = new RestrictActionBuilderAdapter(anyOfRoles)
}

package security

import be.objectify.deadbolt.scala.{ActionBuilders, AuthenticatedRequest, DeadboltHandler, HandlerKey}
import be.objectify.deadbolt.scala.cache.HandlerCache
import com.google.inject.Inject
import play.api.mvc._

import scala.concurrent.Future

class DeadboltActionsAdapter @Inject()(actionBuilders: ActionBuilders, handlerCache: HandlerCache) {

  class RestrictActionBuilderAdapter(anyOfRoles: Seq[String]) {

    private val roleGroups = anyOfRoles.toList.map(Array(_))
    private val actionBuilder = actionBuilders.RestrictAction.RestrictActionBuilder(roleGroups)

    def apply[A](bodyParser: BodyParser[A])(block: AuthenticatedRequest[A] => Future[Result]): Action[A] = actionBuilder(bodyParser)(block)(handlerCache(AccessHandler))

    def apply(block: AuthenticatedRequest[AnyContent] => Future[Result]): Action[AnyContent] = actionBuilder(block)(handlerCache(AccessHandler))

    def apply(block: => Future[Result]): Action[AnyContent] = actionBuilder(block)(handlerCache(AccessHandler))
  }

  class SubjectPresentActionBuilderAdapter(handlerKey: HandlerKey) {

    private val actionBuilder = actionBuilders.SubjectPresentAction.SubjectPresentActionBuilder()

    def apply(block: AuthenticatedRequest[Unit] => Future[Result]): Action[Unit] =
      actionBuilder(BodyParsers.parse.empty)(block)(handlerCache(handlerKey))
  }

  def restrictRefresh = new SubjectPresentActionBuilderAdapter(RefreshHandler)

  def restrictAccess(anyOfRoles: String*) = new RestrictActionBuilderAdapter(anyOfRoles)

  def restrictToAuthenticated = new SubjectPresentActionBuilderAdapter(AccessHandler)

}

Add restrict to authenticated user deadbolt action


scalacOptions := Seq(
  "-deprecation"
)

// For MimeLoader plugin. Dogfooding and hoping it doesn't clash with
// our other sbt plugins.
libraryDependencies ++= List(
  "com.eed3si9n" %% "treehugger" % "0.4.4",
  "io.circe" %% "circe-generic" % "0.12.1",
  "org.http4s" %% "http4s-blaze-client" % "0.20.9",
  "org.http4s" %% "http4s-circe" % "0.20.9",
)

// Hack around a binary conflict in scalameta's dependency on
// fastparse as specified by sbt-doctest-0.9.5.
libraryDependencies += "org.scalameta" %% "scalameta" % "4.2.3"

scalacOptions := Seq(
  "-deprecation"
)

// For MimeLoader plugin. Dogfooding and hoping it doesn't clash with
// our other sbt plugins.
libraryDependencies ++= List(
  "com.eed3si9n" %% "treehugger" % "0.4.4",
  "io.circe" %% "circe-generic" % "0.12.1",
  "org.http4s" %% "http4s-blaze-client" % "0.20.11",
  "org.http4s" %% "http4s-circe" % "0.20.11",
)

// Hack around a binary conflict in scalameta's dependency on
// fastparse as specified by sbt-doctest-0.9.5.
libraryDependencies += "org.scalameta" %% "scalameta" % "4.2.3"

Update http4s-blaze-client, http4s-circe to 0.20.11


package com.azavea.rf.common

import net.spy.memcached._

import java.util.concurrent.{Executors, TimeUnit}
import scala.concurrent._
import scala.concurrent.duration._
import scala.util._
import scala.concurrent.ExecutionContext.Implicits.global

package object cache {
  implicit class MemcachedClientMethods(client: MemcachedClient) {
    def getOrElseUpdate[CachedType](cacheKey: String, expensiveOperation: Future[CachedType], ttl: Duration)(implicit ec: ExecutionContext): Future[CachedType] = {
      val futureCached = Future { client.asyncGet(cacheKey).get() }
      futureCached.flatMap({ value =>
        if (value != null) { // cache hit
          Future.successful(value.asInstanceOf[CachedType])
        } else { // cache miss
          val futureCached: Future[CachedType] = expensiveOperation
          futureCached.foreach({ cachedValue => client.set(cacheKey, ttl.toSeconds.toInt, cachedValue) })
          futureCached
        }
      })
    }
  }
}

package com.azavea.rf.common

import net.spy.memcached._
import com.typesafe.scalalogging.LazyLogging
import scala.concurrent._
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global

package object cache extends LazyLogging {
  implicit class MemcachedClientMethods(client: MemcachedClient) {
    def getOrElseUpdate[CachedType](cacheKey: String, expensiveOperation: Future[CachedType], ttl: Duration)(implicit ec: ExecutionContext): Future[CachedType] = {
      val futureCached = Future { client.asyncGet(cacheKey).get() }
      futureCached.flatMap({ value =>
        if (value != null) { // cache hit
          logger.debug(s"Cache Hit: $cacheKey - $value")
          Future.successful(value.asInstanceOf[CachedType])
        } else { // cache miss
          logger.debug(s"Cache Miss: $cacheKey" )
          val futureCached: Future[CachedType] = expensiveOperation
          futureCached.foreach{ cachedValue =>
            try {
              client.set(cacheKey, ttl.toSeconds.toInt, cachedValue)
              logger.debug(s"Cache Set: $cacheKey - $cachedValue")
            } catch {
              case e: Exception => logger.debug(s"Cache Set Error: ${e.getMessage}")
            }
          }

          futureCached
        }
      })
    }
  }
}

Add debug log messages to memcached wrapper


package teststate.selenium

import org.openqa.selenium.{Point, WebElement}

object SeleniumExt {

  class WebElementExt(private val e: WebElement) extends AnyVal {
    def clearAndSendKeys(keys: String): Unit = {
      e.clear()
      e.sendKeys(keys)
    }
  }

  class PointExt(private val p: Point) extends AnyVal {
    def isPositive: Boolean =
      p.x >= 0 && p.y >= 0
  }

}

trait SeleniumExt {
  import SeleniumExt._
  implicit def WebElementExt(e: WebElement): WebElementExt = new WebElementExt(e)
  implicit def PointExt     (p: Point)     : PointExt      = new PointExt(p)
}

package teststate.selenium

import org.openqa.selenium._

object SeleniumExt {

  class WebElementExt(private val self: WebElement) extends AnyVal {
    def clearAndSendKeys(keys: String): Unit = {
      self.clear()
      self.sendKeys(keys)
    }

    def scrollTo(d: WebDriver): Unit = {
      val p = self.getLocation
      _scrollTo(d, Some(p.x), Some(p.y))
    }

    def scrollToX(d: WebDriver): Unit =
      _scrollTo(d, Some(self.getLocation.x), None)

    def scrollToY(d: WebDriver): Unit =
      _scrollTo(d, None, Some(self.getLocation.y))

    private def _scrollTo(d: WebDriver, x: Option[Int], y: Option[Int]): Unit =
      d match {
        case j: JavascriptExecutor =>
          val xx = x.fold("window.scrollX")(_.toString)
          val yy = y.fold("window.scrollY")(_.toString)
          j.executeScript(s"window.scrollTo($xx,$yy)")
          ()
        case _ =>
          throw new JavaScriptNotSupported("Scrolling without JS not supported.")
      }

    def scrollToAndClick(d: WebDriver): Unit = {
      scrollTo(d)
      self.click()
    }

  }

  class PointExt(private val p: Point) extends AnyVal {
    def isPositive: Boolean =
      p.x >= 0 && p.y >= 0
  }

  final class JavaScriptNotSupported(msg: String) extends RuntimeException
}

trait SeleniumExt {
  import SeleniumExt._
  implicit def WebElementExt(e: WebElement): WebElementExt = new WebElementExt(e)
  implicit def PointExt     (p: Point)     : PointExt      = new PointExt(p)
}

Add Selenium ext to scroll to element

Add Selenium ext to scroll to element


name := "core"

fork in run := true

resolvers += "Local Maven Repository" at "file://"+Path.userHome.absolutePath+"/.m2/repository"

libraryDependencies ++= Seq(
  "commons-cli" % "commons-cli" % "1.2",
  "org.apache.commons" % "commons-compress" % "1.4.1",
  "commons-lang" % "commons-lang" % "2.6",
  "bcel" % "bcel" % "5.1",
  "com.h2database" % "h2" % "1.4.187",
  "org.hibernate" % "hibernate-core" % "5.0.0.Beta2",
  "org.hibernate" % "hibernate-entitymanager" % "5.0.0.Beta2",
  "junit" % "junit" % "4.12",
  "com.google.inject" % "guice" % "4.0",
  "org.fedoraproject.javadeptools" % "java-deptools-native" % "1.0.0-SNAPSHOT"
)

name := "core"

fork in run := true

resolvers += "Local Maven Repository" at "file://"+Path.userHome.absolutePath+"/.m2/repository"

libraryDependencies ++= Seq(
  "commons-cli" % "commons-cli" % "1.2",
  "org.apache.commons" % "commons-compress" % "1.4.1",
  "commons-lang" % "commons-lang" % "2.6",
  "bcel" % "bcel" % "5.1",
  "com.h2database" % "h2" % "1.4.187",
  "org.hibernate" % "hibernate-core" % "5.0.0.Beta2",
  "org.hibernate" % "hibernate-entitymanager" % "5.0.0.Beta2",
  "junit" % "junit" % "4.12" % "test",
  "com.novocode" % "junit-interface" % "0.10" % "test",
  "com.google.inject" % "guice" % "4.0",
  "org.fedoraproject.javadeptools" % "java-deptools-native" % "1.0.0-SNAPSHOT"
)

Allow running tests with sbt

Allow running tests with sbt


package com.softwaremill.codebrag.dao

import net.liftweb.mongodb.{DefaultMongoIdentifier, MongoDB}
import com.mongodb.{MongoClient, ServerAddress, Mongo}
import com.typesafe.scalalogging.slf4j.Logging
import scala.collection.JavaConversions

object MongoInit extends Logging {
  def initialize(mongoConfig: MongoConfig) {
    MongoDB.defineDb(DefaultMongoIdentifier, createMongo(asServerAdresses(mongoConfig.mongoServers)), mongoConfig.mongoDatabase)
    ensureIndexes()
  }

  private def ensureIndexes() {
    logger.info("Ensuring Mongo indexes")
    CommitInfoRecord.ensureIndexes()
    FollowupRecord.ensureIndexes()
  }

  private def createMongo(serverList: List[ServerAddress]) = {
    // We need to use a different constructor if there's only 1 server to avoid startup exceptions where Mongo thinks
    // it's in a replica set.
    if (serverList.size == 1) {
      new MongoClient(serverList.head)
    } else {
      import JavaConversions._
      new MongoClient(serverList)
    }
  }

  private def asServerAdresses(servers: String): scala.List[ServerAddress] = {
    servers.split(",").map(new ServerAddress(_)).toList
  }
}

package com.softwaremill.codebrag.dao

import net.liftweb.mongodb.{DefaultMongoIdentifier, MongoDB}
import com.mongodb.{MongoClient, ServerAddress, Mongo}
import com.typesafe.scalalogging.slf4j.Logging
import scala.collection.JavaConversions

object MongoInit extends Logging {
  def initialize(mongoConfig: MongoConfig) {
    initializeWithoutIndexCheck(mongoConfig)
    ensureMongoIndexes()
  }

  def initializeWithoutIndexCheck(mongoConfig: MongoConfig) {
    MongoDB.defineDb(DefaultMongoIdentifier, createMongo(asServerAdresses(mongoConfig.mongoServers)), mongoConfig.mongoDatabase)
  }

  def ensureMongoIndexes() {
    logger.info("Ensuring Mongo indexes")
    CommitInfoRecord.ensureIndexes()
    FollowupRecord.ensureIndexes()
  }

  private def createMongo(serverList: List[ServerAddress]) = {
    // We need to use a different constructor if there's only 1 server to avoid startup exceptions where Mongo thinks
    // it's in a replica set.
    if (serverList.size == 1) {
      new MongoClient(serverList.head)
    } else {
      import JavaConversions._
      new MongoClient(serverList)
    }
  }

  private def asServerAdresses(servers: String): scala.List[ServerAddress] = {
    servers.split(",").map(new ServerAddress(_)).toList
  }
}

Add option to initialize connection to mongo without ensuring indexes exist (for changing user password)


package jp.sf.amateras.solr.scala.query;

object QueryUtils {

  private lazy val specialCharacters =
    Set('+', '-', '&', '|',  '!', '(', ')', '{', '}', '[', ']', '^', '"', '~', '*', '?', ':')

  /**
   * Escapes special characters in the solr query.
   *
   * @param value the source string
   * @return the escaped string
   */
  def escape(value: String): String =
    value.toString.map { c =>
      c match {
        case '\\' => Seq('\\', '\\', '\\', '\\')
        case _ if specialCharacters.contains(c) => Seq('\\', '\\', c)
        case _ => Seq(c)
      }
    }.flatten.mkString

}

package jp.sf.amateras.solr.scala.query;

object QueryUtils {

  private lazy val specialCharacters =
    Set('+', '-', '&', '|',  '!', '(', ')', '{', '}', '[', ']', '^', '"', '~', '*', '?', ':')

  /**
   * Escapes special characters in the solr query.
   *
   * @param value the source string
   * @return the escaped string
   */
  def escape(value: String): String =
    value.toString.map { c =>
      c match {
        case '\\' => Seq('\\', '\\')
        case _ if specialCharacters.contains(c) => Seq('\\', c)
        case _ => Seq(c)
      }
    }.flatten.mkString

}

Fix escaping problem in string literal.

Fix escaping problem in string literal.


import sbt._

object Dependencies {
  lazy val junitVersion = "4.13.1"
  lazy val thetaVersion = "1.1.2"
  lazy val breezeVersion = "1.2"
  lazy val scalaTestVersion = "3.2.2"

  // this is used in build.sbt so that it works with both 2.12 and 2.13
  lazy val scalaParallelCollectionsVersion = "1.0.0"

  val loloDeps = Seq(
    "junit" % "junit" % junitVersion % "test",
    "org.scalanlp" %% "breeze" % breezeVersion,
    "org.scalanlp" %% "breeze-natives" % breezeVersion,
    "io.citrine" %% "theta" % thetaVersion,
    "org.scalatest" %% "scalatest" % scalaTestVersion % "test",
    "com.novocode" % "junit-interface" % "0.11" % "test",
    "org.knowm.xchart" % "xchart" % "3.5.2"
  )
}

import sbt._

object Dependencies {
  lazy val netlibVersion = "1.1.2"
  lazy val junitVersion = "4.13.1"
  lazy val thetaVersion = "1.1.2"
  lazy val breezeVersion = "1.2"
  lazy val scalaTestVersion = "3.2.2"

  // this is used in build.sbt so that it works with both 2.12 and 2.13
  lazy val scalaParallelCollectionsVersion = "1.0.0"

  val loloDeps = Seq(
    "com.github.fommil.netlib" % "all" % netlibVersion pomOnly(),
    "junit" % "junit" % junitVersion % "test",
    "org.scalanlp" %% "breeze" % breezeVersion,
    "io.citrine" %% "theta" % thetaVersion,
    "org.scalatest" %% "scalatest" % scalaTestVersion % "test",
    "com.novocode" % "junit-interface" % "0.11" % "test",
    "org.knowm.xchart" % "xchart" % "3.5.2"
  )
}

Include netlib as pom only dependency.

Include netlib as pom only dependency.


scalacOptions := Seq(
  "-deprecation"
)

// For MimeLoader plugin. Dogfooding and hoping it doesn't clash with
// our other sbt plugins.
libraryDependencies ++= List(
  "com.eed3si9n" %% "treehugger" % "0.4.4",
  "io.circe" %% "circe-generic" % "0.13.0",
  "org.http4s" %% "http4s-blaze-client" % "0.21.18",
  "org.http4s" %% "http4s-circe" % "0.21.18",
)

scalacOptions := Seq(
  "-deprecation"
)

// For MimeLoader plugin. Dogfooding and hoping it doesn't clash with
// our other sbt plugins.
libraryDependencies ++= List(
  "com.eed3si9n" %% "treehugger" % "0.4.4",
  "io.circe" %% "circe-generic" % "0.13.0",
  "org.http4s" %% "http4s-blaze-client" % "0.21.19",
  "org.http4s" %% "http4s-circe" % "0.21.19",
)

Update http4s-blaze-client, ... to 0.21.19


import sbt._
import sbt.Keys._
import android.Keys._
import android.Plugin._

object Build extends android.AutoBuild
{
	lazy val main = Project( "toolbelt", file( "." ) )
		.settings( androidBuildAar: _* )
		.settings(
			libraryDependencies ++= Seq(
				"com.android.support" % "appcompat-v7" % "21.0.3",
				"com.github.japgolly.android" % "svg-android" % "2.0.6",
				"com.jpardogo.materialtabstrip" % "library" % "1.0.8",
				"org.scala-lang" % "scala-reflect" % scalaVersion.value
			),
			name := "Toolbelt",
			organization := "com.taig.android",
			publishArtifact in ( Compile, packageDoc ) := false,
			scalaVersion := "2.11.5",
			scalacOptions ++= Seq(
				"-deprecation",
				"-feature",
				"-language:dynamics",
				"-language:existentials",
				"-language:implicitConversions",
				"-language:reflectiveCalls"
			),
			// @see https://github.com/pfn/android-sdk-plugin/issues/88
			sourceGenerators in Compile <<= ( sourceGenerators in Compile ) ( generators => Seq( generators.last ) ),
			version := "0.3.22-BETA",
			minSdkVersion in Android := "10",
			platformTarget in Android := "android-21",
			targetSdkVersion in Android := "21"
		)
}

import sbt._
import sbt.Keys._
import android.Keys._
import android.Plugin._

object Build extends android.AutoBuild
{
	lazy val main = Project( "toolbelt", file( "." ) )
		.settings( androidBuildAar: _* )
		.settings(
			libraryDependencies ++= Seq(
				"com.android.support" % "appcompat-v7" % "21.0.3",
				"com.github.japgolly.android" % "svg-android" % "2.0.6",
				"com.jpardogo.materialtabstrip" % "library" % "1.0.8",
				"org.scala-lang" % "scala-reflect" % scalaVersion.value
			),
			name := "Toolbelt",
			organization := "com.taig.android",
			publishArtifact in ( Compile, packageDoc ) := false,
			scalaVersion := "2.11.5",
			scalacOptions ++= Seq(
				"-deprecation",
				"-feature",
				"-language:dynamics",
				"-language:existentials",
				"-language:implicitConversions",
				"-language:reflectiveCalls"
			),
			// @see https://github.com/pfn/android-sdk-plugin/issues/88
			sourceGenerators in Compile <<= ( sourceGenerators in Compile ) ( generators => Seq( generators.last ) ),
			version := "0.3.23-BETA",
			minSdkVersion in Android := "10",
			platformTarget in Android := "android-21",
			targetSdkVersion in Android := "21"
		)
}

Set project version to 0.3.22-BETA

Set project version to 0.3.22-BETA


addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "1.1.0")
addSbtPlugin("org.portable-scala" % "sbt-scala-native-crossproject" % "1.1.0")
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.8.0")
addSbtPlugin("org.scala-native" % "sbt-scala-native" % "0.4.3")
addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "3.9.11")
addSbtPlugin("com.github.sbt" % "sbt-pgp" % "2.1.2")
addSbtPlugin("org.scalastyle" %% "scalastyle-sbt-plugin" % "1.0.0")
addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.4.3")

addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.9.3")

addSbtPlugin("com.typesafe.sbt" % "sbt-git" % "1.0.2")

addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "1.1.0")
addSbtPlugin("org.portable-scala" % "sbt-scala-native-crossproject" % "1.1.0")
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.9.0")
addSbtPlugin("org.scala-native" % "sbt-scala-native" % "0.4.3")
addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "3.9.11")
addSbtPlugin("com.github.sbt" % "sbt-pgp" % "2.1.2")
addSbtPlugin("org.scalastyle" %% "scalastyle-sbt-plugin" % "1.0.0")
addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.4.3")

addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.9.3")

addSbtPlugin("com.typesafe.sbt" % "sbt-git" % "1.0.2")

Update sbt-scalajs, scalajs-compiler, ... to 1.9.0


addSbtPlugin("io.get-coursier" % "sbt-coursier" % "1.0.0-M13")

addSbtPlugin("org.scala-js" % "sbt-scalajs" % "0.6.13")

addSbtPlugin("net.lullabyte" % "sbt-chrome-plugin" % "0.2.1")

addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.4.0")

addCompilerPlugin("org.scalamacros" % "paradise" % "2.1.0" cross CrossVersion.full)

Remove coursier, sorry buddy :'(

Remove coursier, sorry buddy :'(


addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.8.2")
addSbtPlugin("org.scalameta"     % "sbt-scalafmt" % "2.4.2")

addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.8.3")
addSbtPlugin("org.scalameta"     % "sbt-scalafmt" % "2.4.2")

Update play-ahc-ws, play-akka-http-server, ... to 2.8.3


libraryDependencies += "org.scala-js" %% "scalajs-env-selenium" % "1.0.0"
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.1.1")
addSbtPlugin("org.scala-js" % "sbt-jsdependencies" % "1.0.2")
addSbtPlugin("org.scala-native" % "sbt-scala-native" % "0.4.0-M2")
addSbtPlugin("io.spray" % "sbt-revolver" % "0.9.1")
addSbtPlugin("com.eed3si9n" % "sbt-projectmatrix" % "0.6.0")

val sbtSoftwareMillVersion = "1.9.11"
addSbtPlugin("com.softwaremill.sbt-softwaremill" % "sbt-softwaremill-common" % sbtSoftwareMillVersion)
addSbtPlugin("com.softwaremill.sbt-softwaremill" % "sbt-softwaremill-publish" % sbtSoftwareMillVersion)

addSbtPlugin("ch.epfl.lamp" % "sbt-dotty" % "0.4.2")
addSbtPlugin("org.scalameta" % "sbt-mdoc" % "2.2.6")

addSbtPlugin("org.jetbrains" % "sbt-ide-settings" % "1.0.0")

libraryDependencies += "org.scala-js" %% "scalajs-env-selenium" % "1.0.0"
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.2.0")
addSbtPlugin("org.scala-js" % "sbt-jsdependencies" % "1.0.2")
addSbtPlugin("org.scala-native" % "sbt-scala-native" % "0.4.0-M2")
addSbtPlugin("io.spray" % "sbt-revolver" % "0.9.1")
addSbtPlugin("com.eed3si9n" % "sbt-projectmatrix" % "0.6.0")

val sbtSoftwareMillVersion = "1.9.11"
addSbtPlugin("com.softwaremill.sbt-softwaremill" % "sbt-softwaremill-common" % sbtSoftwareMillVersion)
addSbtPlugin("com.softwaremill.sbt-softwaremill" % "sbt-softwaremill-publish" % sbtSoftwareMillVersion)

addSbtPlugin("ch.epfl.lamp" % "sbt-dotty" % "0.4.2")
addSbtPlugin("org.scalameta" % "sbt-mdoc" % "2.2.6")

addSbtPlugin("org.jetbrains" % "sbt-ide-settings" % "1.0.0")

Update sbt-scalajs, scalajs-compiler to 1.2.0


package jp.leafytree.android.libproject.app

import android.test.ActivityInstrumentationTestCase2
import android.widget.TextView
import jp.leafytree.android.libproject.R
import junit.framework.Assert
import jp.leafytree.android.libproject.lib1.{Lib1Java, Lib1ScalaActivity}
import scala.collection.concurrent.TrieMap

class Lib1ScalaActivityTest extends ActivityInstrumentationTestCase2[Lib1ScalaActivity](classOf[Lib1ScalaActivity]) {
  def test1() {
    Assert.assertTrue(true)
  }

  def test2() {
    Assert.assertEquals("Lib1Java", getActivity.findViewById(R.id.scala_text_view).asInstanceOf[TextView].getText)
  }

  def test3() {
    val map = TrieMap[String, String]()
    map.put("1", "Lib1Java")
    map.put("2", new Lib1Java().getName)
    Assert.assertEquals(map("1"), map("2"))
  }
}

package jp.leafytree.android.libproject.app

import android.test.ActivityInstrumentationTestCase2
import android.widget.TextView
import jp.leafytree.android.libproject.R
import junit.framework.Assert
import jp.leafytree.android.libproject.lib1.{Lib1Java, Lib1ScalaActivity}
import scala.collection.concurrent.TrieMap
import scalaz._
import Scalaz._

class Lib1ScalaActivityTest extends ActivityInstrumentationTestCase2[Lib1ScalaActivity](classOf[Lib1ScalaActivity]) {
  def test1() {
    Assert.assertTrue(true)
  }

  def test2() {
    Assert.assertEquals("Lib1Java", getActivity.findViewById(R.id.scala_text_view).asInstanceOf[TextView].getText)
  }

  def test3() {
    val map = TrieMap[String, String]()
    map.put("1", "Lib1Java")
    map.put("2", new Lib1Java().getName)
    Assert.assertEquals(map("1"), map("2"))
  }

  def test4() {
    Assert.assertEquals(Success(123), "123".parseInt)
  }
}

Add scalaz availability check for large app


name := "play-scala"

version := "0.1"

lazy val root = (project in file(".")).enablePlugins(PlayScala)

scalaVersion := "2.11.7"

libraryDependencies ++= Seq(
  jdbc,
  cache,
  ws,
  "com.foomoo.abc" %% "abc-domain" % "0.3",
  "com.foomoo.abc" %% "abc-parser" % "0.3",
  "com.foomoo.abc" %% "abc-app" % "0.3",
  "com.foomoo.string-store" % "string-store-service-api" % "0.2",
  "com.foomoo.string-store" % "string-store-service-provider-mongo" % "0.2",
  "org.scalatestplus.play" %% "scalatestplus-play" % "1.5.1" % Test,
  "commons-cli" % "commons-cli" % "1.2"
)

sources in (Compile, doc) := Seq.empty

publishArtifact in (Compile, packageDoc) := false

name := "abc-site-play"

version := "0.2"

lazy val root = (project in file(".")).enablePlugins(PlayScala)

scalaVersion := "2.11.7"

libraryDependencies ++= Seq(
  jdbc,
  cache,
  ws,
  "com.foomoo.abc" %% "abc-domain" % "0.3",
  "com.foomoo.abc" %% "abc-parser" % "0.3",
  "com.foomoo.abc" %% "abc-app" % "0.3",
  "com.foomoo.string-store" % "string-store-service-api" % "0.2",
  "com.foomoo.string-store" % "string-store-service-provider-mongo" % "0.2",
  "org.scalatestplus.play" %% "scalatestplus-play" % "1.5.1" % Test,
  "commons-cli" % "commons-cli" % "1.2"
)

sources in (Compile, doc) := Seq.empty

publishArtifact in (Compile, packageDoc) := false

Set project name and increment version

Set project name and increment version


name := """play-morphia"""

organization := "it.unifi.cerm"

description := "Play 2.5.x Module for Morphia http://mongodb.github.io/morphia/"

version := "1.1"

lazy val root = (project in file(".")).enablePlugins(PlayJava)

scalaVersion := "2.11.7"

libraryDependencies ++= Seq(
  "org.mongodb" % "mongo-java-driver" % "3.2.2",
  "org.mongodb.morphia" % "morphia" % "1.3.2",
  "org.easytesting" % "fest-assert" % "1.4" % "test"
)

name := """play-morphia"""
organization := "it.unifi.cerm"

description := "Play 2.7.x Module for Morphia http://mongodb.github.io/morphia/"

version := "1.0"

lazy val root = (project in file(".")).enablePlugins(PlayJava)

scalaVersion := "2.12.8"

libraryDependencies ++= Seq(
"org.mongodb" % "mongo-java-driver" % "3.9.1",
"xyz.morphia.morphia" % "core" % "1.4.0",
"org.easytesting" % "fest-assert" % "1.4" % "test"
)

Update to work with Play 2.7.x

Update to work with Play 2.7.x


import play.PlayImport.PlayKeys._

name := "lib-play"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.7"

crossScalaVersions := Seq("2.11.7")

version := "0.0.31"

lazy val root = project
  .in(file("."))
  .enablePlugins(PlayScala)
  .settings(
    libraryDependencies ++= Seq(
      ws,
      "org.scalatest" %% "scalatest" % "2.2.6" % "test",
      "org.scalatestplus" %% "play" % "1.4.0" % "test"
    )
)

publishTo := {
  val host = "https://flow.artifactoryonline.com/flow"
  if (isSnapshot.value) {
    Some("Artifactory Realm" at s"$host/libs-snapshot-local;build.timestamp=" + new java.util.Date().getTime)
  } else {
    Some("Artifactory Realm" at s"$host/libs-release-local")
  }
}

import play.PlayImport.PlayKeys._

name := "lib-play"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.7"

crossScalaVersions := Seq("2.11.7")

version := "0.0.32"

lazy val root = project
  .in(file("."))
  .enablePlugins(PlayScala)
  .settings(
    libraryDependencies ++= Seq(
      ws,
      "org.scalatest" %% "scalatest" % "2.2.6" % "test",
      "org.scalatestplus" %% "play" % "1.4.0" % "test"
    )
)

publishTo := {
  val host = "https://flow.artifactoryonline.com/flow"
  if (isSnapshot.value) {
    Some("Artifactory Realm" at s"$host/libs-snapshot-local;build.timestamp=" + new java.util.Date().getTime)
  } else {
    Some("Artifactory Realm" at s"$host/libs-release-local")
  }
}

Increment version from 0.0.31 => 0.0.32

Increment version from 0.0.31 => 0.0.32


import play.PlayImport.PlayKeys._

name := "lib-play"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

crossScalaVersions := Seq("2.11.8")

version := "0.2.20"

lazy val root = project
  .in(file("."))
  .enablePlugins(PlayScala)
  .settings(
    libraryDependencies ++= Seq(
      ws,
      filters,
      "com.jason-goodwin" %% "authentikat-jwt" % "0.4.3",
      "org.scalatestplus" %% "play" % "1.4.0" % "test"
    ),
    resolvers += "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/",
    resolvers += "scalaz-bintray" at "https://dl.bintray.com/scalaz/releases",
    resolvers += "Artifactory" at "https://flow.artifactoryonline.com/flow/libs-release/",
    credentials += Credentials(
      "Artifactory Realm",
      "flow.artifactoryonline.com",
      System.getenv("ARTIFACTORY_USERNAME"),
      System.getenv("ARTIFACTORY_PASSWORD")
    )
)

publishTo := {
  val host = "https://flow.artifactoryonline.com/flow"
  if (isSnapshot.value) {
    Some("Artifactory Realm" at s"$host/libs-snapshot-local;build.timestamp=" + new java.util.Date().getTime)
  } else {
    Some("Artifactory Realm" at s"$host/libs-release-local")
  }
}

import play.PlayImport.PlayKeys._

name := "lib-play"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

crossScalaVersions := Seq("2.11.8")

version := "0.2.21"

lazy val root = project
  .in(file("."))
  .enablePlugins(PlayScala)
  .settings(
    libraryDependencies ++= Seq(
      ws,
      filters,
      "com.jason-goodwin" %% "authentikat-jwt" % "0.4.3",
      "org.scalatestplus" %% "play" % "1.4.0" % "test"
    ),
    resolvers += "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/",
    resolvers += "scalaz-bintray" at "https://dl.bintray.com/scalaz/releases",
    resolvers += "Artifactory" at "https://flow.artifactoryonline.com/flow/libs-release/",
    credentials += Credentials(
      "Artifactory Realm",
      "flow.artifactoryonline.com",
      System.getenv("ARTIFACTORY_USERNAME"),
      System.getenv("ARTIFACTORY_PASSWORD")
    )
)

publishTo := {
  val host = "https://flow.artifactoryonline.com/flow"
  if (isSnapshot.value) {
    Some("Artifactory Realm" at s"$host/libs-snapshot-local;build.timestamp=" + new java.util.Date().getTime)
  } else {
    Some("Artifactory Realm" at s"$host/libs-release-local")
  }
}

autocommit: Update configuration to record version 0.2.21


import play.PlayImport.PlayKeys._

name := "lib-play"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

crossScalaVersions := Seq("2.11.8")

version := "0.1.70"

lazy val root = project
  .in(file("."))
  .enablePlugins(PlayScala)
  .settings(
    libraryDependencies ++= Seq(
      ws,
      filters,
      "com.jason-goodwin" %% "authentikat-jwt" % "0.4.3",
      "org.scalatestplus" %% "play" % "1.4.0" % "test"
    ),
    resolvers += "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/",
    resolvers += "scalaz-bintray" at "https://dl.bintray.com/scalaz/releases",
    resolvers += "Artifactory" at "https://flow.artifactoryonline.com/flow/libs-release/",
    credentials += Credentials(
      "Artifactory Realm",
      "flow.artifactoryonline.com",
      System.getenv("ARTIFACTORY_USERNAME"),
      System.getenv("ARTIFACTORY_PASSWORD")
    )
)

publishTo := {
  val host = "https://flow.artifactoryonline.com/flow"
  if (isSnapshot.value) {
    Some("Artifactory Realm" at s"$host/libs-snapshot-local;build.timestamp=" + new java.util.Date().getTime)
  } else {
    Some("Artifactory Realm" at s"$host/libs-release-local")
  }
}

import play.PlayImport.PlayKeys._

name := "lib-play"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

crossScalaVersions := Seq("2.11.8")

version := "0.2.1"

lazy val root = project
  .in(file("."))
  .enablePlugins(PlayScala)
  .settings(
    libraryDependencies ++= Seq(
      ws,
      filters,
      "com.jason-goodwin" %% "authentikat-jwt" % "0.4.3",
      "org.scalatestplus" %% "play" % "1.4.0" % "test"
    ),
    resolvers += "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/",
    resolvers += "scalaz-bintray" at "https://dl.bintray.com/scalaz/releases",
    resolvers += "Artifactory" at "https://flow.artifactoryonline.com/flow/libs-release/",
    credentials += Credentials(
      "Artifactory Realm",
      "flow.artifactoryonline.com",
      System.getenv("ARTIFACTORY_USERNAME"),
      System.getenv("ARTIFACTORY_PASSWORD")
    )
)

publishTo := {
  val host = "https://flow.artifactoryonline.com/flow"
  if (isSnapshot.value) {
    Some("Artifactory Realm" at s"$host/libs-snapshot-local;build.timestamp=" + new java.util.Date().getTime)
  } else {
    Some("Artifactory Realm" at s"$host/libs-release-local")
  }
}

autocommit: Update configuration to record version 0.2.1


import com.github.retronym.SbtOneJar._

oneJarSettings

name := "api-build"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

version := "0.0.87"

exportJars := true

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.5.8",
      "com.ning" % "async-http-client" % "1.9.39",
      "org.scalatest" %% "scalatest" % "2.2.6" % Test
    )
  )

publishTo := {
  val host = "https://flow.artifactoryonline.com/flow"
  if (isSnapshot.value) {
    Some("Artifactory Realm" at s"$host/libs-snapshot-local;build.timestamp=" + new java.util.Date().getTime)
  } else {
    Some("Artifactory Realm" at s"$host/libs-release-local")
  }
}

import com.github.retronym.SbtOneJar._

oneJarSettings

name := "api-build"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

version := "0.0.88"

exportJars := true

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.5.8",
      "com.ning" % "async-http-client" % "1.9.39",
      "org.scalatest" %% "scalatest" % "2.2.6" % Test
    )
  )

publishTo := {
  val host = "https://flow.artifactoryonline.com/flow"
  if (isSnapshot.value) {
    Some("Artifactory Realm" at s"$host/libs-snapshot-local;build.timestamp=" + new java.util.Date().getTime)
  } else {
    Some("Artifactory Realm" at s"$host/libs-release-local")
  }
}

autocommit: Update configuration to record version 0.0.88


import com.github.retronym.SbtOneJar._

oneJarSettings

name := "api-build"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

version := "0.0.67"

exportJars := true

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.5.4",
      "com.ning" % "async-http-client" % "1.9.39",
      "org.scalatest" %% "scalatest" % "2.2.6" % Test
    )
  )

publishTo := {
  val host = "https://flow.artifactoryonline.com/flow"
  if (isSnapshot.value) {
    Some("Artifactory Realm" at s"$host/libs-snapshot-local;build.timestamp=" + new java.util.Date().getTime)
  } else {
    Some("Artifactory Realm" at s"$host/libs-release-local")
  }
}

import com.github.retronym.SbtOneJar._

oneJarSettings

name := "api-build"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

version := "0.0.68"

exportJars := true

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.5.4",
      "com.ning" % "async-http-client" % "1.9.39",
      "org.scalatest" %% "scalatest" % "2.2.6" % Test
    )
  )

publishTo := {
  val host = "https://flow.artifactoryonline.com/flow"
  if (isSnapshot.value) {
    Some("Artifactory Realm" at s"$host/libs-snapshot-local;build.timestamp=" + new java.util.Date().getTime)
  } else {
    Some("Artifactory Realm" at s"$host/libs-release-local")
  }
}

autocommit: Update configuration to record version 0.0.68


package info.fotm.util

import java.nio.file.{Files, Paths}

import com.twitter.bijection.Bijection

class FilePersisted[S](fileName: String)(implicit serializer: Bijection[S, Array[Byte]]) extends Persisted[S] {

  override def save(state: S): Unit = {
    Files.write(Paths.get(fileName), serializer(state))
  }

  override def fetch(): Option[S] =
    if (Files.exists(Paths.get(fileName))) {
      val bytes = Files.readAllBytes(Paths.get(fileName))
      Some(serializer.inverse(bytes))
    } else {
      None
    }
}

package info.fotm.util

import java.nio.file.{Files, Paths}

import com.twitter.bijection.Bijection

import scala.util.Try

class FilePersisted[S](fileName: String)(implicit serializer: Bijection[S, Array[Byte]]) extends Persisted[S] {

  override def save(state: S): Unit = {
    Files.write(Paths.get(fileName), serializer(state))
  }

  override def fetch(): Option[S] =
    Try {
      val bytes = Files.readAllBytes(Paths.get(fileName))
      serializer.inverse(bytes)
    }.toOption
}

Fix fetch from file when there's an exception


package uk.ac.wellcome.platform.idminter.utils

import org.scalatest.{FunSpec, Matchers}
import org.scalatest.prop.PropertyChecks

class IdentifiableTest extends FunSpec with PropertyChecks with Matchers {

  it("should generate a string with 8 characters, none of which are ambiguous characters") {
    forAll(minSuccessful(100)) { (a: Int) =>
      {
        val id = Identifiable.generate
        id should have size (8)
        id.toCharArray should contain noneOf ('0', 'o', 'i', 'l', '1')
        id should fullyMatch regex "[0-9|a-z&&[^oil10]]{8}"
      }
    }
  }

}

package uk.ac.wellcome.platform.idminter.utils

import org.scalatest.{FunSpec, Matchers}
import org.scalatest.prop.PropertyChecks

class IdentifiableTest extends FunSpec with PropertyChecks with Matchers {

  it("should generate a string with 8 characters, none of which are ambiguous characters") {
    forAll(minSuccessful(100)) { (a: Int) =>
      {
        val id = Identifiable.generate
        id should have size (8)
        id.toCharArray should contain noneOf ('0', 'o', 'i', 'l', '1')
        id should fullyMatch regex "[0-9|a-z&&[^oil10]]{8}"
      }
    }
  }

  // We have a rule that identifiers can't start with a number, as this
  // makes them awkward to use as a string in certain contexts.
  it("should never generate an identifier that starts with a number") {
    forAll(minSuccessful(100)) { (_: Int) =>
      {
        val id = Identifiable.generate
        assert(!id.head.isDigit)
      }
    }
  }

}

Add a test that canonical identifiers start with a letter


package com.komanov.stringformat.jmh

import org.openjdk.jmh.annotations.Benchmark

class StringBuilderBenchmark extends BenchmarkBase {

  @Benchmark
  def javaStringBuilder: String = {
    new java.lang.StringBuilder()
      .append("abc")
      .append("def")
      .toString
  }

  @Benchmark
  def scalaStringBuilder: String = {
    new scala.collection.mutable.StringBuilder()
      .append("abc")
      .append("def")
      .toString
  }

}

Add tests for StringBuilder with long strings


package com.softwaremill.codebrag.service.github.jgit

import java.nio.file.{Paths, Path}
import com.softwaremill.codebrag.service.config.CodebragConfiguration

class InternalGitDirTree {

  def containsRepo(owner: String, repoName: String): Boolean = {
    getPath(owner, repoName).toFile.exists()
  }

  def getPath(owner: String, repoName: String): Path = Paths.get(s"${InternalGitDirTree.Root}/$owner/$repoName")
}

object InternalGitDirTree {

  val Root = (
    if (!CodebragConfiguration.localGitPath.equals(""))
      CodebragConfiguration.localGitPath
    else ".") + "/repos"
}

package com.softwaremill.codebrag.service.github.jgit

import java.nio.file.{Paths, Path}
import com.softwaremill.codebrag.service.config.CodebragConfiguration
import org.eclipse.jgit.util.StringUtils._

class InternalGitDirTree {

  def containsRepo(owner: String, repoName: String): Boolean = {
    getPath(owner, repoName).toFile.exists()
  }

  def getPath(owner: String, repoName: String): Path = Paths.get(s"${InternalGitDirTree.Root}/$owner/$repoName")
}

object InternalGitDirTree {

  val Root = (
    if (!isEmptyOrNull(CodebragConfiguration.localGitPath))
      CodebragConfiguration.localGitPath
    else ".") + "/repos"
}

Fix loading of path for local repos from configuration - It was crashing on non-existing file


package antwar
package sandbox

import scala.collection.immutable._
import scala.util.control.Exception._

case class BreadthFirstSearch(board: Board, goal: Tile => Boolean) {

  case class Node(value: Tile, children: List[Node] = Nil, parent: Option[Node] = None) {
    override def toString = "Tree(" + value.toString + " {" + children.map(_.toString).mkString(",") + "})\n"
  }

  /**
   *  Build a graph for the BFS, with a deep limit to levelLimit
   */
  def buildGraph(tile: Tile, marked: Set[Tile] = Set(), currentLevel: Int = 0, levelLimit: Int = 3): Node = {

    Node(tile,
      if (currentLevel > levelLimit)
        Nil
      else {
        val neighbors = board neighborsOf tile filterNot marked.contains
        neighbors map { n => buildGraph(n, marked ++ neighbors, currentLevel + 1, levelLimit) }
      })

  }

  private def searchGraph(queue: Queue[Node]): Option[Tile] = catching(classOf[NoSuchElementException]) opt queue.dequeue match {
      case Some((node, rest)) =>
        if (goal(node.value))
          Some(node.value)
        else
          searchGraph(rest.enqueue(node.children))

      case _ => None
    }

  def findTile(startTile: Tile): Option[Tile] = {
    val graph = buildGraph(startTile)
    searchGraph(Queue(graph))
  }

}

package antwar
package sandbox

import scala.collection.immutable._
import scala.util.control.Exception._

case class BreadthFirstSearch(board: Board, goal: Tile => Boolean) {

  case class Node(value: Tile, level: Int, children: List[Node] = Nil, parent: Option[Node] = None) {
    override def toString = "Tree(" + value.toString + " {" + children.map(_.toString).mkString(",") + "})\n"
  }

  /**
   *  Build a graph for the BFS, with a deep limit to levelLimit
   */
  def buildGraph(tile: Tile, marked: Set[Tile] = Set(), currentLevel: Int = 0, levelLimit: Int = 10): Node =
    Node(
      tile,
      currentLevel,
      if (currentLevel > levelLimit)
        Nil
      else {
        val neighbors = board neighborsOf tile filterNot marked.contains
        neighbors map { n => buildGraph(n, marked ++ neighbors, currentLevel + 1, levelLimit) }
      })

  private def searchGraph(queue: Queue[Node]): Option[Tile] = catching(classOf[NoSuchElementException]) opt queue.dequeue match {
      case Some((node, rest)) =>
        if (goal(node.value))
          Some(node.value)
        else
          searchGraph(rest.enqueue(node.children))
      case _ => None
    }

  def findTile(startTile: Tile): Option[Tile] = {
    val graph = buildGraph(startTile, Set(startTile))
    searchGraph(Queue(graph))
  }

}

Add level to the nodes

Add level to the nodes


package protocols

import akka.NotUsed
import akka.stream.scaladsl.Source
import models.cfs.Block._
import play.api.http._
import play.api.libs.MimeTypes
import play.api.mvc._
import play.utils.UriEncoding

/**
 * @author zepeng.li@gmail.com
 */

trait HttpDownloadable {

  def size: Long
  def name: String
  def whole: Source[BLK, NotUsed]
}

trait HttpDownloadResult extends HeaderNames with Status {

  def send(
    file: HttpDownloadable,
    name: HttpDownloadable => String = _.name,
    inline: Boolean = false
  ): Result = {
    val result = Result(
      ResponseHeader(OK),
      HttpEntity.Streamed(
        file.whole,
        Some(file.size),
        contentTypeOf(file)
      )
    )
    if (inline) result
    else {
      val encoded = UriEncoding.encodePathSegment(name(file), "utf-8")
      result.withHeaders(
        CONTENT_DISPOSITION -> s"""attachment; filename="$encoded" """
      )
    }
  }

  def contentTypeOf(inode: HttpDownloadable): Option[String] = {
    MimeTypes.forFileName(inode.name).orElse(Some(ContentTypes.BINARY))
  }
}

object HttpDownloadResult extends HttpDownloadResult

package protocols

import java.nio.charset.StandardCharsets

import akka.NotUsed
import akka.stream.scaladsl.Source
import models.cfs.Block._
import play.api.http._
import play.api.libs.MimeTypes
import play.api.mvc._
import play.utils.UriEncoding

/**
 * @author zepeng.li@gmail.com
 */

trait HttpDownloadable {

  def size: Long
  def name: String
  def whole: Source[BLK, NotUsed]
}

trait HttpDownloadResult extends HeaderNames with Status {

  def send(
    file: HttpDownloadable,
    name: HttpDownloadable => String = _.name,
    inline: Boolean = false
  ): Result = {
    val result = Result(
      ResponseHeader(OK),
      HttpEntity.Streamed(
        file.whole,
        Some(file.size),
        contentTypeOf(file)
      )
    )
    val encoded = UriEncoding.encodePathSegment(name(file), StandardCharsets.UTF_8)
    result.withHeaders(
      CONTENT_DISPOSITION -> {
        val dispositionType = if (inline) "inline" else "attachment"
        s"""$dispositionType; filename="$name"; filename*=utf-8''$encoded"""
      }
    )
  }

  def contentTypeOf(inode: HttpDownloadable): Option[String] = {
    MimeTypes.forFileName(inode.name).orElse(Some(ContentTypes.BINARY))
  }
}

object HttpDownloadResult extends HttpDownloadResult

Support non-ISO8859-1 filename in Content-Disposition header


addSbtPlugin("org.scalameta" % "sbt-mdoc" % "2.3.6")
addSbtPlugin("org.planet42" % "laika-sbt" % "0.18.2")

addSbtPlugin("org.scalameta" % "sbt-mdoc" % "2.2.24")
addSbtPlugin("org.planet42" % "laika-sbt" % "0.18.2")

Revert "Update mdoc, sbt-mdoc to 2.3.6"

Revert "Update mdoc, sbt-mdoc to 2.3.6"


addSbtPlugin("org.scala-js" % "sbt-scalajs" % "0.6.29")

addSbtPlugin("org.scalastyle" %% "scalastyle-sbt-plugin" % "1.0.0")

addSbtPlugin("com.github.gseitz" % "sbt-release" % "1.0.12")

addSbtPlugin("org.scala-js" % "sbt-scalajs" % "0.6.31")

addSbtPlugin("org.scalastyle" %% "scalastyle-sbt-plugin" % "1.0.0")

addSbtPlugin("com.github.gseitz" % "sbt-release" % "1.0.12")

Update sbt-scalajs, scalajs-library, ... to 0.6.31


addSbtPlugin("com.lightbend.paradox"     % "sbt-paradox"             % "0.8.0")
addSbtPlugin("com.typesafe.sbt"          % "sbt-site"                % "1.4.1")
addSbtPlugin("com.typesafe.sbt"          % "sbt-ghpages"             % "0.6.3")
addSbtPlugin("com.geirsson"              % "sbt-ci-release"          % "1.5.4")
addSbtPlugin("org.scoverage"             % "sbt-scoverage"           % "1.6.1")
addSbtPlugin("com.timushev.sbt"          % "sbt-updates"             % "0.5.1")
addSbtPlugin("pl.project13.scala"        % "sbt-jmh"                 % "0.3.7")
addSbtPlugin("de.heikoseeberger"         % "sbt-header"              % "5.6.0")
addSbtPlugin("io.chrisdavenport"         % "sbt-mima-version-check"  % "0.1.2")
addSbtPlugin("io.github.davidgregory084" % "sbt-tpolecat"            % "0.1.14")
addSbtPlugin("org.scalameta"             % "sbt-mdoc"                % "2.2.11" )

addSbtPlugin("com.lightbend.paradox"     % "sbt-paradox"             % "0.8.0")
addSbtPlugin("com.typesafe.sbt"          % "sbt-site"                % "1.4.1")
addSbtPlugin("com.typesafe.sbt"          % "sbt-ghpages"             % "0.6.3")
addSbtPlugin("com.geirsson"              % "sbt-ci-release"          % "1.5.4")
addSbtPlugin("org.scoverage"             % "sbt-scoverage"           % "1.6.1")
addSbtPlugin("com.timushev.sbt"          % "sbt-updates"             % "0.5.1")
addSbtPlugin("pl.project13.scala"        % "sbt-jmh"                 % "0.3.7")
addSbtPlugin("de.heikoseeberger"         % "sbt-header"              % "5.6.0")
addSbtPlugin("io.chrisdavenport"         % "sbt-mima-version-check"  % "0.1.2")
addSbtPlugin("io.github.davidgregory084" % "sbt-tpolecat"            % "0.1.14")
addSbtPlugin("org.scalameta"             % "sbt-mdoc"                % "2.2.12" )

Update mdoc, sbt-mdoc to 2.2.12

Update mdoc, sbt-mdoc to 2.2.12


libraryDependencies += "ch.qos.logback" % "logback-classic" % "1.2.11"

// https://github.com/coursier/coursier/issues/450
classpathTypes += "maven-plugin"

addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "4.2.4")
addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.11.0")
addSbtPlugin("com.github.tkawachi" % "sbt-doctest" % "0.10.0")
addSbtPlugin("org.http4s" % "sbt-http4s-org" % "0.14.7")
addSbtPlugin("com.github.sbt" % "sbt-native-packager" % "1.9.11")
addSbtPlugin("io.spray" % "sbt-revolver" % "0.9.1")
addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.4.3")
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.10.1")
addSbtPlugin("org.scala-native" % "sbt-scala-native" % "0.4.7")
addSbtPlugin("org.portable-scala" % "sbt-scala-native-crossproject" % "1.2.0")
addSbtPlugin("org.scoverage" % "sbt-scoverage" % "2.0.6")

libraryDependencies += "ch.qos.logback" % "logback-classic" % "1.2.11"

// https://github.com/coursier/coursier/issues/450
classpathTypes += "maven-plugin"

addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "4.2.4")
addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.11.0")
addSbtPlugin("com.github.tkawachi" % "sbt-doctest" % "0.10.0")
addSbtPlugin("org.http4s" % "sbt-http4s-org" % "0.14.8")
addSbtPlugin("com.github.sbt" % "sbt-native-packager" % "1.9.11")
addSbtPlugin("io.spray" % "sbt-revolver" % "0.9.1")
addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.4.3")
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.10.1")
addSbtPlugin("org.scala-native" % "sbt-scala-native" % "0.4.7")
addSbtPlugin("org.portable-scala" % "sbt-scala-native-crossproject" % "1.2.0")
addSbtPlugin("org.scoverage" % "sbt-scoverage" % "2.0.6")

Update sbt-http4s-org to 0.14.8 in series/0.23


libraryDependencies += "ch.qos.logback" % "logback-classic" % "1.2.11"

// https://github.com/coursier/coursier/issues/450
classpathTypes += "maven-plugin"

addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "4.2.4")
addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.11.0")
addSbtPlugin("com.github.tkawachi" % "sbt-doctest" % "0.10.0")
addSbtPlugin("org.http4s" % "sbt-http4s-org" % "0.14.3")
addSbtPlugin("com.github.sbt" % "sbt-native-packager" % "1.9.9")
addSbtPlugin("io.spray" % "sbt-revolver" % "0.9.1")
addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.4.3")
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.10.0")
addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.9.3")

libraryDependencies += "ch.qos.logback" % "logback-classic" % "1.2.11"

// https://github.com/coursier/coursier/issues/450
classpathTypes += "maven-plugin"

addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "4.2.4")
addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.11.0")
addSbtPlugin("com.github.tkawachi" % "sbt-doctest" % "0.10.0")
addSbtPlugin("org.http4s" % "sbt-http4s-org" % "0.14.3")
addSbtPlugin("com.github.sbt" % "sbt-native-packager" % "1.9.9")
addSbtPlugin("io.spray" % "sbt-revolver" % "0.9.1")
addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.4.3")
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.10.0")
addSbtPlugin("org.scoverage" % "sbt-scoverage" % "2.0.0")

Update sbt-scoverage to 2.0.0 in series/0.23


addSbtPlugin("io.spray" % "sbt-revolver" % "0.9.1")
addSbtPlugin("com.typesafe.sbt" % "sbt-twirl" % "1.5.1")
addSbtPlugin("io.github.irundaia" % "sbt-sassify" % "1.5.2")
addSbtPlugin("com.github.sbt" % "sbt-native-packager" % "1.9.9")
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.9.0")
addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "1.2.0")
addSbtPlugin("ch.epfl.scala" % "sbt-scalafix" % "0.10.0")

libraryDependencies ++= Seq(
  "org.testcontainers" % "postgresql" % "1.17.1",
  "org.testcontainers" % "elasticsearch" % "1.17.1",
  "org.tpolecat" %% "doobie-postgres" % "0.13.4"
)

addSbtPlugin("io.spray" % "sbt-revolver" % "0.9.1")
addSbtPlugin("com.typesafe.sbt" % "sbt-twirl" % "1.5.1")
addSbtPlugin("io.github.irundaia" % "sbt-sassify" % "1.5.2")
addSbtPlugin("com.github.sbt" % "sbt-native-packager" % "1.9.9")
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.10.1")
addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "1.2.0")
addSbtPlugin("ch.epfl.scala" % "sbt-scalafix" % "0.10.0")

libraryDependencies ++= Seq(
  "org.testcontainers" % "postgresql" % "1.17.1",
  "org.testcontainers" % "elasticsearch" % "1.17.1",
  "org.tpolecat" %% "doobie-postgres" % "0.13.4"
)

Update sbt-scalajs, scalajs-compiler, ... to 1.10.1


package dotty.tools.dotc
package core

import Contexts._
import config.Printers.{default, typr}

trait ConstraintRunInfo { self: Run =>
  private var maxSize = 0
  private var maxConstraint: Constraint | Null = _
  def recordConstraintSize(c: Constraint, size: Int): Unit =
    if (size > maxSize) {
      maxSize = size
      maxConstraint = c
    }
  def printMaxConstraint()(using Context): Unit =
    val printer = if (ctx.settings.YdetailedStats.value) default else typr
    if maxSize > 0 then
      printer.println(s"max constraint = ${maxConstraint.nn.show}\nsize = $maxSize")

  protected def reset(): Unit = maxConstraint = null
}

package dotty.tools.dotc
package core

import Contexts._
import config.Printers.{default, typr}

trait ConstraintRunInfo { self: Run =>
  private var maxSize = 0
  private var maxConstraint: Constraint | Null = _
  def recordConstraintSize(c: Constraint, size: Int): Unit =
    if (size > maxSize) {
      maxSize = size
      maxConstraint = c
    }
  def printMaxConstraint()(using Context): Unit =
    if maxSize > 0 then
      val printer = if ctx.settings.YdetailedStats.value then default else typr
      printer.println(s"max constraint size: $maxSize")
      try printer.println(s"max constraint = ${maxConstraint.nn.show}")
      catch case ex: StackOverflowError => printer.println("max constraint cannot be printed due to stack overflow")

  protected def reset(): Unit = maxConstraint = null
}

Handle stackoverflows when trying to print the maximal constraint


name := "lib-reference-scala"

organization := "io.flow"

scalaVersion in ThisBuild := "2.12.4"

crossScalaVersions := Seq("2.12.4", "2.11.12", "2.10.6")

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "org.scalatest" %% "scalatest" % "3.0.5" % Test
    )
  )

publishTo := {
  val host = "https://flow.artifactoryonline.com/flow"
  if (isSnapshot.value) {
    Some("Artifactory Realm" at s"$host/libs-snapshot-local;build.timestamp=" + new java.util.Date().getTime)
  } else {
    Some("Artifactory Realm" at s"$host/libs-release-local")
  }
}

version := "0.1.60"

name := "lib-reference-scala"

organization := "io.flow"

scalaVersion in ThisBuild := "2.12.4"

crossScalaVersions := Seq("2.12.4", "2.11.12", "2.10.6")

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "org.scalatest" %% "scalatest" % "3.0.5" % Test
    )
  )

publishTo := {
  val host = "https://flow.artifactoryonline.com/flow"
  if (isSnapshot.value) {
    Some("Artifactory Realm" at s"$host/libs-snapshot-local;build.timestamp=" + new java.util.Date().getTime)
  } else {
    Some("Artifactory Realm" at s"$host/libs-release-local")
  }
}

version := "0.1.61"

autocommit: Update configuration to record version 0.1.61


import com.github.retronym.SbtOneJar._

oneJarSettings

name := "api-build"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

version := "0.1.12"

exportJars := true

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.5.10",
      "com.ning" % "async-http-client" % "1.9.40",
      "org.scalatest" %% "scalatest" % "3.0.1" % Test
    )
  )

publishTo := {
  val host = "https://flow.artifactoryonline.com/flow"
  if (isSnapshot.value) {
    Some("Artifactory Realm" at s"$host/libs-snapshot-local;build.timestamp=" + new java.util.Date().getTime)
  } else {
    Some("Artifactory Realm" at s"$host/libs-release-local")
  }
}

import com.github.retronym.SbtOneJar._

oneJarSettings

name := "api-build"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

version := "0.1.11"

exportJars := true

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.5.10",
      "com.ning" % "async-http-client" % "1.9.40",
      "org.scalatest" %% "scalatest" % "3.0.1" % Test
    )
  )

publishTo := {
  val host = "https://flow.artifactoryonline.com/flow"
  if (isSnapshot.value) {
    Some("Artifactory Realm" at s"$host/libs-snapshot-local;build.timestamp=" + new java.util.Date().getTime)
  } else {
    Some("Artifactory Realm" at s"$host/libs-release-local")
  }
}

Revert "autocommit: Update configuration to record version 0.1.12"

This reverts commit ba8a09be37ab467b03ffcc161df97877490ffcc3.


package org.jetbrains.plugins.scala.performance.highlighting.projectHighlighting

import java.util.concurrent.TimeUnit

import com.intellij.openapi.vfs.newvfs.impl.VfsRootAccess
import org.jetbrains.plugins.scala.SlowTests
import org.junit.experimental.categories.Category

/**
  * Author: Svyatoslav Ilinskiy
  * Date: 10/23/15.
  */
@Category(Array(classOf[SlowTests]))
class ScalaCommunityHighlightingPerformanceTest extends PerformanceSbtProjectHighlightingTestBase {

  override protected def getExternalSystemConfigFileName: String = "build.sbt"

  override def githubUsername: String = "JetBrains"

  override def githubRepoName: String = "intellij-scala"

  override def revision: String = "493444f6465d0eddea75ac5cd5a848cc30d48ae5"

  def testPerformanceScalaCommunityScalaPsiUtil() = doTest("ScalaPsiUtil.scala", TimeUnit.SECONDS.toMillis(20))

  def testPerformanceScalaCommunityScalaAnnotator() = doTest("ScalaAnnotator.scala", TimeUnit.SECONDS.toMillis(15))

  override def doTest(path: String, timeout: Long): Unit = {
    VfsRootAccess.allowRootAccess("/usr/lib/jvm/java-7-oracle/") //without this, an error happens, has to do with tools.jar
    super.doTest(path, timeout)
  }
}

package org.jetbrains.plugins.scala.performance.highlighting.projectHighlighting

import java.util.concurrent.TimeUnit

import com.intellij.openapi.vfs.newvfs.impl.VfsRootAccess
import org.jetbrains.plugins.scala.SlowTests
import org.junit.experimental.categories.Category

/**
  * Author: Svyatoslav Ilinskiy
  * Date: 10/23/15.
  */
@Category(Array(classOf[SlowTests]))
class ScalaCommunityHighlightingPerformanceTest extends PerformanceSbtProjectHighlightingTestBase {

  override protected def getExternalSystemConfigFileName: String = "build.sbt"

  override def githubUsername: String = "JetBrains"

  override def githubRepoName: String = "intellij-scala"

  override def revision: String = "493444f6465d0eddea75ac5cd5a848cc30d48ae5"

  def testPerformanceScalaCommunityScalaPsiUtil() = doTest("ScalaPsiUtil.scala", TimeUnit.SECONDS.toMillis(20))

  def testPerformanceScalaCommunityScalaAnnotator() = doTest("ScalaAnnotator.scala", TimeUnit.SECONDS.toMillis(15))

  override def doTest(path: String, timeout: Long): Unit = {
    VfsRootAccess.SHOULD_PERFORM_ACCESS_CHECK = false
    super.doTest(path, timeout)
  }
}

Disable access check instead of the hacky way that was used previously


enablePlugins(ContainerPlugin)

libraryDependencies += "javax.servlet" % "javax.servlet-api" % "4.0.1" % "provided"
libraryDependencies += "javax.ws.rs" % "javax.ws.rs-api" % "2.0"

containerLibs in Container :=
  Seq("fish.payara.extras" % "payara-micro" % "5.191")

containerLaunchCmd in Container := { (port, path) =>
  Seq("fish.payara.micro.PayaraMicro", "--deploy", "target/webapp", "--contextroot", "/")
}

enablePlugins(ContainerPlugin)

libraryDependencies += "javax.ws.rs" % "javax.ws.rs-api" % "2.0" % "provided"

containerLibs in Container :=
  Seq("fish.payara.extras" % "payara-micro" % "5.191")

containerLaunchCmd in Container := { (port, path) =>
  Seq("fish.payara.micro.PayaraMicro", "--deploy", "target/webapp", "--contextroot", "/")
}

Drop unused dependency; rescope javax.ws.rs-api

See thread in #369


import sbt._

object Dependencies {

  val logging_lib = "com.typesafe.scala-logging" %% "scala-logging" % "3.9.5"
  val test_lib    = "org.scalatest" % "scalatest_2.11" % "2.2.6"

  val core_deps = Seq(logging_lib, test_lib % Test)
}

import sbt._

object Dependencies {

  val logging_lib = "com.typesafe.scala-logging" %% "scala-logging" % "3.9.5"
  val test_lib    = "org.scalatest" % "scalatest_2.11" % "3.2.14"

  val core_deps = Seq(logging_lib, test_lib % Test)
}

Update dependency org.scalatest:scalatest_2.11 to v3


import akka.actor.{Actor, ActorSystem, Props}
import fsm.DiningHakkersOnFsm
import postoffice.PostOffice
import spray.SprayDemo

import scala.util.Random

object Main extends App {
  DiningHakkersOnFsm.run(ActorSystem("fsm"))
  PostOffice.run(ActorSystem("post-office"))
  SprayDemo.run(ActorSystem("spray"))

  val system = ActorSystem("small-demos")
  val lazyActorProps = Props(new Actor {
    override def receive: Receive = {
      case msg =>
        Thread.sleep(Random.nextInt(2000))
        sender() ! msg
    }
  })

  val lazyActor1 = system.actorOf(lazyActorProps, "lazy1")
  val lazyActor2 = system.actorOf(lazyActorProps, "lazy2")
  for (i <- 0 to 1000) {
    lazyActor1.tell("doit", lazyActor2)
  }
}

import akka.actor.{Actor, ActorSystem, Props}
import fsm.DiningHakkersOnFsm
import postoffice.PostOffice
import spray.SprayDemo

import scala.util.Random

object Main extends App {
  DiningHakkersOnFsm.run(ActorSystem("fsm"))
  PostOffice.run(ActorSystem("post-office"))
  SprayDemo.run(ActorSystem("spray"))

  val system = ActorSystem("small-demos")
  val lazyActorProps = Props(new Actor {
    var counter = 0
    override def receive: Receive = {
      case msg =>
        Thread.sleep(Random.nextInt(2000))
        counter += 1
        sender() ! msg
    }
  })

  val lazyActor1 = system.actorOf(lazyActorProps, "lazy1")
  val lazyActor2 = system.actorOf(lazyActorProps, "lazy2")
  for (i <- 0 to 1000) {
    lazyActor1.tell("doit", lazyActor2)
  }
}

Add counters to ping-pong actors

Add counters to ping-pong actors


package eu.pepot.eu.spark.inputsplitter.helper

import java.io.File

import eu.pepot.eu.spark.inputsplitter.common.file.FileDetails
import Helper._

object TestsHelper {

  def resourcesBaseDir(subDir: String) = {
    toStringPath("src/test/resources/eu/pepot/eu/spark/inputsplitter/samples", subDir)
  }

  def resourcesBaseDirWithAbsolutePath(subDir: String) = {
    new File("src/test/resources/eu/pepot/eu/spark/inputsplitter/samples/" + subDir).getAbsolutePath
  }

  def toFDs(s: String): FileDetails = {
    FileDetails(s, new File(s).length())
  }

}

package eu.pepot.eu.spark.inputsplitter.helper

import java.io.File

import eu.pepot.eu.spark.inputsplitter.common.file.FileDetails
import Helper._

object TestsHelper {

  def resourcesBaseDir(subDir: String) = {
    toStringPath("src/test/resources/eu/pepot/eu/spark/inputsplitter/samples", subDir)
  }

  def resourcesBaseDirWithAbsolutePath(subDir: String) = {
    new File("src/test/resources/eu/pepot/eu/spark/inputsplitter/samples", subDir).getAbsolutePath
  }

  def toFDs(s: String): FileDetails = {
    FileDetails(s, new File(s).length())
  }

}

Use better File(parent, child) constructor


import sbt._
import Process._
import java.io.File

class SpielProject(info: ProjectInfo) extends AndroidProject(info) {
  override def androidPlatformName = "android-1.6"

  val rhino = "rhino" % "js" % "1.7R2"

  override def proguardOption = """
    -adaptresourcefilenames **.properties
    -keep class * extends org.mozilla.javascript.VMBridge
    -keep public class org.mozilla.javascript.Token
  """

  override def packageTask(signPackage: Boolean) = task {
    super.packageTask(signPackage).run
    FileUtilities.unzip(classesMinJarPath, outputDirectoryName, GlobFilter("org/mozilla/javascript/resources/*.properties"), log)
    for(p <- (outputDirectoryName/"org"**"*.properties").get) {
      (
        (new java.lang.ProcessBuilder(
          aaptPath.absolutePath,
          "add",
          packageApkPath.absolutePath,
          p.toString.replace(outputDirectoryName+"/", "")
        ))
        directory outputDirectoryName.asFile
      ) ! log
    }
    FileUtilities.clean(outputDirectoryName/"org", log)
    None
  }
}

import sbt._
import Process._
import java.io.File

class SpielProject(info: ProjectInfo) extends AndroidProject(info) {
  override def androidPlatformName = "android-1.6"

  val rhino = "rhino" % "js" % "1.7R2"

  override def proguardOption = """
    -adaptresourcefilenames **.properties
    -keep class * extends org.mozilla.javascript.VMBridge
    -keep public class org.mozilla.javascript.Token
  """

  override def aaptPackageTask = task {
    super.aaptPackageTask.run
    FileUtilities.unzip(classesMinJarPath, outputDirectoryName, GlobFilter("org/mozilla/javascript/resources/*.properties"), log)
    for(p <- (outputDirectoryName/"org"**"*.properties").get) {
      (
        (new java.lang.ProcessBuilder(
          aaptPath.absolutePath,
          "add",
          resourcesApkPath.absolutePath,
          p.toString.replace("./"+outputDirectoryName+"/", "")
        ))
        directory outputDirectoryName.asFile
      ) ! log
    }
    FileUtilities.clean(outputDirectoryName/"org", log)
    None
  }
}

Fix build system, resources now load correctly and we can haz errors!

--HG--
extra : convert_revision : a4511363dc7d3be1045fde03877e1794356f2893


import sbt._
import sbt.Keys._
import android.Keys._
import android.Plugin._

object Build extends android.AutoBuild
{
	lazy val main = Project( "toolbelt", file( "." ) )
		.settings( buildAar: _* )
		.settings(
			libraryDependencies ++= Seq(
				"org.scala-lang" % "scala-reflect" % scalaVersion.value,
				"com.android.support" % "support-v4" % "20.0.0",
				"com.github.japgolly.android" % "svg-android" % "2.0.6"
			),
			name := "Toolbelt",
			organization := "com.taig.android",
			scalaVersion := "2.11.2",
			scalacOptions ++= Seq(
				"-deprecation",
				"-feature",
				"-language:dynamics",
				"-language:implicitConversions",
				"-language:reflectiveCalls"
			),
			version := "0.0.6-BETA",
			libraryProject in Android := true,
			minSdkVersion in Android := "10",
			targetSdkVersion in Android := "19"
		)
}

import sbt._
import sbt.Keys._
import android.Keys._
import android.Plugin._

object Build extends android.AutoBuild
{
	lazy val main = Project( "toolbelt", file( "." ) )
		.settings( buildAar: _* )
		.settings(
			libraryDependencies ++= Seq(
				"org.scala-lang" % "scala-reflect" % scalaVersion.value,
				"com.android.support" % "support-v4" % "20.0.0",
				"com.github.japgolly.android" % "svg-android" % "2.0.6"
			),
			name := "Toolbelt",
			organization := "com.taig.android",
			scalaVersion := "2.11.2",
			scalacOptions ++= Seq(
				"-deprecation",
				"-feature",
				"-language:dynamics",
				"-language:implicitConversions",
				"-language:reflectiveCalls"
			),
			version := "0.0.7-BETA",
			libraryProject in Android := true,
			minSdkVersion in Android := "10",
			targetSdkVersion in Android := "19"
		)
}

Set project version to 0.0.7-BETA

Set project version to 0.0.7-BETA


addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.6.0")
addSbtPlugin("org.scala-js" % "sbt-jsdependencies" % "1.0.2")
addSbtPlugin("org.scala-native" % "sbt-scala-native" % "0.4.0")
addSbtPlugin("io.spray" % "sbt-revolver" % "0.9.1")
addSbtPlugin("com.eed3si9n" % "sbt-projectmatrix" % "0.8.0")

val sbtSoftwareMillVersion = "2.0.5"
addSbtPlugin("com.softwaremill.sbt-softwaremill" % "sbt-softwaremill-common" % sbtSoftwareMillVersion)
addSbtPlugin("com.softwaremill.sbt-softwaremill" % "sbt-softwaremill-publish" % sbtSoftwareMillVersion)
addSbtPlugin("com.softwaremill.sbt-softwaremill" % "sbt-softwaremill-browser-test-js" % sbtSoftwareMillVersion)

addSbtPlugin("org.scalameta" % "sbt-mdoc" % "2.2.21")

addSbtPlugin("org.jetbrains.scala" % "sbt-ide-settings" % "1.1.1")

addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.6.0")
addSbtPlugin("org.scala-js" % "sbt-jsdependencies" % "1.0.2")
addSbtPlugin("org.scala-native" % "sbt-scala-native" % "0.4.0")
addSbtPlugin("io.spray" % "sbt-revolver" % "0.9.1")
addSbtPlugin("com.eed3si9n" % "sbt-projectmatrix" % "0.8.0")

val sbtSoftwareMillVersion = "2.0.6"
addSbtPlugin("com.softwaremill.sbt-softwaremill" % "sbt-softwaremill-common" % sbtSoftwareMillVersion)
addSbtPlugin("com.softwaremill.sbt-softwaremill" % "sbt-softwaremill-publish" % sbtSoftwareMillVersion)
addSbtPlugin("com.softwaremill.sbt-softwaremill" % "sbt-softwaremill-browser-test-js" % sbtSoftwareMillVersion)

addSbtPlugin("org.scalameta" % "sbt-mdoc" % "2.2.21")

addSbtPlugin("org.jetbrains.scala" % "sbt-ide-settings" % "1.1.1")

Update sbt-softwaremill-browser-test-js, ... to 2.0.6


addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.4.6")
addSbtPlugin("com.github.sbt" % "sbt-pgp" % "2.1.2")
addSbtPlugin("com.github.sbt" % "sbt-git" % "2.0.0")
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.10.0")
addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "1.2.0")
addSbtPlugin("org.portable-scala" % "sbt-scala-native-crossproject" % "1.2.0")
addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "3.9.13")
addSbtPlugin("ohnosequences" % "sbt-github-release" % "0.7.0")
addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.11.0")
addSbtPlugin("org.scala-native" % "sbt-scala-native" % "0.4.4")

// https://github.com/ohnosequences/sbt-github-release/issues/28#issuecomment-426086656
libraryDependencies += "com.sun.activation" % "javax.activation" % "1.2.0"

addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.4.6")
addSbtPlugin("com.github.sbt" % "sbt-pgp" % "2.1.2")
addSbtPlugin("com.github.sbt" % "sbt-git" % "2.0.0")
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.10.1")
addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "1.2.0")
addSbtPlugin("org.portable-scala" % "sbt-scala-native-crossproject" % "1.2.0")
addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "3.9.13")
addSbtPlugin("ohnosequences" % "sbt-github-release" % "0.7.0")
addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.11.0")
addSbtPlugin("org.scala-native" % "sbt-scala-native" % "0.4.4")

// https://github.com/ohnosequences/sbt-github-release/issues/28#issuecomment-426086656
libraryDependencies += "com.sun.activation" % "javax.activation" % "1.2.0"


scalacOptions += "-deprecation"
libraryDependencies += "org.slf4j" % "slf4j-nop" % "1.7.32"

addSbtPlugin("com.typesafe"                      % "sbt-mima-plugin"       % "0.9.2")
addSbtPlugin("com.typesafe.sbt"                  % "sbt-osgi"              % "0.9.6")
addSbtPlugin("com.eed3si9n"                      % "sbt-buildinfo"         % "0.10.0")
addSbtPlugin("com.geirsson"                      % "sbt-ci-release"        % "1.5.7")
addSbtPlugin("com.thoughtworks.sbt-api-mappings" % "sbt-api-mappings"      % "3.0.0")
addSbtPlugin("org.scala-js"                      % "sbt-scalajs"           % "1.6.0")
addSbtPlugin("org.scala-native"                  % "sbt-scala-native"      % "0.4.0")
addSbtPlugin("org.portable-scala"                % "sbt-scalajs-crossproject" % "1.1.0")
addSbtPlugin("org.portable-scala"                % "sbt-scala-native-crossproject" % "1.1.0")
addSbtPlugin("com.codecommit"                    % "sbt-github-actions"    % "0.12.0")

scalacOptions += "-deprecation"
libraryDependencies += "org.slf4j" % "slf4j-nop" % "1.7.32"

addSbtPlugin("com.typesafe"                      % "sbt-mima-plugin"       % "0.9.2")
addSbtPlugin("com.typesafe.sbt"                  % "sbt-osgi"              % "0.9.6")
addSbtPlugin("com.eed3si9n"                      % "sbt-buildinfo"         % "0.10.0")
addSbtPlugin("com.geirsson"                      % "sbt-ci-release"        % "1.5.7")
addSbtPlugin("com.thoughtworks.sbt-api-mappings" % "sbt-api-mappings"      % "3.0.0")
addSbtPlugin("org.scala-js"                      % "sbt-scalajs"           % "1.7.0")
addSbtPlugin("org.scala-native"                  % "sbt-scala-native"      % "0.4.0")
addSbtPlugin("org.portable-scala"                % "sbt-scalajs-crossproject" % "1.1.0")
addSbtPlugin("org.portable-scala"                % "sbt-scala-native-crossproject" % "1.1.0")
addSbtPlugin("com.codecommit"                    % "sbt-github-actions"    % "0.12.0")

Update sbt-scalajs, scalajs-compiler, ... to 1.7.0


addSbtPlugin("com.eed3si9n" % "sbt-projectmatrix" % "0.9.0")

val sbtSoftwareMillVersion = "2.0.8"
addSbtPlugin(
  "com.softwaremill.sbt-softwaremill" % "sbt-softwaremill-common" % sbtSoftwareMillVersion
)
addSbtPlugin(
  "com.softwaremill.sbt-softwaremill" % "sbt-softwaremill-publish" % sbtSoftwareMillVersion
)

addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.8.0")
addSbtPlugin("com.typesafe" % "sbt-mima-plugin" % "1.0.1")

addSbtPlugin("com.eed3si9n" % "sbt-projectmatrix" % "0.9.0")

val sbtSoftwareMillVersion = "2.0.9"
addSbtPlugin(
  "com.softwaremill.sbt-softwaremill" % "sbt-softwaremill-common" % sbtSoftwareMillVersion
)
addSbtPlugin(
  "com.softwaremill.sbt-softwaremill" % "sbt-softwaremill-publish" % sbtSoftwareMillVersion
)

addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.8.0")
addSbtPlugin("com.typesafe" % "sbt-mima-plugin" % "1.0.1")

Update sbt-softwaremill-common, ... to 2.0.9


package controllers

import controllers.Common.PrototypeHtml
import helpers.{UnitSpec, WithApplication}
import org.mockito.Mockito.when
import play.api.test.FakeRequest
import play.api.test.Helpers.{OK, contentAsString, defaultAwaitTimeout, status}
import uk.gov.dvla.vehicles.presentation.common.clientsidesession.ClientSideSessionFactory
import utils.helpers.Config

final class MicroserviceErrorUnitSpec extends UnitSpec {

  "present" should {

    "display the page" in new WithApplication {
      status(present) should equal(OK)
    }

    "not display progress bar" in new WithApplication {
      contentAsString(present) should not include "Step "
    }

    "display prototype message when config set to true" in new WithApplication {
      contentAsString(present) should include(PrototypeHtml)
    }

    "not display prototype message when config set to false" in new WithApplication {
      val request = FakeRequest()
      implicit val clientSideSessionFactory = injector.getInstance(classOf[ClientSideSessionFactory])
      implicit val config: Config = mock[Config]
      when(config.isPrototypeBannerVisible).thenReturn(false)
      // Stub this config value.
      val microServiceErrorPrototypeNotVisible = new MicroServiceError()

      val result = microServiceErrorPrototypeNotVisible.present(request)
      contentAsString(result) should not include PrototypeHtml
    }
  }

  private lazy val present = microServiceError.present(FakeRequest())
  private val microServiceError = injector.getInstance(classOf[MicroServiceError])
}

package controllers

import com.tzavellas.sse.guice.ScalaModule
import controllers.Common.PrototypeHtml
import helpers.{UnitSpec, WithApplication}
import org.mockito.Mockito.when
import play.api.test.FakeRequest
import play.api.test.Helpers.{OK, contentAsString, defaultAwaitTimeout, status}
import utils.helpers.Config

final class MicroserviceErrorUnitSpec extends UnitSpec {

  "present" should {

    "display the page" in new WithApplication {
      status(present) should equal(OK)
    }

    "not display progress bar" in new WithApplication {
      contentAsString(present) should not include "Step "
    }

    "display prototype message when config set to true" in new WithApplication {
      contentAsString(present) should include(PrototypeHtml)
    }

    "not display prototype message when config set to false" in new WithApplication {
      val request = FakeRequest()
      val result = microServiceErrorPrototypeNotVisible.present(request)
      contentAsString(result) should not include PrototypeHtml
    }
  }

  private def microServiceErrorPrototypeNotVisible = {
    testInjector(new ScalaModule() {
      override def configure(): Unit = {
        val config: Config = mock[Config]
        when(config.isPrototypeBannerVisible).thenReturn(false) // Stub this config value.
        bind[Config].toInstance(config)
      }
    }).getInstance(classOf[MicroServiceError])
  }

  private lazy val present = microServiceError.present(FakeRequest())
  private val microServiceError = injector.getInstance(classOf[MicroServiceError])
}

Test with testInjector to stub config

Refactor: Test with testInjector to stub config


package com.microsoft.partnercatalyst.fortis.spark.transforms.language

import org.scalatest.FlatSpec

class TestLanguageDetector(cognitiveServicesResponse: String) extends LanguageDetector(LanguageDetectorAuth("key")) {
  protected override def callCognitiveServices(request: String): String = cognitiveServicesResponse
  override def buildRequestBody(text: String, textId: String): String = super.buildRequestBody(text, textId)
}

class LanguageDetectorSpec extends FlatSpec {
  "The image analyzer" should "formulate correct request and parse response to domain types" in {
    val responseConfidence = 1.0
    val detector = new TestLanguageDetector(s"""{"documents":[{"id":"0","detectedLanguages":[{"name":"English","iso6391Name":"en","score":$responseConfidence}]}],"errors":[]}""")
    val language = detector.detectLanguage("some text")

    assert(language.contains("en"))
  }

  it should "ignore low confidence detections" in {
    val responseConfidence = 0.01
    val detector = new TestLanguageDetector(s"""{"documents":[{"id":"0","detectedLanguages":[{"name":"English","iso6391Name":"en","score":$responseConfidence}]}],"errors":[]}""")
    val language = detector.detectLanguage("some text")

    assert(language.isEmpty)
  }

  it should "build correct request body" in {
    val id = "0"
    val text = "some text"
    val requestBody = new TestLanguageDetector("").buildRequestBody(text, id)

    assert(requestBody == s"""{"documents":[{"id":"$id","text":"$text"}]}""")
  }
}

package com.microsoft.partnercatalyst.fortis.spark.transforms.language

import org.scalatest.FlatSpec

class TestLanguageDetector(cognitiveServicesResponse: String) extends LanguageDetector(LanguageDetectorAuth("key")) {
  protected override def callCognitiveServices(request: String): String = cognitiveServicesResponse
  override def buildRequestBody(text: String, textId: String): String = super.buildRequestBody(text, textId)
}

class LanguageDetectorSpec extends FlatSpec {
  "The language detector" should "formulate correct request and parse response to domain types" in {
    val responseConfidence = 1.0
    val detector = new TestLanguageDetector(s"""{"documents":[{"id":"0","detectedLanguages":[{"name":"English","iso6391Name":"en","score":$responseConfidence}]}],"errors":[]}""")
    val language = detector.detectLanguage("some text")

    assert(language.contains("en"))
  }

  it should "ignore low confidence detections" in {
    val responseConfidence = 0.01
    val detector = new TestLanguageDetector(s"""{"documents":[{"id":"0","detectedLanguages":[{"name":"English","iso6391Name":"en","score":$responseConfidence}]}],"errors":[]}""")
    val language = detector.detectLanguage("some text")

    assert(language.isEmpty)
  }

  it should "build correct request body" in {
    val id = "0"
    val text = "some text"
    val requestBody = new TestLanguageDetector("").buildRequestBody(text, id)

    assert(requestBody == s"""{"documents":[{"id":"$id","text":"$text"}]}""")
  }
}

Fix typo in test naming

Fix typo in test naming


package scalex
package es

import org.elasticsearch.client.Client
import org.elasticsearch.common.xcontent.XContentBuilder
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest
import org.elasticsearch.action.admin.indices.flush.FlushRequest
import org.elasticsearch.indices.IndexMissingException

class Type(name: String, indexName: String, client: Client) {

  def populate[A](objs: Iterator[A], map: A => XContentBuilder, id: A => String) = {
    drop
    val bulk = client.prepareBulk
    objs foreach { obj => bulk add store(map(obj), id(obj)) }
    bulk.execute.actionGet
    flush
  }

  def store(obj: XContentBuilder, id: String) =
    client.prepareIndex(indexName, name, id) setSource obj

  def drop = try {
    client.admin().indices().delete(new DeleteIndexRequest(indexName)).actionGet
  } catch {
    case e: IndexMissingException =>
  }

  def flush =
    client.admin().indices().flush(new FlushRequest(indexName).refresh(true)).actionGet
}

package scalex
package es

import org.elasticsearch.client.Client
import org.elasticsearch.common.xcontent.XContentBuilder
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest
import org.elasticsearch.action.admin.indices.flush.FlushRequest
import org.elasticsearch.indices.IndexMissingException

class Type(indexName: String, name: String, client: Client) {

  def populate[A](objs: Iterator[A], map: A => XContentBuilder, id: A => String) = {
    drop
    val bulk = client.prepareBulk
    objs foreach { obj => bulk add store(map(obj), id(obj)) }
    bulk.execute.actionGet
    flush
  }

  def store(obj: XContentBuilder, id: String) =
    client.prepareIndex(indexName, name, id) setSource obj

  def drop = try {
    client.admin().indices().delete(new DeleteIndexRequest(indexName)).actionGet
  } catch {
    case e: IndexMissingException =>
  }

  def flush =
    client.admin().indices().flush(new FlushRequest(indexName).refresh(true)).actionGet
}

Fix ES type constructor arguments order

Fix ES type constructor arguments order


package com.twitter.finatra.http.internal.marshalling.mustache

import com.google.common.net.MediaType
import com.twitter.finatra.http.marshalling.mustache.{MustacheBodyComponent, MustacheService}
import com.twitter.finatra.http.marshalling.{MessageBodyWriter, WriterResponse}
import com.twitter.io.Buf
import javax.inject.{Inject, Singleton}

@Singleton
class MustacheMessageBodyWriter @Inject()(
  mustacheService: MustacheService,
  templateLookup: MustacheTemplateNameLookup)
  extends MessageBodyWriter[Any] {

  /* Public */

  override def write(obj: Any): WriterResponse = {
    WriterResponse(
      MediaType.HTML_UTF_8,
      mustacheService.createBuffer(
        templateLookup.getTemplateName(obj),
        getScope(obj))
    )
  }

  /* Private */

  private def getScope(obj: Any): Any = {
    obj match {
      case c: MustacheBodyComponent => c.data
      case _ => obj
    }
  }

}

package com.twitter.finatra.http.internal.marshalling.mustache

import com.google.common.net.MediaType
import com.twitter.finatra.http.marshalling.mustache.{MustacheBodyComponent, MustacheService}
import com.twitter.finatra.http.marshalling.{MessageBodyWriter, WriterResponse}
import javax.inject.{Inject, Singleton}

@Singleton
class MustacheMessageBodyWriter @Inject()(
  mustacheService: MustacheService,
  templateLookup: MustacheTemplateNameLookup)
  extends MessageBodyWriter[Any] {

  /* Public */

  override def write(obj: Any): WriterResponse = {
    WriterResponse(
      MediaType.HTML_UTF_8,
      mustacheService.createBuffer(
        templateLookup.getTemplateName(obj),
        getScope(obj))
    )
  }

  /* Private */

  private def getScope(obj: Any): Any = {
    obj match {
      case c: MustacheBodyComponent => c.data
      case _ => obj
    }
  }

}

Enable warnings for unused imports for scala

Problem:

Many projects have unused imports that they are unaware of. This will occasionally cause them to have false-dependencies on other code, which slows down builds unnecessarily.

Solution:

Enable warnings for unused imports for scalac, and remove unused imports for `fatal_warnings` targets (since an unused import will now be an error for them).

RB_ID=808875


import java.io.File
import java.nio.file.Files

object Main extends App {

  val cp = new collection.mutable.ArrayBuffer[File]

  def buildCp(loader: ClassLoader): Unit =
    if (loader != null) {
      loader match {
        case u: java.net.URLClassLoader =>
          cp ++= u.getURLs
            .map(_.toURI)
            .map(new File(_))
        case _ =>
      }

      buildCp(loader.getParent)
    }

  buildCp(Thread.currentThread().getContextClassLoader)

  val sbtBase = new File(sys.props.getOrElse(
    "sbt.global.base",
    sys.props("user.home") + "/.sbt"
  ))
  val prefix = new File(sbtBase, "boot").getAbsolutePath

  def fromBootAndUnique(name: String): Unit = {
    val jars = cp.filter(_.getName.startsWith(name)).distinct
    assert(jars.length == 1, s"Found 0 or multiple JARs for $name: $jars")

    val Seq(jar) = jars

    assert(jar.getAbsolutePath.startsWith(prefix), s"JAR for $name ($jar) not under $prefix")
  }

  fromBootAndUnique("scala-library")
  fromBootAndUnique("scala-reflect")
  fromBootAndUnique("scala-compiler")

  Files.write(new File("output").toPath, "OK".getBytes("UTF-8"))
}

import java.io.File
import java.nio.file.Files

import scala.collection.JavaConverters._

object Main extends App {

  val cp = new collection.mutable.ArrayBuffer[File]

  def buildCp(loader: ClassLoader): Unit =
    if (loader != null) {
      loader match {
        case u: java.net.URLClassLoader =>
          cp ++= u.getURLs
            .map(_.toURI)
            .map(new File(_))
        case _ =>
      }

      buildCp(loader.getParent)
    }

  buildCp(Thread.currentThread().getContextClassLoader)

  val sbtBase = new File(sys.props.getOrElse(
    "sbt.global.base",
    sys.props("user.home") + "/.sbt"
  ))
  val prefix = new File(sbtBase, "boot").getAbsolutePath

  def fromBootAndUnique(name: String): Unit = {
    val jars = cp.filter(_.getName.startsWith(name)).distinct
    assert(jars.length == 1, s"Found 0 or multiple JARs for $name: $jars")

    val Seq(jar) = jars

    assert(jar.getAbsolutePath.startsWith(prefix), s"JAR for $name ($jar) not under $prefix")
  }

  val props = Thread.currentThread()
    .getContextClassLoader
    .getResources("library.properties")
    .asScala
    .toVector
    .map(_.toString)
    .sorted

  // That one doesn't pass with sbt 1.x, maybe because of classloader filtering?
  // fromBootAndUnique("scala-library")
  assert(props.lengthCompare(1) == 0, s"Found several library.properties files in classpath: $props")

  fromBootAndUnique("scala-reflect")
  fromBootAndUnique("scala-compiler")

  Files.write(new File("output").toPath, "OK".getBytes("UTF-8"))
}

Tweak scripted test for sbt 1.x

Tweak scripted test for sbt 1.x


package scala.meta.internal.io

import java.net.URI
import java.nio.charset.Charset
import java.nio.file.FileVisitOption
import scala.meta.io._
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.nio.file.SimpleFileVisitor

object PlatformFileIO {
  def readAllBytes(uri: URI): Array[Byte] =
    InputStreamIO.readBytes(uri.toURL.openStream())

  def readAllBytes(path: AbsolutePath): Array[Byte] =
    Files.readAllBytes(path.toNIO)

  def slurp(path: AbsolutePath, charset: Charset): String =
    scala.io.Source.fromFile(path.toFile)(scala.io.Codec(charset)).mkString

  def listFiles(path: AbsolutePath): ListFiles =
    new ListFiles(path, Option(path.toFile.list()).toList.flatten.map(RelativePath.apply))

  def isFile(path: AbsolutePath): Boolean =
    Files.isRegularFile(path.path)

  def isDirectory(path: AbsolutePath): Boolean =
    Files.isDirectory(path.path)

  def listAllFilesRecursively(root: AbsolutePath): ListFiles = {
    import scala.collection.JavaConverters._
    val relativeFiles = Files
      .walk(root.toNIO)
      .iterator()
      .asScala
      .collect {
        case path if Files.isRegularFile(path) =>
          RelativePath(root.path.relativize(path))
      }
      .toSeq
    new ListFiles(root, relativeFiles)
  }
}

package scala.meta.internal.io

import java.net.URI
import java.nio.charset.Charset
import java.nio.file.FileVisitOption
import scala.meta.io._
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.nio.file.SimpleFileVisitor
import java.util.stream.Collectors

object PlatformFileIO {
  def readAllBytes(uri: URI): Array[Byte] =
    InputStreamIO.readBytes(uri.toURL.openStream())

  def readAllBytes(path: AbsolutePath): Array[Byte] =
    Files.readAllBytes(path.toNIO)

  def slurp(path: AbsolutePath, charset: Charset): String =
    scala.io.Source.fromFile(path.toFile)(scala.io.Codec(charset)).mkString

  def listFiles(path: AbsolutePath): ListFiles =
    new ListFiles(path, Option(path.toFile.list()).toList.flatten.map(RelativePath.apply))

  def isFile(path: AbsolutePath): Boolean =
    Files.isRegularFile(path.path)

  def isDirectory(path: AbsolutePath): Boolean =
    Files.isDirectory(path.path)

  def listAllFilesRecursively(root: AbsolutePath): ListFiles = {
    import scala.collection.JavaConverters._
    val relativeFiles = Files
      .walk(root.toNIO)
      .collect(Collectors.toList[Path])
      .asScala
      .collect {
        case path if Files.isRegularFile(path) =>
          RelativePath(root.path.relativize(path))
      }
    new ListFiles(root, relativeFiles)
  }
}

Use nio collectors to safely close stream.


addSbtPlugin("com.47deg" % "sbt-microsites" % "0.7.23")
addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.9.0")
addSbtPlugin("com.eed3si9n" % "sbt-unidoc" % "0.4.2")
addSbtPlugin("com.github.gseitz" % "sbt-release" % "1.0.9")
addSbtPlugin("com.github.tkawachi" % "sbt-doctest" % "0.9.2")
addSbtPlugin("com.jsuereth" % "sbt-pgp" % "1.1.2")
addSbtPlugin("com.typesafe" % "sbt-mima-plugin" % "0.3.0")
addSbtPlugin("org.portable-scala" % "sbt-scala-native-crossproject" % "0.6.0")
addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "0.6.0")
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "0.6.28")
addSbtPlugin("org.scala-native" % "sbt-scala-native" % "0.3.9")
addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.5.1")
addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "2.3")

addSbtPlugin("com.47deg" % "sbt-microsites" % "0.7.23")
addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.9.0")
addSbtPlugin("com.eed3si9n" % "sbt-unidoc" % "0.4.2")
addSbtPlugin("com.github.gseitz" % "sbt-release" % "1.0.9")
addSbtPlugin("com.github.tkawachi" % "sbt-doctest" % "0.9.2")
addSbtPlugin("com.jsuereth" % "sbt-pgp" % "1.1.2")
addSbtPlugin("com.typesafe" % "sbt-mima-plugin" % "0.3.0")
addSbtPlugin("org.portable-scala" % "sbt-scala-native-crossproject" % "0.6.1")
addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "0.6.1")
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "0.6.28")
addSbtPlugin("org.scala-native" % "sbt-scala-native" % "0.3.9")
addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.5.1")
addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "2.3")

Update sbt-scala-native-crossproject, ... to 0.6.1


resolvers += Resolver.url("artifactory", url("http://scalasbt.artifactoryonline.com/scalasbt/sbt-plugin-releases"))(Resolver.ivyStylePatterns)

addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "0.4.2")

addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.10.0")

addSbtPlugin("com.openstudy" % "sbt-resource-management" % "0.4.1-SNAPSHOT")

addSbtPlugin("net.virtual-void" % "sbt-dependency-graph" % "0.7.4")

resolvers += Resolver.url("artifactory", url("http://scalasbt.artifactoryonline.com/scalasbt/sbt-plugin-releases"))(Resolver.ivyStylePatterns)

addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "0.4.2")

addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.10.0")

addSbtPlugin("com.openstudy" % "sbt-resource-management" % "0.4.2")

addSbtPlugin("net.virtual-void" % "sbt-dependency-graph" % "0.7.4")

Use release 0.4.2 of sbt-resource-management.


// Comment to get more information during initialization
logLevel := Level.Warn

// https://github.com/scoverage/sbt-scoverage/releases
addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.6.0")

// https://github.com/scoverage/sbt-coveralls/releases
addSbtPlugin("org.scoverage" % "sbt-coveralls" % "1.2.7")

// https://github.com/codacy/sbt-codacy-coverage/releases
addSbtPlugin("com.codacy" % "sbt-codacy-coverage" % "1.3.15")

// https://github.com/scalameta/scalafmt
addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.0.0")

// Comment to get more information during initialization
logLevel := Level.Warn

// https://github.com/scoverage/sbt-scoverage/releases
addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.6.1")

// https://github.com/scoverage/sbt-coveralls/releases
addSbtPlugin("org.scoverage" % "sbt-coveralls" % "1.2.7")

// https://github.com/codacy/sbt-codacy-coverage/releases
addSbtPlugin("com.codacy" % "sbt-codacy-coverage" % "1.3.15")

// https://github.com/scalameta/scalafmt
addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.0.0")

Upgrade sbt-scoverage plugin to version 1.6.1

This version uses scoverage 1.4.1 by default, which fixes an incompatiblity
with Scala 2.13.1, but is no longer compatible with Scala 2.13.0.


resolvers += Classpaths.sbtPluginReleases

resolvers += "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/"

resolvers += Resolver.url(
  "tpolecat-sbt-plugin-releases",
    url("http://dl.bintray.com/content/tpolecat/sbt-plugin-releases"))(
        Resolver.ivyStylePatterns)

addSbtPlugin("org.tpolecat" % "tut-plugin" % "0.6.9")

addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.5.1")

addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "5.2.4")

addSbtPlugin("com.github.gseitz" % "sbt-release" % "1.0.10")

addSbtPlugin("com.jsuereth" % "sbt-pgp" % "1.1.2")

addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "2.0")

addSbtPlugin("com.typesafe" % "sbt-mima-plugin" % "0.3.0")

addSbtPlugin("org.scalariform" % "sbt-scalariform" % "1.8.2")

addSbtPlugin("org.scala-js" % "sbt-scalajs" % "0.6.25")

addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "0.5.0")

resolvers += Classpaths.sbtPluginReleases

resolvers += "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/"

resolvers += Resolver.url(
  "tpolecat-sbt-plugin-releases",
    url("http://dl.bintray.com/content/tpolecat/sbt-plugin-releases"))(
        Resolver.ivyStylePatterns)

addSbtPlugin("org.tpolecat" % "tut-plugin" % "0.6.9")

addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.5.1")

addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "5.2.4")

addSbtPlugin("com.github.gseitz" % "sbt-release" % "1.0.10")

addSbtPlugin("com.jsuereth" % "sbt-pgp" % "1.1.2")

addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "2.0")

addSbtPlugin("com.typesafe" % "sbt-mima-plugin" % "0.3.0")

addSbtPlugin("org.scalariform" % "sbt-scalariform" % "1.8.2")

addSbtPlugin("org.scala-js" % "sbt-scalajs" % "0.6.26")

addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "0.5.0")

Update sbt-scalajs, scalajs-compiler, scalajs-library... to 0.6.26


package lore.types

import lore.execution.Context

case class LabelType(name: String, supertype: Type) extends Type {
  override def isSubtype(other: Type): Boolean = this == other || supertype.isSubtype(other)
  override def directDeclaredSubtypes(implicit context: Context) = {
    context.types.values.filter(_.isInstanceOf[LabelType]).map(_.asInstanceOf[LabelType]).filter(_.supertype == this).toSet
  }
  override def isAbstract = true // TODO: Really?
  override def toString = s"$name"
  override def verbose = s"$toString < $supertype"
}

package lore.types

import lore.execution.Context

case class LabelType(name: String, supertype: Type) extends Type {
  override def isSubtype(other: Type): Boolean = {
    other match {
      case LabelType(_, _) => this == other || supertype.isSubtype(other)
      case _ => other.isSupertype(this) || supertype.isSubtype(other)
    }
  }

  override def directDeclaredSubtypes(implicit context: Context) = {
    context.types.values.filter(_.isInstanceOf[LabelType]).map(_.asInstanceOf[LabelType]).filter(_.supertype == this).toSet
  }
  override def isAbstract = true // TODO: Really?
  override def toString = s"$name"
  override def verbose = s"$toString < $supertype"
}

Fix label type subtyping regarding sum types.


package io.github.bamos

object Whitelist {
  val users = Seq(
    "adius",
    "adobe-research",
    "ajn123",
    "bamos",
    "bryangarza",
    "cmusatyalab",
    "darksigma",
    "docker",
    "jebes",
    "HackathonHackers",
    "hamiltont",
    "ObeliskIsHuge",
    "rhema",
    "snowplow",
    "tejasmanohar",
    "themattman",
    "VT-Magnum-Research",
    "WalnutiQ",
    "zmughal",
    "geotrellis",
    "twitter",
    "github",
    "facebook",
    "etsy",
    "square",
    "amplab",
    "fnothaft",
    "bigdatagenomics",
    "homebrew",
    "puppetlabs",
    "rails",
    "google",
    "okfn",
    "humblesoftware",
    "ecomfe",
    "mozilla",
    "spine",
    "jez",
    "haskell",
    "coreos",
    "scotty-web",
    "vishnuravi",
    "cimpress-mcp",
    "creativecommons",
    "cc-archive"
  ).map(_.toLowerCase)
}

package io.github.bamos

object Whitelist {
  val users = Seq(
  "HackathonHackers",
  "ObeliskIsHuge",
  "VT-Magnum-Research",
  "WalnutiQ",
  "adius",
  "adobe-research",
  "ajn123",
  "amplab",
  "bamos",
  "bigdatagenomics",
  "bryangarza",
  "cc-archive",
  "cimpress-mcp",
  "cjwelborn",
  "cmusatyalab",
  "coreos",
  "creativecommons",
  "darksigma",
  "docker",
  "ecomfe",
  "etsy",
  "facebook",
  "fnothaft",
  "geotrellis",
  "github",
  "google",
  "hamiltont",
  "haskell",
  "homebrew",
  "humblesoftware",
  "jebes",
  "jez",
  "mozilla",
  "okfn",
  "puppetlabs",
  "rails",
  "rhema",
  "scotty-web",
  "snowplow",
  "spine",
  "square",
  "tejasmanohar",
  "themattman",
  "twitter",
  "vishnuravi",
  "welbornprod",
  "zmughal"
  ).map(_.toLowerCase)
}

Sort and add cjwelborn and welbornprod to the list


package lore.compiler.typing

import lore.compiler.test.BaseSpec

class SubtypingTypingSpec extends BaseSpec {

  private val fragmentBase = "typing"

  s"$fragmentBase/subtyping_errors" should "be compiled with typing errors" in {
    assertCompilationErrorMessages(s"$fragmentBase/subtyping_errors.lore")(
      ("This expression has the illegal type `A`. We expected the following type (or a subtype thereof): B.", 13),
      ("This expression has the illegal type `Ox`. We expected the following type (or a subtype thereof): Fox.", 20),
      ("This expression has the illegal type `Unit`. We expected the following type (or a subtype thereof): Real.", 25),
      ("This expression has the illegal type `Real`. We expected the following type (or a subtype thereof): String.", 31),
      ("This expression has the illegal type `Animal`. We expected the following type (or a subtype thereof): Fox.", 40),
    )
  }

}

package lore.compiler.typing

import lore.compiler.test.BaseSpec

class SubtypingTypingSpec extends BaseSpec {

  private val fragmentBase = "typing"

  s"$fragmentBase/subtyping_errors" should "be compiled with typing errors" in {
    assertCompilationErrorMessages(s"$fragmentBase/subtyping_errors.lore")(
      ("`shape.prop` has the illegal type `A`. We expected the following type (or a subtype thereof): B.", 13),
      ("`Ox()` has the illegal type `Ox`. We expected the following type (or a subtype thereof): Fox.", 20),
      ("`test()` has the illegal type `Unit`. We expected the following type (or a subtype thereof): Real.", 25),
      ("`pi()` has the illegal type `Real`. We expected the following type (or a subtype thereof): String.", 31),
      ("`advance(fox)` has the illegal type `Animal`. We expected the following type (or a subtype thereof): Fox.", 40),
    )
  }

}

Fix test after error message changes.

Compiler: Fix test after error message changes.