package io.flow.lint.linters

import io.flow.lint.Linter
import com.bryzek.apidoc.spec.v0.models.{Field, Model, Service}

/**
  * For well known field names, enforce specific types to ensure
  * consistency. For example, all fields named 'id' must be
  * strings.
  */
case object CommonFieldTypes extends Linter with Helpers {

  val Expected = Map(
    "id" -> "string",      // we use string identifiers for all of our resources
    "number" -> "string",  // 'number' is the external unique identifier
    "guid" -> "uuid",
    "email" -> "string"
  )

  override def validate(service: Service): Seq[String] = {
    service.models.flatMap(validateModel(service, _))
  }

  def validateModel(service: Service, model: Model): Seq[String] = {
    model.fields.flatMap(validateFieldType(service, model, _))
  }

  def validateFieldType(service: Service, model: Model, field: Field): Seq[String] = {
    Expected.get(field.name) match {
      case None => {
        Nil
      }
      case Some(exp) => {
        exp == field.`type` match {
          case true => {
            Nil
          }
          case false => {
            Seq(error(model, field, s"Type must be '$exp' and not ${field.`type`}"))
          }
        }
      }
    }
  }

}

package io.flow.lint.linters

import io.flow.lint.Linter
import com.bryzek.apidoc.spec.v0.models.{Field, Model, Service}

/**
  * For well known field names, enforce specific types to ensure
  * consistency. For example, all fields named 'id' must be
  * strings.
  */
case object CommonFieldTypes extends Linter with Helpers {

  val Expected = Map(
    "id" -> "string",      // we use string identifiers for all of our resources
    "number" -> "string",  // 'number' is the external unique identifier
    "guid" -> "uuid",
    "email" -> "string"
  )

  override def validate(service: Service): Seq[String] = {
    service.models.
      filter(m => !ignored(m.attributes, "common_field_types")).
      flatMap(validateModel(service, _))
  }

  def validateModel(service: Service, model: Model): Seq[String] = {
    model.fields.flatMap(validateFieldType(service, model, _))
  }

  def validateFieldType(service: Service, model: Model, field: Field): Seq[String] = {
    Expected.get(field.name) match {
      case None => {
        Nil
      }
      case Some(exp) => {
        exp == field.`type` match {
          case true => {
            Nil
          }
          case false => {
            Seq(error(model, field, s"Type must be '$exp' and not ${field.`type`}"))
          }
        }
      }
    }
  }

}

Add hint to ignore common_field_types

Add hint to ignore common_field_types


package composition

import com.google.inject.name.Names
import com.tzavellas.sse.guice.ScalaModule
import play.api.{Logger, LoggerLike}
import uk.gov.dvla.vehicles.presentation.common.filters.AccessLoggingFilter._

final class LoggerLikeBinding extends ScalaModule {

  def configure() = bind[LoggerLike].annotatedWith(Names.named(AccessLoggerName)).toInstance(Logger("dvla.common.AccessLogger"))
}

package composition

import com.google.inject.name.Names
import uk.gov.dvla.vehicles.presentation.common
import common.filters.{AccessLoggingConfig, DefaultAccessLoggingConfig}
import com.tzavellas.sse.guice.ScalaModule
import play.api.{Logger, LoggerLike}
import uk.gov.dvla.vehicles.presentation.common.filters.AccessLoggingFilter._

final class LoggerLikeBinding extends ScalaModule {

  def configure() = {
    bind[LoggerLike].annotatedWith(Names.named(AccessLoggerName)).toInstance(Logger("dvla.common.AccessLogger"))
    bind[AccessLoggingConfig].toInstance(new DefaultAccessLoggingConfig())
  }
}

Fix the exception cases for the access logging


package dotty.tools
package dotc
package config

import core.Decorators.*
import util.Property

enum SourceVersion:
  case `3.0-migration`, `3.0`, `3.1` // Note: do not add `3.1-migration` here, 3.1 is the same language as 3.0.
  case `3.2-migration`, `3.2`
  case `future-migration`, `future`

  val isMigrating: Boolean = toString.endsWith("-migration")

  def stable: SourceVersion =
    if isMigrating then SourceVersion.values(ordinal + 1) else this

  def isAtLeast(v: SourceVersion) = stable.ordinal >= v.ordinal

object SourceVersion extends Property.Key[SourceVersion]:
  def defaultSourceVersion = `3.0`

  /** language versions that may appear in a language import, are deprecated, but not removed from the standard library. */
  val illegalSourceVersionNames = List("3.1-migration").map(_.toTermName)

  /** language versions that the compiler recognises. */
  val validSourceVersionNames = values.toList.map(_.toString.toTermName)

  /** All source versions that can be recognised from a language import. e.g. `import language.3.1` */
  val allSourceVersionNames = validSourceVersionNames ::: illegalSourceVersionNames
end SourceVersion

package dotty.tools
package dotc
package config

import core.Decorators.*
import util.Property

enum SourceVersion:
  case `3.0-migration`, `3.0`, `3.1` // Note: do not add `3.1-migration` here, 3.1 is the same language as 3.0.
  case `3.2-migration`, `3.2`
  case `future-migration`, `future`

  val isMigrating: Boolean = toString.endsWith("-migration")

  def stable: SourceVersion =
    if isMigrating then SourceVersion.values(ordinal + 1) else this

  def isAtLeast(v: SourceVersion) = stable.ordinal >= v.ordinal

object SourceVersion extends Property.Key[SourceVersion]:
  def defaultSourceVersion = `3.2`

  /** language versions that may appear in a language import, are deprecated, but not removed from the standard library. */
  val illegalSourceVersionNames = List("3.1-migration").map(_.toTermName)

  /** language versions that the compiler recognises. */
  val validSourceVersionNames = values.toList.map(_.toString.toTermName)

  /** All source versions that can be recognised from a language import. e.g. `import language.3.1` */
  val allSourceVersionNames = validSourceVersionNames ::: illegalSourceVersionNames
end SourceVersion

Set default source version to 3.2

Set default source version to 3.2


import com.typesafe.tools.mima.core._

object MiMaFilters {
  val Library: Seq[ProblemFilter] = Seq(
    // Experimental APIs that can be added in 3.2.0 or later
    ProblemFilters.exclude[ReversedMissingMethodProblem]("scala.quoted.Quotes#reflectModule#SymbolMethods.asQuotes"),
    ProblemFilters.exclude[DirectMissingMethodProblem]("scala.quoted.Quotes#reflectModule#SymbolMethods.asQuotes"),
    ProblemFilters.exclude[ReversedMissingMethodProblem]("scala.quoted.Quotes#reflectModule#TypeReprMethods.typeArgs"),
    ProblemFilters.exclude[DirectMissingMethodProblem]("scala.deriving.Mirror.fromProductTyped"),
    ProblemFilters.exclude[DirectMissingMethodProblem]("scala.deriving.Mirror.fromTuple"),
    ProblemFilters.exclude[ReversedMissingMethodProblem]("scala.quoted.Quotes#reflectModule#ClassDefModule.apply"),
    ProblemFilters.exclude[DirectMissingMethodProblem]("scala.quoted.Quotes#reflectModule#ClassDefModule.apply"),
    ProblemFilters.exclude[ReversedMissingMethodProblem]("scala.quoted.Quotes#reflectModule#SymbolModule.newClass"),
    ProblemFilters.exclude[DirectMissingMethodProblem]("scala.quoted.Quotes#reflectModule#SymbolModule.newClass"),
    ProblemFilters.exclude[ReversedMissingMethodProblem]("scala.quoted.Quotes#reflectModule#SymbolMethods.typeRef"),
    ProblemFilters.exclude[DirectMissingMethodProblem]("scala.quoted.Quotes#reflectModule#SymbolMethods.typeRef"),
    ProblemFilters.exclude[ReversedMissingMethodProblem]("scala.quoted.Quotes#reflectModule#SymbolMethods.termRef"),
    ProblemFilters.exclude[DirectMissingMethodProblem]("scala.quoted.Quotes#reflectModule#SymbolMethods.termRef"),
    ProblemFilters.exclude[ReversedMissingMethodProblem]("scala.quoted.Quotes#reflectModule#TypeTreeModule.ref"),
    ProblemFilters.exclude[DirectMissingMethodProblem]("scala.quoted.Quotes#reflectModule#TypeTreeModule.ref"),

    // TupledFunction
    ProblemFilters.exclude[MissingClassProblem]("scala.runtime.TupledFunctions"),
    ProblemFilters.exclude[MissingClassProblem]("scala.runtime.TupledFunctions$"),
    ProblemFilters.exclude[MissingClassProblem]("scala.util.TupledFunction"),
    ProblemFilters.exclude[MissingClassProblem]("scala.util.TupledFunction$"),

    // Private inner classes, but we emit all classes as public in Java bytecode
    ProblemFilters.exclude[InaccessibleClassProblem]("scala.quoted.FromExpr$PrimitiveFromExpr"),
    ProblemFilters.exclude[InaccessibleClassProblem]("scala.quoted.Type$ValueOf$"),
    ProblemFilters.exclude[InaccessibleClassProblem]("scala.reflect.Selectable$DefaultSelectable"),
  )
}

import com.typesafe.tools.mima.core._

object MiMaFilters {
  val Library: Seq[ProblemFilter] = Seq(
  )
}

Remove excluded filters from mima

Remove excluded filters from mima


name := "deadbolt-java"

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

scalaVersion := "2.12.7"

crossScalaVersions := Seq("2.12.7", "2.13.0-M5")

organization := "be.objectify"

libraryDependencies ++= Seq(
  "org.mockito" % "mockito-all" % "1.10.19" % "test",
  "org.awaitility" % "awaitility" % "3.0.0" % "test"
)

releasePublishArtifactsAction := PgpKeys.publishSigned.value

// workaround for scaladoc error https://github.com/scala/scala-dev/issues/249
// also see http://www.scala-lang.org/news/2.12.0/#scaladoc-can-be-used-to-document-java-sources
scalacOptions in (Compile, doc) += "-no-java-comments"

javacOptions += "-Xlint:deprecation"
scalacOptions += "-deprecation"

resolvers += Resolver.sonatypeRepo("snapshots")

name := "deadbolt-java"

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

scalaVersion := "2.12.7"

crossScalaVersions := Seq("2.12.7", "2.13.0-M5")

organization := "be.objectify"

libraryDependencies ++= Seq(
  "org.mockito" % "mockito-all" % "1.10.19" % "test",
  "org.awaitility" % "awaitility" % "3.0.0" % "test"
)

releasePublishArtifactsAction := PgpKeys.publishSigned.value

// workaround for scaladoc error https://github.com/scala/scala-dev/issues/249
// also see http://www.scala-lang.org/news/2.12.0/#scaladoc-can-be-used-to-document-java-sources
scalacOptions in (Compile, doc) ++= {
  if (scalaBinaryVersion.value == "2.12") Seq("-no-java-comments") else Nil
}

javacOptions += "-Xlint:deprecation"
scalacOptions += "-deprecation"

resolvers += Resolver.sonatypeRepo("snapshots")

Revert "Change scala bug workaround to work with Scala 2.13"

This reverts commit adb3d5b5cdf697fe01adc843b5c0df4384eb67d1.


package org.talkingpuffin.time

import java.util.Date
import org.joda.time.{DateTime, Seconds}
import org.talkingpuffin.state.{PrefKeys, GlobalPrefs}
import org.joda.time.format.DateTimeFormat
import org.talkingpuffin.ui.HtmlFormatter

object TimeUtil{
  val fmt = DateTimeFormat.forPattern("MM/dd HH:mm:ss")
  val fmtNoDay = DateTimeFormat.forPattern("HH:mm:ss")
  def formatAge(date: Date) : String  = formatAge(new DateTime(date))
  def formatAge(date: DateTime): String = {
    if (showAsAge_?)
      new TimeFormatter(toAge(date)).colonSeparated
    else
      if (isToday(date)) fmtNoDay.print(date) else fmt.print(date)
  }
  def showAsAge_? = GlobalPrefs.isOn(PrefKeys.SHOW_TWEET_DATE_AS_AGE)
  def isToday(d1: DateTime):Boolean = {
     val now = new DateTime()
     d1.getDayOfYear == now.getDayOfYear &&  d1.getYear == now.getYear
  }
  def toAge(date: DateTime) : Long=  Seconds.secondsBetween(date,now).getSeconds
  def now = new DateTime

  def asHTML(value : Any) : String = asHTML(value.asInstanceOf[Date])
  def asHTML(time :  Date) :String = {
   HtmlFormatter.htmlAround("" +
       formatAge(time) + "")
   }
}

package org.talkingpuffin.time

import java.util.Date
import org.joda.time.{DateTime, Seconds}
import org.talkingpuffin.state.{PrefKeys, GlobalPrefs}
import org.joda.time.format.DateTimeFormat
import org.talkingpuffin.ui.HtmlFormatter

object TimeUtil{
  val fmt = DateTimeFormat.forPattern("MM/dd HH:mm:ss")
  val fmtNoDay = DateTimeFormat.forPattern("HH:mm:ss")
  def formatAge(date: Date): String  = formatAge(new DateTime(date))
  def formatAge(date: DateTime): String = {
    if (showAsAge_?)
      new TimeFormatter(toAge(date)).colonSeparated
    else
      if (isToday(date)) fmtNoDay.print(date) else fmt.print(date)
  }
  def showAsAge_? = GlobalPrefs.isOn(PrefKeys.SHOW_TWEET_DATE_AS_AGE)
  def isToday(d1: DateTime): Boolean = {
     val now = new DateTime()
     d1.getDayOfYear == now.getDayOfYear && d1.getYear == now.getYear
  }
  def toAge(date: DateTime): Long = Seconds.secondsBetween(date,now).getSeconds
  def now = new DateTime
  def asHTML(value: Any): String = asHTML(value.asInstanceOf[Date])
  def asHTML(time: Date): String = {
   HtmlFormatter.htmlAround("" +
       formatAge(time) + "")
   }
}

Fix from Leif and formatting corrections.


package lila.blog

import scala.concurrent.duration._

final class LastPostCache(api: BlogApi, ttl: Duration, collection: String) {

  private val cache = lila.memo.MixedCache.single[List[MiniPost]](
    api.prismicApi flatMap { prismic =>
      api.recent(prismic, none, 3) map {
        _ ?? {
          _.results.toList flatMap MiniPost.fromDocument(collection)
        }
      }
    },
    timeToLive = ttl,
    default = Nil,
    awaitTime = 1.millisecond)

  def apply = cache get true
  // def apply = List.empty[MiniPost]

  private[blog] def clear {
    cache invalidate true
  }
}

package lila.blog

import scala.concurrent.duration._

final class LastPostCache(api: BlogApi, ttl: Duration, collection: String) {

  private val cache = lila.memo.MixedCache.single[List[MiniPost]](
    api.prismicApi flatMap { prismic =>
      api.recent(prismic, none, 3) map {
        _ ?? {
          _.results.toList flatMap MiniPost.fromDocument(collection)
        }
      }
    },
    timeToLive = ttl,
    default = Nil,
    awaitTime = 1.millisecond)

  def apply = cache get true

  private[blog] def clear {
    cache invalidate true
  }
}

Revert "disable last blog posts cache"

Revert "disable last blog posts cache"

This reverts commit 7981dc342c1efa85d35b129c209ccddeb5cd2a69.


import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.streaming.StreamingContext
import com.datastax.driver.spark._
import org.apache.spark.streaming.Seconds

object test extends App {
  val sparkConf = new SparkConf(true)
  .set("cassandra.connection.host", "127.0.0.1")
  .setMaster("local[2]")
  .setAppName("spark-driver-demo")

  val sc = new SparkContext("local[2]", "test", sparkConf)
  val ssc =  new StreamingContext(sparkConf, Seconds(1))
  val allstarfull = sc.cassandraTable("demo", "allstarfull")

  println("count: " + allstarfull.count)

  //allstarful.foreach(println(_))
println("first: " + allstarfull.first)
}

import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.streaming.StreamingContext
import com.datastax.driver.spark._
import org.apache.spark.streaming.Seconds

object test extends App {
  val sparkConf = new SparkConf(true)
  .set("cassandra.connection.host", "127.0.0.1")
  .setMaster("local[2]")
  .setAppName("spark-driver-demo")

  val sc = new SparkContext("local[2]", "test", sparkConf)
  val ssc =  new StreamingContext(sparkConf, Seconds(1))
  val allstarfull = sc.cassandraTable("cassandra_spark_mlbdata", "allstarfull")

  println("count: " + allstarfull.count)

  //allstarful.foreach(println(_))
println("first: " + allstarfull.first)
}

Update keyspace to match creation scripts.


package code
package service

import code.model.Project
import code.model.Task
import net.liftweb.mapper.By
import net.liftweb.common.Empty

object ProjectService {

  def getDisplayName(project: Project): String = {
    val parentProject = Project.findByKey(project.parent.get)
    if (parentProject.isEmpty) {
      project.name.get
    } else {
      getDisplayName(parentProject.get) + "-" + project.name
    }
  }

  def move(what: Project, newParent: Project) = what.parent(newParent).save

  def moveToRoot(what: Project) = what.parent(Empty).save

  def isEmpty(project: Project) = Task.findAll(By(Task.parent, project)).isEmpty && Project.findAll(By(Project.parent, project)).isEmpty

  def delete(project: Project) = {
    if (isEmpty(project)) {
      project.delete_!
    } else {
      throw new IllegalArgumentException("Projects with Tasks or Subprojects can not be deleted.");
    }
  }

}

package code
package service

import code.model.Project
import code.model.Task
import net.liftweb.mapper.By
import net.liftweb.common.{Box, Full, Empty}

object ProjectService {

  def getDisplayName(project: Project): String = {
    def loop(z: List[Project], box: Box[Project]): List[Project] = box match {
      case Full(p) => loop(p :: z, Project.findByKey(p.parent.get))
      case _ => z
    }
    loop(Nil, Full(project)).map(_.name).mkString("-")
  }

  def move(what: Project, newParent: Project) = what.parent(newParent).save

  def moveToRoot(what: Project) = what.parent(Empty).save

  def isEmpty(project: Project) = Task.findAll(By(Task.parent, project)).isEmpty && Project.findAll(By(Project.parent, project)).isEmpty

  def delete(project: Project) = {
    if (isEmpty(project)) {
      project.delete_!
    } else {
      throw new IllegalArgumentException("Projects with Tasks or Subprojects can not be deleted.");
    }
  }

}

Refactor to terminate compiler warnings.


// the application itself
lazy val app = project
  .in(file("."))
  .settings(
    name := "my-app",
    libraryDependencies += "com.typesafe" % "config" % "1.3.0"
  )

// --------------------------------------
// -------- Package Submodules ----------
// --------------------------------------
lazy val testPackage = project
  .in(file("build/test"))
  .enablePlugins(JavaAppPackaging)
  .settings(
    resourceDirectory in Compile := (resourceDirectory in (app, Compile)).value,
    mappings in Universal += {
      ((resourceDirectory in Compile).value / "test.conf") -> "conf/application.conf"
    }
  )
  .dependsOn(app)

lazy val stagePackage = project
  .in(file("build/stage"))
  .enablePlugins(JavaAppPackaging)
  .settings(
    resourceDirectory in Compile := (resourceDirectory in (app, Compile)).value,
    mappings in Universal += {
      ((resourceDirectory in Compile).value / "stage.conf") -> "conf/application.conf"
    }
  )
  .dependsOn(app)

lazy val prodPackage = project
  .in(file("build/prod"))
  .enablePlugins(JavaAppPackaging)
  .settings(
    resourceDirectory in Compile := (resourceDirectory in (app, Compile)).value,
    mappings in Universal += {
      ((resourceDirectory in Compile).value / "prod.conf") -> "conf/application.conf"
    }
  )
  .dependsOn(app)

// the application itself
lazy val app = project
  .in(file("."))
  .settings(
    name := "my-app",
    libraryDependencies += "com.typesafe" % "config" % "1.3.0"
  )

// --------------------------------------
// -------- Package Submodules ----------
// --------------------------------------
lazy val testPackage = project
  .in(file("build/test"))
  .enablePlugins(JavaAppPackaging)
  .settings(
    Compile / mainClass := (app / Compile / mainClass).value,
    Compile / resourceDirectory := (app / Compile / resourceDirectory).value,
    Universal / mappings += {
      ((resourceDirectory in Compile).value / "test.conf") -> "conf/application.conf"
    }
  )
  .dependsOn(app)

lazy val stagePackage = project
  .in(file("build/stage"))
  .enablePlugins(JavaAppPackaging)
  .settings(
    Compile / mainClass := (app / Compile / mainClass).value,
    Compile / resourceDirectory := (app / Compile / resourceDirectory).value,
    Universal / mappings += {
      ((resourceDirectory in Compile).value / "stage.conf") -> "conf/application.conf"
    }
  )
  .dependsOn(app)

lazy val prodPackage = project
  .in(file("build/prod"))
  .enablePlugins(JavaAppPackaging)
  .settings(
    Compile / mainClass := (app / Compile / mainClass).value,
    Compile / resourceDirectory := (app / Compile / resourceDirectory).value,
    Universal / mappings += {
      ((Compile / resourceDirectory).value / "prod.conf") -> "conf/application.conf"
    }
  )
  .dependsOn(app)

Add mainClass in Compile for test-stage-prod example


package lib

import java.io.FileOutputStream
import java.util.zip.{ZipEntry, ZipOutputStream}
import com.bryzek.apidoc.generator.v0.models.File

object Zipfile {

  private[this] val UTF8 = "UTF-8"

  def create(dirName: String, files: Seq[File]): java.io.File = {
    val path = java.io.File.createTempFile(dirName, ".zip")
    create(path, files, prefix = dirName + "/")
    path
  }

  def create(
    zip: java.io.File,
    files: Seq[File],
    prefix: String = ""
  ) {
    val zipOutputStream = new ZipOutputStream(new FileOutputStream(zip))
    files.foreach { f =>
      zipOutputStream.putNextEntry(new ZipEntry(s"$prefix${f.name}"))
      zipOutputStream.write(f.contents.getBytes(UTF8))
      zipOutputStream.closeEntry
    }
    zipOutputStream.close()
  }

}

package lib

import java.io.FileOutputStream
import java.util.zip.{ZipEntry, ZipOutputStream}
import com.bryzek.apidoc.generator.v0.models.File

object Zipfile {

  private[this] val UTF8 = "UTF-8"

  def create(dirName: String, files: Seq[File]): java.io.File = {
    val path = java.io.File.createTempFile(dirName, ".zip")
    createForFile(path, files, prefix = dirName + "/")
    path
  }

  private def createForFile(
    zip: java.io.File,
    files: Seq[File],
    prefix: String = ""
  ) {
    val zipOutputStream = new ZipOutputStream(new FileOutputStream(zip))
    files.foreach { f =>
      zipOutputStream.putNextEntry(new ZipEntry(s"$prefix${f.name}"))
      zipOutputStream.write(f.contents.getBytes(UTF8))
      zipOutputStream.closeEntry
    }
    zipOutputStream.close()
  }

}

Rename method instead of overloading

Rename method instead of overloading


import sbt._

class LiftJson(info: ProjectInfo) extends DefaultProject(info) {
  val specs      = "org.scala-tools.testing" % "specs" % "1.5.0"
  val scalacheck = "org.scala-tools.testing" % "scalacheck" % "1.5"

  override def ivyXML =
    <publications>
      <artifact name="lift-json" type="jar" ext="jar"/>
    </publications>
}

import sbt._

class LiftJson(info: ProjectInfo) extends DefaultProject(info) {
  val junit      = "junit" % "junit" % "4.5"
  val specs      = "org.scala-tools.testing" % "specs" % "1.5.0"
  val scalacheck = "org.scala-tools.testing" % "scalacheck" % "1.5"

  override def ivyXML =
    <publications>
      <artifact name="lift-json" type="jar" ext="jar"/>
    </publications>
}

Add junit as a dependency.

Add junit as a dependency.


import java.nio.file._
import sbt.nio.Keys._
import sbt.nio._
import scala.concurrent.duration._
import StandardCopyOption.{ REPLACE_EXISTING => replace }

watchTriggeredMessage := { (i, path: Path, c) =>
  val prev = watchTriggeredMessage.value
  if (path.getFileName.toString == "C.scala")
    throw new IllegalStateException("C.scala should not trigger")
  prev(i, path, c)
}

watchOnIteration := { i: Int =>
  val base = baseDirectory.value.toPath
  val src =
    base.resolve("src").resolve("main").resolve("scala").resolve("sbt").resolve("test")
  val changes = base.resolve("changes")
  Files.copy(changes.resolve("C.scala"), src.resolve("C.scala"), replace)
  if (i < 5) {
    val content =
      new String(Files.readAllBytes(changes.resolve("A.scala"))) + "\n" + ("//" * i)
    Files.write(src.resolve("A.scala"), content.getBytes)
  } else {
    Files.copy(changes.resolve("B.scala"), src.resolve("B.scala"), replace)
  }
  println(s"Waiting for changes...")
  Watch.Ignore
}

watchOnFileInputEvent := { (_, event: Watch.Event) =>
  if (event.path.getFileName.toString == "B.scala") Watch.CancelWatch
  else Watch.Trigger
}

watchAntiEntropy := 0.millis

import java.nio.file._
import java.nio.file.attribute.FileTime

import sbt.nio.Keys._
import sbt.nio._

import scala.concurrent.duration._

watchTriggeredMessage := { (i, path: Path, c) =>
  val prev = watchTriggeredMessage.value
  if (path.getFileName.toString == "C.scala")
    throw new IllegalStateException("C.scala should not trigger")
  prev(i, path, c)
}

watchOnIteration := { i: Int =>
  val base = baseDirectory.value.toPath
  val src =
    base.resolve("src").resolve("main").resolve("scala").resolve("sbt").resolve("test")
  val changes = base.resolve("changes")
  def copy(fileName: String): Unit = {
    val content =
      new String(Files.readAllBytes(changes.resolve(fileName))) + "\n" + ("//" * i)
    Files.write(src.resolve(fileName), content.getBytes)
  }
  val c = src.resolve("C.scala")
  Files.setLastModifiedTime(c, FileTime.fromMillis(Files.getLastModifiedTime(c).toMillis + 1111))
  if (i < 5) copy("A.scala")
  else copy("B.scala")
  println(s"Waiting for changes...")
  Watch.Ignore
}

watchOnFileInputEvent := { (_, event: Watch.Event) =>
  if (event.path.getFileName.toString == "B.scala") Watch.CancelWatch
  else Watch.Trigger
}

watchAntiEntropy := 0.millis

Make scripted watch/on-changes more robust

I noticed that sometimes this test hangs in ci. I think it may be
because sometimes the event for A got handled while the cache entry for
B.scala was invalidated. Because the test runs ~compile, the next run of
compile would then reset the cache entry for B.scala. The next run of
watchOnIteration invalidtes B.scala again, but this time to the same
hash, so it doesn't actually trigger a file input event. By changing the
content of B.scala every time, we ensure that it should still cause a
file event.

I haven't confirmed that this will fix the sporadic hangs because I
can't reproduce on my machine, but this change won't hurt.


package com.example.http4s
package blaze

import cats.effect._
import cats.implicits._

object BlazeHttp2Example extends IOApp {
  override def run(args: List[String]): IO[ExitCode] =
    BlazeSslExampleApp
      .builder[IO]
      .enableHttp2(true)
      .serve
      .compile
      .drain
      .as(ExitCode.Success)
}

package com.example.http4s
package blaze

import cats.effect._
import cats.implicits._

object BlazeHttp2Example extends IOApp {
  override def run(args: List[String]): IO[ExitCode] =
    BlazeSslExampleApp
      .builder[IO]
      .enableHttp2(true)
      .serve
      .compile
      .lastOrError
}

Update Example to not ignore App ExitCode


package com.webtrends.harness.service.test

import ch.qos.logback.classic.Level
import com.typesafe.config.Config
import com.webtrends.harness.component.Component
import com.webtrends.harness.service.Service
import org.specs2.mutable.SpecificationLike

/**
 * @author Michael Cuthbert on 5/28/15.
 */
trait BaseSpecTest extends SpecificationLike {
  implicit val config:Config
  implicit val componentMap:Option[Map[String, Class[_<:Component]]] = None
  implicit val servicesMap:Option[Map[String, Class[_<:Service]]] = None

  TestHarness(config, servicesMap, componentMap, Level.ALL)
  Thread.sleep(1000)
  implicit val system = TestHarness.system.get
}

package com.webtrends.harness.service.test

import ch.qos.logback.classic.Level
import com.typesafe.config.{Config, ConfigFactory}
import com.webtrends.harness.component.Component
import com.webtrends.harness.service.Service
import org.specs2.mutable.SpecificationLike

/**
 * @author Michael Cuthbert on 5/28/15.
 */
trait BaseSpecTest extends SpecificationLike {
  def config:Config = ConfigFactory.empty()
  def componentMap:Option[Map[String, Class[_<:Component]]] = None
  def servicesMap:Option[Map[String, Class[_<:Service]]] = None

  TestHarness(config, servicesMap, componentMap, Level.ALL)
  Thread.sleep(1000)
  implicit val system = TestHarness.system.get
}

Make all vals into defs

Make all vals into defs


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.0",
				"com.github.japgolly.android" % "svg-android" % "2.0.6",
				"com.jpardogo.materialtabstrip" % "library" % "1.0.6",
				"org.scala-lang" % "scala-reflect" % scalaVersion.value
			),
			name := "Toolbelt",
			organization := "com.taig.android",
			publishArtifact in ( Compile, packageDoc ) := false,
			scalaVersion := "2.11.4",
			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.20-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.0",
				"com.github.japgolly.android" % "svg-android" % "2.0.6",
				"com.jpardogo.materialtabstrip" % "library" % "1.0.6",
				"org.scala-lang" % "scala-reflect" % scalaVersion.value
			),
			name := "Toolbelt",
			organization := "com.taig.android",
			publishArtifact in ( Compile, packageDoc ) := false,
			scalaVersion := "2.11.4",
			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.21-BETA",
			minSdkVersion in Android := "10",
			platformTarget in Android := "android-21",
			targetSdkVersion in Android := "21"
		)
}

Set project version to 0.3.21-BETA

Set project version to 0.3.21-BETA


resolvers ++= Seq(
  Classpaths.sbtPluginReleases,
  Resolver.sonatypeRepo("releases"),
  Resolver.bintrayIvyRepo("jetbrains", "sbt-plugins")
)

addSbtPlugin("org.scalameta" % "sbt-mdoc" % "2.2.22")
addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.4.3")
addSbtPlugin("com.github.sbt" % "sbt-ci-release" % "1.5.9")
addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.10.0")
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "1.1.0")
addSbtPlugin("org.scalameta" % "sbt-native-image" % "0.3.1")
addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.4.3")
addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "1.1.0")
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.7.0")
addSbtPlugin("com.typesafe" % "sbt-mima-plugin" % "1.0.0")
addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "1.8.1")

resolvers ++= Seq(
  Classpaths.sbtPluginReleases,
  Resolver.sonatypeRepo("releases"),
  Resolver.bintrayIvyRepo("jetbrains", "sbt-plugins")
)

addSbtPlugin("org.scalameta" % "sbt-mdoc" % "2.2.23")
addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.4.3")
addSbtPlugin("com.github.sbt" % "sbt-ci-release" % "1.5.9")
addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.10.0")
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "1.1.0")
addSbtPlugin("org.scalameta" % "sbt-native-image" % "0.3.1")
addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.4.3")
addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "1.1.0")
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.7.0")
addSbtPlugin("com.typesafe" % "sbt-mima-plugin" % "1.0.0")
addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "1.8.1")

Update mdoc, sbt-mdoc to 2.2.23

Update mdoc, sbt-mdoc to 2.2.23


scalacOptions ++= Seq("-unchecked", "-deprecation", "-feature")

addSbtPlugin("com.geirsson"     % "sbt-scalafmt" % "1.5.0")
addSbtPlugin("com.typesafe.sbt" % "sbt-twirl"    % "1.3.15")
addSbtPlugin("com.eed3si9n"     % "sbt-assembly" % "0.14.8")
addSbtPlugin("org.scalatra.sbt" % "sbt-scalatra" % "1.0.1")
addSbtPlugin("com.jsuereth"     % "sbt-pgp"      % "1.1.2")
addSbtCoursier
addSbtPlugin("com.typesafe.sbt" % "sbt-license-report" % "1.2.0")

scalacOptions ++= Seq("-unchecked", "-deprecation", "-feature")

addSbtPlugin("com.geirsson"     % "sbt-scalafmt" % "1.5.0")
addSbtPlugin("com.typesafe.sbt" % "sbt-twirl"    % "1.3.15")
addSbtPlugin("com.eed3si9n"     % "sbt-assembly" % "0.14.8")
addSbtPlugin("org.scalatra.sbt" % "sbt-scalatra" % "1.0.3")
addSbtPlugin("com.jsuereth"     % "sbt-pgp"      % "1.1.2")
addSbtCoursier
addSbtPlugin("com.typesafe.sbt" % "sbt-license-report" % "1.2.0")

Bump sbt-scalatra plugin to 1.0.3

Bump sbt-scalatra plugin to 1.0.3


package xt.vc

import xt.Logger
import xt.vc.controller._
import xt.vc.view.Renderer

import org.jboss.netty.handler.codec.http._
import HttpHeaders.Names._
import HttpResponseStatus._

trait Controller extends ExtendedEnv with Logger with Net with ParamAccess with Url with Filter with Renderer {
  private var responded = false

  def respond = synchronized {
    if (responded) {
      throw new Exception("Double respond")
    } else {
      responded = true
      encodeCookies
      ctx.getChannel.write(this)
    }
  }

  /**
   * Returns 302 response.
   *
   * @param location Can be:
   * * absolute:                contains "://"
   * * relative to this domain: starts with "/"
   * * Controller#action:       contains "#"
   * * action:                  otherwise
   */
  def redirectTo(location: String, params: Any*) {
    response.setStatus(FOUND)

    val location2 = if (location.contains("://") || location.startsWith("/"))
      location
    else {
      urlFor(location, params)
    }

    HttpHeaders.setContentLength(response, 0)
    response.setHeader(LOCATION, location2)
    respond
  }

  //----------------------------------------------------------------------------

  private def encodeCookies {
    if (cookies != null && cookies.size > 0) {   // == null: CookieDecoder has not been run
      val encoder = new CookieEncoder(true)
      val iter = cookies.iterator
      while (iter.hasNext) encoder.addCookie(iter.next)
      response.setHeader(SET_COOKIE, encoder.encode)
    }
  }
}

package xt.vc

import xt.Logger
import xt.vc.controller._
import xt.vc.view.Renderer

import org.jboss.netty.handler.codec.http._
import HttpHeaders.Names._
import HttpResponseStatus._

trait Controller extends ExtendedEnv with Logger with Net with ParamAccess with Url with Filter with Renderer {
  private var responded = false

  def respond = synchronized {
    if (responded) {
      // Print the stack trace so that application developers know where to fix
      try {
        throw new Exception("Double respond")
      } catch {
        case e =>
          logger.error("Double respond", e)
      }
    } else {
      responded = true
      encodeCookies
      ctx.getChannel.write(this)
    }
  }

  /**
   * Returns 302 response.
   *
   * @param location Can be:
   * * absolute:                contains "://"
   * * relative to this domain: starts with "/"
   * * Controller#action:       contains "#"
   * * action:                  otherwise
   */
  def redirectTo(location: String, params: Any*) {
    response.setStatus(FOUND)

    val location2 = if (location.contains("://") || location.startsWith("/"))
      location
    else {
      urlFor(location, params)
    }

    HttpHeaders.setContentLength(response, 0)
    response.setHeader(LOCATION, location2)
    respond
  }

  //----------------------------------------------------------------------------

  private def encodeCookies {
    if (cookies != null && cookies.size > 0) {   // == null: CookieDecoder has not been run
      val encoder = new CookieEncoder(true)
      val iter = cookies.iterator
      while (iter.hasNext) encoder.addCookie(iter.next)
      response.setHeader(SET_COOKIE, encoder.encode)
    }
  }
}

Print the stack trace so that application developers know where to fix the double respond bug


package com.socrata.soda.server.resources

import com.socrata.http.server.routing.SimpleResource
import com.socrata.http.server.{HttpRequest, HttpResponse, HttpService}
import com.socrata.http.server.implicits._
import com.socrata.http.server.responses._
import com.socrata.soda.server._
import com.socrata.soda.server.SodaUtils
import com.socrata.soda.server.responses.HttpMethodNotAllowed
import org.apache.commons.codec.binary.Base64

class SodaResource extends SimpleResource {

  override def methodNotAllowed: HttpService = { req =>
    val allowed = allowedMethods
    Header("Allow", allowed.mkString(",")) ~> SodaUtils.response(
      req,
      HttpMethodNotAllowed(req.getMethod, allowed))
  }

  def user(req: HttpRequest): String = {
    val fromHeader = for {
      authenticate <- req.header("Authenticate")
      if authenticate.startsWith("Basic ")
    } yield new String(Base64.decodeBase64(authenticate.split(" ", 1)(1)), "latin1").split(":")(0)
    fromHeader.getOrElse {
      SodaResource.log.info("Unable to get user out of Authenticate header; going with `anonymous' for now")
      "anonymous"
    }
  }

  def optionalHeader(header: String, headerValue: Option[String]): HttpResponse =
    headerValue match {
      case Some(v) => Header(header, v)
      case None => Function.const(())
    }
}

object SodaResource {
  private val log = org.slf4j.LoggerFactory.getLogger(classOf[SodaResource])
}

package com.socrata.soda.server.resources

import com.socrata.http.server.routing.SimpleResource
import com.socrata.http.server.{HttpRequest, HttpResponse, HttpService}
import com.socrata.http.server.implicits._
import com.socrata.http.server.responses._
import com.socrata.soda.server._
import com.socrata.soda.server.SodaUtils
import com.socrata.soda.server.responses.HttpMethodNotAllowed
import org.apache.commons.codec.binary.Base64

class SodaResource extends SimpleResource {

  override def methodNotAllowed: HttpService = { req =>
    val allowed = allowedMethods
    Header("Allow", allowed.mkString(",")) ~> SodaUtils.response(
      req,
      HttpMethodNotAllowed(req.getMethod, allowed))
  }

  // SF doesn't handle auth, unlike what was originally envisionsed, but is still wired up to pass user info down
  // to DC, this could be used for debugging or ripped out.
  def user(req: HttpRequest): String = "anonymous"

  def optionalHeader(header: String, headerValue: Option[String]): HttpResponse =
    headerValue match {
      case Some(v) => Header(header, v)
      case None => Function.const(())
    }
}

object SodaResource {
  private val log = org.slf4j.LoggerFactory.getLogger(classOf[SodaResource])
}

Stop logging about not getting a user passed in, we know we don't do that.

We don't pass user infomation down to sf so it just logs a silly
message.   Not ripping it out entirely because that would also require changes
in DC... we certainly could easily start passing down a user for debugging info but that
wouldn't be in the Authorization header since it isn't auth.


package org.http4s.client.blaze

import scalaz.concurrent.Task

import org.http4s._

import org.specs2.mutable.After

// TODO: this should have a more comprehensive test suite
class ExternalBlazeHttp1ClientSpec extends Http4sSpec {

  private val simpleClient = SimpleHttp1Client()

  "Blaze Simple Http1 Client" should {
    "Make simple https requests" in {
      val resp = simpleClient.expect[String](uri("https://github.com/")).run
      resp.length mustNotEqual 0
    }
  }

  step {
    simpleClient.shutdown.run
  }

  private val pooledClient = PooledHttp1Client()

  "RecyclingHttp1Client" should {
    def fetchBody = pooledClient.toService(_.as[String]).local { uri: Uri => Request(uri = uri) }

    "Make simple https requests" in {
      val resp = fetchBody.run(uri("https://github.com/")).run
      resp.length mustNotEqual 0
    }

    "Repeat a simple https request" in {
      val f = (0 until 10).map(_ => Task.fork {
        val resp = fetchBody.run(uri("https://github.com/"))
        resp.map(_.length)
      })

      foreach(Task.gatherUnordered(f).run) { length =>
        length mustNotEqual 0
      }
    }
  }

  step {
    pooledClient.shutdown.run
  }
}

package org.http4s.client.blaze

import scala.concurrent.duration._
import scalaz.concurrent.Task

import org.http4s._

import org.specs2.mutable.After

// TODO: this should have a more comprehensive test suite
class ExternalBlazeHttp1ClientSpec extends Http4sSpec {
  private val timeout = 30.seconds

  private val simpleClient = SimpleHttp1Client()

  "Blaze Simple Http1 Client" should {
    "Make simple https requests" in {
      val resp = simpleClient.expect[String](uri("https://httpbin.org/get")).runFor(timeout)
      resp.length mustNotEqual 0
    }
  }

  step {
    simpleClient.shutdown.run
  }

  private val pooledClient = PooledHttp1Client()

  "RecyclingHttp1Client" should {
    def fetchBody = pooledClient.toService(_.as[String]).local { uri: Uri => Request(uri = uri) }

    "Make simple https requests" in {
      val resp = fetchBody.run(uri("https://github.com/")).run
      resp.length mustNotEqual 0
    }

    "Repeat a simple https request" in {
      val f = (0 until 10).map(_ => Task.fork {
        val resp = fetchBody.run(uri("https://github.com/"))
        resp.map(_.length)
      })

      foreach(Task.gatherUnordered(f).run) { length =>
        length mustNotEqual 0
      }
    }
  }

  step {
    pooledClient.shutdown.run
  }
}

Use httpbin.org for Blaze client external SSL test

When `AsyncHttpClientSpec` triggers `ThreadDumpOnTimeout`, the thread
dump often shows `ExternalBlazeHttp1ClientSpec` calling github.com in
the stack.  GitHub rate limits requests from Travis CI, so switch to
https://httpbin.org/get to see if that helps avoid timeouts.
Additional detail in http4s/http4s#909.

This is suggestion http4s/http4s#1 from @rossabaker [from Gitter](https://gitter.im/http4s/http4s?at=58a73413aa800ee52cabed70).


package tabulate

import java.io.StringWriter

import tabulate.engine.WriterEngine

object ops extends CsvInput.ToCsvInputOps
                   with CsvOutput.ToCsvOutputOps
                   with RowEncoder.ToRowEncoderOps
                   with CellEncoder.ToCellEncoderOps {
  implicit class CellDecoderOps(val str: String) extends AnyVal {
    def decodeCsvCell[A](implicit da: CellDecoder[A]): DecodeResult[A] = da.decode(str)
    def unsafeDecodeCsvCell[A](implicit da: CellDecoder[A]): A = da.unsafeDecode(str)
  }

  implicit class RowDecoderOps(val row: Seq[String]) extends AnyVal {
    def decodeCsvRow[A](implicit da: RowDecoder[A]): DecodeResult[A] = da.decode(row)
    def unsafeDecodeCsvRow[A](implicit da: RowDecoder[A]): A = da.unsafeDecode(row)
  }

  implicit class TraversableOps[A: RowEncoder](val rows: Traversable[A]) {
    def asCsv(sep: Char, header: Seq[String] = Seq.empty)(implicit engine: WriterEngine): String = {
      val out = new StringWriter()
      CsvWriter(out, sep, header).write(rows).close()
      out.toString
    }
  }
}

package tabulate

import java.io.StringWriter

import tabulate.engine.WriterEngine

object ops extends CsvInput.ToCsvInputOps
                   with CsvOutput.ToCsvOutputOps
                   with RowEncoder.ToRowEncoderOps
                   with CellEncoder.ToCellEncoderOps {
  implicit class CellDecoderOps(val str: String) extends AnyVal {
    def fromCsvCell[A](implicit da: CellDecoder[A]): DecodeResult[A] = da.decode(str)
    def unsafeFromCsvCell[A](implicit da: CellDecoder[A]): A = da.unsafeDecode(str)
  }

  implicit class RowDecoderOps(val row: Seq[String]) extends AnyVal {
    def fromCsvRow[A](implicit da: RowDecoder[A]): DecodeResult[A] = da.decode(row)
    def unsafeFromCsvRow[A](implicit da: RowDecoder[A]): A = da.unsafeDecode(row)
  }

  implicit class TraversableOps[A: RowEncoder](val rows: Traversable[A]) {
    def asCsv(sep: Char, header: Seq[String] = Seq.empty)(implicit engine: WriterEngine): String = {
      val out = new StringWriter()
      CsvWriter(out, sep, header).write(rows).close()
      out.toString
    }
  }
}

Rename `decodeCsvCell` to `fromCsvCell`, to be more symmetrical with `asCsvCell`.


package org.talkingpuffin.ui

import org.talkingpuffin.filter.TagUsers
import javax.swing.JDialog
import util.Cancelable
import swing.{FlowPanel, Action, Button, BorderPanel}
import java.awt.event.KeyEvent

/**
 * A dialog from which tags can be selected.
 */
class TagsDialog(owner: java.awt.Frame, tagUsers: TagUsers, checkedValues: List[String])
    extends JDialog(owner, "Tags", true) with Cancelable {
  var ok = false
  val panel = new BorderPanel {
    val tagsPanel = new TagsPanel(false, true, tagUsers, checkedValues)
    add(tagsPanel, BorderPanel.Position.Center)

    add(new FlowPanel {
      contents += new Button(cancelAction)
      val okAction = new Action("OK") {
        mnemonic = KeyEvent.VK_O
        def apply = {ok = true; TagsDialog.this.setVisible(false)}
      }
      val okButton = new Button(okAction)
      TagsDialog.this.getRootPane.setDefaultButton(okButton.peer)
      contents += okButton
    }, BorderPanel.Position.South)
  }
  setContentPane(panel.peer)
  pack
  setLocationRelativeTo(owner)

  def selectedTags = panel.tagsPanel.selectedTags
}

package org.talkingpuffin.ui

import javax.swing.JDialog
import swing.{FlowPanel, Action, Button, BorderPanel}
import org.talkingpuffin.filter.TagUsers
import util.Cancelable

/**
 * A dialog from which tags can be selected.
 */
class TagsDialog(owner: java.awt.Frame, tagUsers: TagUsers, checkedValues: List[String])
    extends JDialog(owner, "Tags", true) with Cancelable {
  var ok = false
  val panel = new BorderPanel {
    val tagsPanel = new TagsPanel(false, true, tagUsers, checkedValues)
    add(tagsPanel, BorderPanel.Position.Center)

    add(new FlowPanel {
      contents += new Button(cancelAction)
      val okAction = new Action("OK") {
        def apply = {ok = true; TagsDialog.this.setVisible(false)}
      }
      val okButton = new Button(okAction)
      TagsDialog.this.getRootPane.setDefaultButton(okButton.peer)
      contents += okButton
    }, BorderPanel.Position.South)
  }
  setContentPane(panel.peer)
  pack
  setLocationRelativeTo(owner)

  def selectedTags = panel.tagsPanel.selectedTags
}

Remove the O accelerator from the OK button. There may be an O checkbox.


name := "KmsEncryption4S"

version := "1.0"

scalaVersion := "2.12.2"

libraryDependencies ++= {
  Seq(

    // KMS SDK
    "com.amazonaws"              % "aws-java-sdk-kms"         % "1.11.122",
    "com.amazonaws"              % "aws-encryption-sdk-java"  % "0.0.1",

    // Dependencies
    "org.bouncycastle"           % "bcprov-ext-jdk15on"       % "1.54",

    // Logging
    "com.typesafe.scala-logging" % "scala-logging_2.11"       % "3.5.0",
    "ch.qos.logback"             % "logback-classic"          % "1.1.7",

    // Argument parser
    "commons-cli"                % "commons-cli"              % "1.4",

    // Testing
    "org.scalatest"             %% "scalatest"                % "3.0.0"       % "test"
  )
}

// Assembly
mainClass in Global := Some("onema.Main")
assemblyJarName in assembly := "encryption4s.jar"

name := "KmsEncryption4S"

version := "1.0"

scalaVersion := "2.12.2"

libraryDependencies ++= {
  Seq(

    // KMS SDK
    "com.amazonaws"              % "aws-java-sdk-kms"         % "1.11.122",
    "com.amazonaws"              % "aws-encryption-sdk-java"  % "1.3.1",

    // Dependencies
    "org.bouncycastle"           % "bcprov-ext-jdk15on"       % "1.54",

    // Logging
    "com.typesafe.scala-logging" % "scala-logging_2.11"       % "3.5.0",
    "ch.qos.logback"             % "logback-classic"          % "1.1.7",

    // Argument parser
    "commons-cli"                % "commons-cli"              % "1.4",

    // Testing
    "org.scalatest"             %% "scalatest"                % "3.0.0"       % "test"
  )
}

// Assembly
mainClass in Global := Some("onema.Main")
assemblyJarName in assembly := "encryption4s.jar"

Update to latest version of the encryption sdk


import com.github.retronym.SbtOneJar._

oneJarSettings

name := "api-build"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

version := "0.0.69"

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.70"

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.70


name := "lib-reference-scala"

organization := "io.flow"

scalaVersion in ThisBuild := "2.12.8"

crossScalaVersions := Seq("2.12.8")

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "org.scalatest" %% "scalatest" % "3.0.5" % Test,
      compilerPlugin("com.github.ghik" %% "silencer-plugin" % "1.3.0"),
      "com.github.ghik" %% "silencer-lib" % "1.3.0" % Provided,
    ),
    credentials += Credentials(
      "Artifactory Realm",
      "flow.jfrog.io",
      System.getenv("ARTIFACTORY_USERNAME"),
      System.getenv("ARTIFACTORY_PASSWORD")
    )
  )

publishTo := {
  val host = "https://flow.jfrog.io/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")
  }
}

// silence all warnings on autogenerated files
flowGeneratedFiles ++= Seq(
  "src/main/scala/io/flow/generated/.*".r,
)

// Make sure you only exclude warnings for the project directories, i.e. make builds reproducible
scalacOptions += s"-P:silencer:sourceRoots=${baseDirectory.value.getCanonicalPath}"

version := "0.2.29"

name := "lib-reference-scala"

organization := "io.flow"

scalaVersion in ThisBuild := "2.12.8"

crossScalaVersions := Seq("2.12.8")

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "org.scalatest" %% "scalatest" % "3.0.5" % Test,
      compilerPlugin("com.github.ghik" %% "silencer-plugin" % "1.3.0"),
      "com.github.ghik" %% "silencer-lib" % "1.3.0" % Provided,
    ),
    credentials += Credentials(
      "Artifactory Realm",
      "flow.jfrog.io",
      System.getenv("ARTIFACTORY_USERNAME"),
      System.getenv("ARTIFACTORY_PASSWORD")
    )
  )

publishTo := {
  val host = "https://flow.jfrog.io/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")
  }
}

// silence all warnings on autogenerated files
flowGeneratedFiles ++= Seq(
  "src/main/scala/io/flow/generated/.*".r,
)

// Make sure you only exclude warnings for the project directories, i.e. make builds reproducible
scalacOptions += s"-P:silencer:sourceRoots=${baseDirectory.value.getCanonicalPath}"

version := "0.2.30"

autocommit: Update configuration to record version 0.2.30


name := "apibuilder-validation"

organization := "io.flow"

scalaVersion in ThisBuild := "2.12.4"

crossScalaVersions := Seq("2.12.4", "2.11.11")

version := "0.1.11"

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.6.7",
      "org.scalatest" %% "scalatest" % "3.0.4" % 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")
  }
}

name := "apibuilder-validation"

organization := "io.flow"

scalaVersion in ThisBuild := "2.12.4"

crossScalaVersions := Seq("2.12.4", "2.11.11")

version := "0.1.12"

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.6.7",
      "org.scalatest" %% "scalatest" % "3.0.4" % 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.1.12


import com.github.retronym.SbtOneJar._

oneJarSettings

name := "api-lint"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.7"

version := "0.0.19"

exportJars := true

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.4.6",
      "com.ning" % "async-http-client" % "1.9.33",
      "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-lint"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.7"

version := "0.0.20"

exportJars := true

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.4.6",
      "com.ning" % "async-http-client" % "1.9.33",
      "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")
  }
}

Increment version from 0.0.19 => 0.0.20

Increment version from 0.0.19 => 0.0.20


name := "S99"

version := "1.0.0"

scalaVersion := "2.11.0"

scalacOptions ++= Seq("-deprecation")

libraryDependencies += "org.scalatest" %% "scalatest" % "2.1.0" % "test"

name := "S99"

version := "1.0.0"

scalaVersion := "2.11.0"

scalacOptions ++= Seq("-deprecation")

libraryDependencies += "org.scalatest" %% "scalatest" % "2.1.3" % "test"

libraryDependencies += "junit" % "junit" % "4.11" % "test"

Add JUnit dependency for tests (they would not compile).


package controllers

import play.api._
import play.api.mvc._
import models._
import dal._

import scala.concurrent.{ ExecutionContext, Future }

import javax.inject._

class Application  @Inject() (repo: CarroRepository, repomedia: MediaRepository)
                                 (implicit ec: ExecutionContext) extends Controller {

  def index = Action {
    Ok(views.html.index("Your new application is ready. Muhahaha", "andre"))
  }

  def carro( id:Long) = Action.async {

  	//val car = new Carro(1, "BMW M6", "5 portas, de 2005", "bmw-m6.jpeg", "bmw, m6, 5 portas")
  	repo.get(id).map { car =>
      val medias = repomedia.getByCarId(car.get.id.get.toLong)
		  Ok(views.html.carro(
        car.getOrElse(throw new RuntimeException("None available")),
         medias.toList)
      )
      // TODO make this show a not found personalised page
  	}
  }
}

package controllers

import play.api._
import play.api.mvc._
import models._
import dal._

import scala.concurrent.{ ExecutionContext, Future }

import javax.inject._

class Application  @Inject() (repo: CarroRepository, repomedia: MediaRepository)
                                 (implicit ec: ExecutionContext) extends Controller {

  def index = Action {
    Ok(views.html.index("Your new application is ready. Muhahaha", "andre"))
  }

  def carro( id:Long) = Action.async {

  	//val car = new Carro(1, "BMW M6", "5 portas, de 2005", "bmw-m6.jpeg", "bmw, m6, 5 portas")
  	repo.get(id).map { car =>
      val medias = if (car != None) {
        repomedia.getByCarId(car.get.id.get.toLong)
      } else {
        Nil
      }

      if (car != None) {
        Ok(views.html.carro(
          car.getOrElse(throw new RuntimeException("None available")),
          medias.toList))
      } else {
        NotFound("Nenhum carro encontrado.")
      }

      // TODO make this show a not found personalised page
  	}
  }
}

Handle NotFound and empty media list

Handle NotFound and empty media list


package io.aigar.controller

import io.aigar.controller.response._
import org.json4s.{DefaultFormats, Formats}
import org.scalatra.json._

class GameController extends AigarStack with JacksonJsonSupport {
  protected implicit val jsonFormats: Formats = DefaultFormats

  before() {
    contentType = formats("json")
  }

  object GameData {
    var all = List(
      GameState(1, 13),
      GameState(1, 50)
    )
  }

  case class Failure(data: String)
  case class Success(data: String)

  get("/:id") {
    GameData.all find (_.id.toString() == params("id")) match {
      case Some(b) => b
      case None => halt(404)
    }
  }

  post("/") {
    Success("Well done, the game was created")
  }

  post("/:id/action") {
    Success("Are you sure you want to do that?")
  }
}

package io.aigar.controller

import io.aigar.controller.response._
import org.json4s.{DefaultFormats, Formats}
import org.scalatra.json._

class GameController extends AigarStack with JacksonJsonSupport {
  protected implicit val jsonFormats: Formats = DefaultFormats

  before() {
    contentType = formats("json")
  }

  object GameStates {
    var all = List(
      GameState(1, 13),
      GameState(1, 50)
    )
  }

  case class Failure(data: String)
  case class Success(data: String)

  get("/:id") {
    GameStateResponse(
      GameStates.all find (_.id.toString() == params("id")) match {
        case Some(b) => b
        case None => halt(404)
      }
    )
  }

  post("/") {
    GameCreationResponse(GameCreation(42, "http://somewherekindasafe.xyz"))
  }

  post("/:id/action") {
    SuccessResponse("ok")
  }
}

Change controller to return the right format


name := "Degage - db layer"

normalizedName := "db"

version := "1.2-SNAPSHOT"

organization := "be.ugent.degage"

crossPaths := false

libraryDependencies += "mysql" % "mysql-connector-java" % "5.1.34"

libraryDependencies += "com.google.guava" % "guava" % "17.0"

libraryDependencies += "com.novocode" % "junit-interface" % "0.10" % "test"

// TODO: use java.security instead ?
libraryDependencies += "org.mindrot"  % "jbcrypt"  % "0.3m"

autoScalaLibrary := false

parallelExecution in Test := false

name := "Degage - db layer"

normalizedName := "db"

version := "1.2-SNAPSHOT"

organization := "be.ugent.degage"

crossPaths := false

libraryDependencies += "mysql" % "mysql-connector-java" % "5.1.36"

libraryDependencies += "com.google.guava" % "guava" % "17.0"

libraryDependencies += "com.novocode" % "junit-interface" % "0.10" % "test"

// TODO: use java.security instead ?
libraryDependencies += "org.mindrot"  % "jbcrypt"  % "0.3m"

autoScalaLibrary := false

parallelExecution in Test := false

Upgrade Mysql JDBC driver to be compatible with latest Mysql version


package org.scalameta
package build

object Versions {
  val LatestScala210 = "2.10.7"
  val LatestScala211 = "2.11.12"
  val LatestScala212 = "2.12.9"
  val LatestScala213 = "2.13.0"
  val LegacyScalaVersions = List("2.12.8")
}

package org.scalameta
package build

object Versions {
  val LatestScala211 = "2.11.12"
  val LatestScala212 = "2.12.9"
  val LatestScala213 = "2.13.0"
  val LegacyScalaVersions = List("2.12.8")
}

Remove unused scala 2.10 version

Remove unused scala 2.10 version


/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package dbis.pig.op

import dbis.pig.plan._
import dbis.pig.schema._

import scala.collection.mutable.ArrayBuffer

case class SplitBranch(val outPipeName: String, val expr: Expr)

/**
 * SplitInto represents the SPLIT INTO operator of Pig.
 *
 * @param initialInPipeName the names of the input pipe.
 * @param splits a list of split branches (output pipe + condition)
 */
case class SplitInto(val initialInPipeName: String, val splits: List[SplitBranch])
  extends PigOperator("", initialInPipeName) {

  override def initialOutPipeNames: List[String] = splits.map{ case branch => branch.outPipeName }

  override def lineageString: String = {
    s"""SPLIT%""" + super.lineageString
  }
}

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package dbis.pig.op

case class SplitBranch(val outPipeName: String, val expr: Predicate)

/**
 * SplitInto represents the SPLIT INTO operator of Pig.
 *
 * @param initialInPipeName the names of the input pipe.
 * @param splits a list of split branches (output pipe + condition)
 */
case class SplitInto(val initialInPipeName: String, val splits: List[SplitBranch])
  extends PigOperator("", initialInPipeName) {

  override def initialOutPipeNames: List[String] = splits.map{ case branch => branch.outPipeName }

  override def lineageString: String = {
    s"""SPLIT%""" + super.lineageString
  }
}

Make SplitBranch's expr a Predicate

Make SplitBranch's expr a Predicate

We're going to turn SplitBranches into Filters, so we might as well
force the expression to be a Predicate.


libraryDependencies ++= Seq(
    "play" %% "play" % "2.1-RC2",
    "org.reflections" % "reflections" % "0.9.8",
    "org.specs2" %% "specs2" % "1.5" % "test",
    "play" %% "play-test" % "2.1-RC2" % "test"
)

// needed for Play
resolvers += "Typesafe Releases" at "http://repo.typesafe.com/typesafe/releases/"

// sad situation https://github.com/jesseeichar/scala-io/issues/77#issuecomment-11991815
moduleConfigurations += ModuleConfiguration("com.github.scala-incubator.io", DefaultMavenRepository)

moduleConfigurations += ModuleConfiguration("com.jsuereth", DefaultMavenRepository)

// disable publishing the main javadoc jar
publishArtifact in (Compile, packageDoc) := false

seq(scalariformSettings: _*)

libraryDependencies ++= Seq(
    "play" %% "play" % "2.1-RC2",
    "org.reflections" % "reflections" % "0.9.8" exclude("javassist", "javassist"), // http://code.google.com/p/reflections/issues/detail?id=140
    "org.specs2" %% "specs2" % "1.5" % "test",
    "play" %% "play-test" % "2.1-RC2" % "test"
)

// needed for Play
resolvers += "Typesafe Releases" at "http://repo.typesafe.com/typesafe/releases/"

// sad situation https://github.com/jesseeichar/scala-io/issues/77#issuecomment-11991815
moduleConfigurations += ModuleConfiguration("com.github.scala-incubator.io", DefaultMavenRepository)

moduleConfigurations += ModuleConfiguration("com.jsuereth", DefaultMavenRepository)

// disable publishing the main javadoc jar
publishArtifact in (Compile, packageDoc) := false

seq(scalariformSettings: _*)

Fix dependency resolution of Javassist

Fix dependency resolution of Javassist

Reflections uses the old group-id 'javassist', but Play references a
newer version with the current group-id 'org.javassist'. This leads
to a dependency resolution problem when doing an assembly:

[error] (*:assembly) deduplicate: different file contents found in the following:
[error] /home/rtyley/.ivy2/cache/javassist/javassist/jars/javassist-3.12.1.GA.jar:javassist/bytecode/stackmap/Tracer.class
[error] /home/rtyley/.ivy2/cache/org.javassist/javassist/jars/javassist-3.16.1-GA.jar:javassist/bytecode/stackmap/Tracer.class

http://code.google.com/p/reflections/issues/detail?id=140


val scalaJSVersion = sys.env.getOrElse("SCALAJS_VERSION", "1.0.1")

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

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

addSbtPlugin("com.geirsson" % "sbt-scalafmt" % "1.5.1")

addSbtPlugin("com.geirsson" % "sbt-ci-release" % "1.5.3")

val scalaJSVersion = sys.env.getOrElse("SCALAJS_VERSION", "1.1.0")

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

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

addSbtPlugin("com.geirsson" % "sbt-scalafmt" % "1.5.1")

addSbtPlugin("com.geirsson" % "sbt-ci-release" % "1.5.3")

Update sbt-scalajs, scalajs-compiler to 1.1.0


// pulls in: sbt-pgp, sbt-release, sbt-mima-plugin, sbt-dependency-graph, sbt-buildinfo, sbt-sonatype
// TODO use sbt-release plugin
addSbtPlugin("org.typelevel" % "sbt-typelevel" % "0.3.1")

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

addSbtPlugin("com.scalapenos" % "sbt-prompt" % "0.2.1")

addSbtPlugin("com.typesafe.sbt" % "sbt-scalariform" % "1.3.0")

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

resolvers += "sonatype-releases" at "https://oss.sonatype.org/content/repositories/releases/"

resolvers += Classpaths.sbtPluginReleases

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

// Spark Packages Plugin
resolvers += "Spark Package Main Repo" at "https://dl.bintray.com/spark-packages/maven"

//SbtAssembly 0.12.0 is included in sbt-spark-package
addSbtPlugin("org.spark-packages" % "sbt-spark-package" % "0.2.1")

// pulls in: sbt-pgp, sbt-release, sbt-mima-plugin, sbt-dependency-graph, sbt-buildinfo, sbt-sonatype
// TODO use sbt-release plugin
addSbtPlugin("org.typelevel" % "sbt-typelevel" % "0.3.1")

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

addSbtPlugin("com.scalapenos" % "sbt-prompt" % "0.2.1")

addSbtPlugin("com.typesafe.sbt" % "sbt-scalariform" % "1.3.0")

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

resolvers += "sonatype-releases" at "https://oss.sonatype.org/content/repositories/releases/"

resolvers += Classpaths.sbtPluginReleases

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

//SbtAssembly 0.12.0 is included in sbt-spark-package
addSbtPlugin("org.spark-packages" % "sbt-spark-package" % "0.2.2")

Update SparkPackages plugin to 2.2

SPARKC-144: Update SparkPackages plugin to 2.2


addSbtPlugin("ch.epfl.lamp" % "sbt-dotty" % "0.5.1")

addSbtPlugin("com.codecommit" % "sbt-github-actions" % "0.9.5")

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

addSbtPlugin("com.geirsson" % "sbt-ci-release" % "1.5.5")

addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.4.2")

addSbtPlugin("com.github.tkawachi" % "sbt-doctest" % "0.9.8")

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

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

addSbtPlugin("org.portable-scala" % "sbt-scala-native-crossproject" % "1.0.0")

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

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

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

addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.4.0")

addSbtPlugin("ch.epfl.lamp" % "sbt-dotty" % "0.5.1")

addSbtPlugin("com.codecommit" % "sbt-github-actions" % "0.9.5")

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

addSbtPlugin("com.geirsson" % "sbt-ci-release" % "1.5.5")

addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.4.2")

addSbtPlugin("com.github.tkawachi" % "sbt-doctest" % "0.9.8")

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

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

addSbtPlugin("org.portable-scala" % "sbt-scala-native-crossproject" % "1.0.0")

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

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

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

addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.4.0")

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


resolvers += "simplytyped" at "http://simplytyped.github.io/repo/releases"

addSbtPlugin("com.simplytyped" % "sbt-antlr4" % "0.7.4")

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

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

Add sbt-release plugin to build

Add sbt-release plugin to build


addSbtPlugin("com.codecommit" % "sbt-github-actions" % "0.13.0")

addSbtPlugin("com.github.sbt" % "sbt-ci-release" % "1.5.9")

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

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

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

addSbtPlugin("com.codecommit" % "sbt-github-actions" % "0.13.0")

addSbtPlugin("com.github.sbt" % "sbt-ci-release" % "1.5.9")

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

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

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

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


import sbt._
import Keys._
import org.portablescala.sbtplatformdeps.PlatformDepsPlugin.autoImport._

object Dependencies {
  lazy val jaxbApi = "javax.xml.bind" % "jaxb-api" % "2.3.1" % "test"

  lazy val jodaTime = Seq(
    "joda-time" % "joda-time" % "2.10.12",
    "org.joda" % "joda-convert" % "2.2.1"
  )
  lazy val jackson = Seq(
    "com.fasterxml.jackson.core" % "jackson-databind" % "2.13.0"
  )
  lazy val scalaz_core = Def.setting(
    "org.scalaz" %%% "scalaz-core" % "7.3.5" cross CrossVersion.for3Use2_13
  )
  lazy val paranamer = "com.thoughtworks.paranamer" % "paranamer" % "2.8"
  lazy val scalatest = Def.setting(
    Seq("org.scalatest" %%% "scalatest-wordspec" % "3.2.10" % "test")
  )
  lazy val scalatestScalacheck = Def.setting(
    Seq("org.scalatestplus" %%% "scalacheck-1-15" % "3.2.10.0" % "test")
  )

  lazy val scalaXml = Def.setting {
    "org.scala-lang.modules" %%% "scala-xml" % "2.0.1"
  }
}

import sbt._
import Keys._
import org.portablescala.sbtplatformdeps.PlatformDepsPlugin.autoImport._

object Dependencies {
  lazy val jaxbApi = "javax.xml.bind" % "jaxb-api" % "2.3.1" % "test"

  lazy val jodaTime = Seq(
    "joda-time" % "joda-time" % "2.10.13",
    "org.joda" % "joda-convert" % "2.2.1"
  )
  lazy val jackson = Seq(
    "com.fasterxml.jackson.core" % "jackson-databind" % "2.13.0"
  )
  lazy val scalaz_core = Def.setting(
    "org.scalaz" %%% "scalaz-core" % "7.3.5" cross CrossVersion.for3Use2_13
  )
  lazy val paranamer = "com.thoughtworks.paranamer" % "paranamer" % "2.8"
  lazy val scalatest = Def.setting(
    Seq("org.scalatest" %%% "scalatest-wordspec" % "3.2.10" % "test")
  )
  lazy val scalatestScalacheck = Def.setting(
    Seq("org.scalatestplus" %%% "scalacheck-1-15" % "3.2.10.0" % "test")
  )

  lazy val scalaXml = Def.setting {
    "org.scala-lang.modules" %%% "scala-xml" % "2.0.1"
  }
}

Update joda-time to 2.10.13 in master

Update joda-time to 2.10.13 in master


name := """publisher-web"""

version := "1.0-SNAPSHOT"

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

scalaVersion := "2.11.1"

libraryDependencies ++= Seq(
  javaJdbc,
  javaEbean,
  cache,
  javaWs,
  "org.webjars" %% "webjars-play" % "2.3.0",
  "org.webjars" % "bootstrap" % "3.2.0",
  "org.webjars" % "dojo" % "1.10.0",
  "nl.idgis.publisher" % "publisher-domain" % "0.0.1-SNAPSHOT",
  "com.typesafe.akka" %% "akka-remote" % "2.3.3"
)

includeFilter in (Assets, LessKeys.less) := "*.less"

pipelineStages := Seq(rjs)

resolvers += "idgis-public" at "http://nexus.idgis.eu/content/groups/public/"

resolvers += "idgis-thirdparty" at "http://nexus.idgis.eu/content/repositories/thirdparty/"

buildInfoSettings

sourceGenerators in Compile <+= buildInfo

buildInfoKeys := Seq[BuildInfoKey](name, version, scalaVersion, sbtVersion)

buildInfoPackage := "planoview"

buildInfoPackage := "publisher"

name := """publisher-web"""

version := "1.0-SNAPSHOT"

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

scalaVersion := "2.11.1"

libraryDependencies ++= Seq(
  javaJdbc,
  javaEbean,
  cache,
  javaWs,
  "org.webjars" %% "webjars-play" % "2.3.0",
  "org.webjars" % "bootstrap" % "3.2.0",
  "org.webjars" % "dojo" % "1.10.0",
  "nl.idgis.publisher" % "publisher-domain" % "0.0.1-SNAPSHOT",
  "com.typesafe.akka" %% "akka-remote" % "2.3.3"
)

includeFilter in (Assets, LessKeys.less) := "*.less"

pipelineStages := Seq(rjs)

resolvers += Resolver.mavenLocal

resolvers += "idgis-public" at "http://nexus.idgis.eu/content/groups/public/"

resolvers += "idgis-thirdparty" at "http://nexus.idgis.eu/content/repositories/thirdparty/"

buildInfoSettings

sourceGenerators in Compile <+= buildInfo

buildInfoKeys := Seq[BuildInfoKey](name, version, scalaVersion, sbtVersion)

buildInfoPackage := "planoview"

buildInfoPackage := "publisher"

Use local maven repos in resolvers

Use local maven repos in resolvers


package dotty.tools
package dotc

import reporting.StoreReporter
import vulpix.TestConfiguration

import dotty.tools.vulpix.TestConfiguration.mkClasspath

import java.nio.file._

import org.junit.Test
import org.junit.Assert._

class SettingsTests {

  @Test def missingOutputDir: Unit =
    val options = Array("-d", "not_here")
    val reporter = Main.process(options, reporter = StoreReporter())
    assertEquals(1, reporter.errorCount)
    assertEquals("'not_here' does not exist or is not a directory or .jar file", reporter.allErrors.head.message)

  @Test def jarOutput: Unit = {
    val source = "tests/pos/Foo.scala"
    val out = Paths.get("out/jaredFoo.jar").normalize
    if (Files.exists(out)) Files.delete(out)
    val options = Array("-classpath", TestConfiguration.basicClasspath, "-d", out.toString, source)
    val reporter = Main.process(options)
    assertEquals(0, reporter.errorCount)
    assertTrue(Files.exists(out))
  }

  @Test def t8124: Unit =
    val source    = Paths.get("tests/pos/Foo.scala").normalize
    val outputDir = Paths.get("out/testSettings").normalize
    if Files.notExists(outputDir)
      Files.createDirectory(outputDir)
    val options  = Array("-encoding", "-d", outputDir.toString, source.toString)
    val reporter = Main.process(options, reporter = StoreReporter())
    assertEquals(1, reporter.errorCount)
}

package dotty.tools
package dotc

import reporting.StoreReporter
import vulpix.TestConfiguration

import dotty.tools.vulpix.TestConfiguration.mkClasspath

import java.nio.file._

import org.junit.Test
import org.junit.Assert._

class SettingsTests {

  @Test def missingOutputDir: Unit =
    val options = Array("-d", "not_here")
    val reporter = Main.process(options, reporter = StoreReporter())
    assertEquals(1, reporter.errorCount)
    assertEquals("'not_here' does not exist or is not a directory or .jar file", reporter.allErrors.head.message)

  @Test def jarOutput: Unit = {
    val source = "tests/pos/Foo.scala"
    val out = Paths.get("out/jaredFoo.jar").normalize
    if (Files.exists(out)) Files.delete(out)
    val options = Array("-classpath", TestConfiguration.basicClasspath, "-d", out.toString, source)
    val reporter = Main.process(options)
    assertEquals(0, reporter.errorCount)
    assertTrue(Files.exists(out))
  }

  @Test def `t8124 Don't crash on missing argument`: Unit =
    val source    = Paths.get("tests/pos/Foo.scala").normalize
    val outputDir = Paths.get("out/testSettings").normalize
    if Files.notExists(outputDir) then Files.createDirectory(outputDir)
    // -encoding takes an arg!
    val options  = Array("-encoding", "-d", outputDir.toString, source.toString)
    val reporter = Main.process(options, reporter = StoreReporter())
    assertEquals(1, reporter.errorCount)
}

Add clarifying test name and comment

Add clarifying test name and comment


package modelservice.web

import akka.io.IO
import modelservice.core.Core
import modelservice.api.Api
import spray.can.Http

/**
 * Web
 */
trait Web {
  this: Api with Core =>
  IO(Http) ! Http.Bind(modelService, interface = "0.0.0.0", port = 8080)
}

package modelservice.web

import akka.io.IO
import modelservice.core.Core
import modelservice.api.Api
import spray.can.Http

/**
 * Web
 */
trait Web {
  this: Api with Core =>
  {
    val interface = System.getProperty("http.interface") match {
      case x: String => x
      case _ => "0.0.0.0"
    }
    val port = System.getProperty("http.port") match {
      case x: String => {
        try {
          x.toInt
        } catch {
          case e: Exception => 8080
        }
      }
      case _ => 8080
    }
    IO(Http) ! Http.Bind(modelService, interface=interface, port=port)
  }
}

Add options to set interface and port at boot time


val AIRFRAME_VERSION = "20.10.1"
scalaVersion in ThisBuild := "2.12.12"

// RPC API definition. This project should contain only RPC interfaces
lazy val api =
  project
    .in(file("api"))
    .settings(
      libraryDependencies ++= Seq(
        "org.wvlet.airframe" %% "airframe-http" % AIRFRAME_VERSION
      )
    )

lazy val greeter =
  project
    .in(file("."))
    .enablePlugins(AirframeHttpPlugin, PackPlugin)
    .settings(
      // Generates HTTP clients
      airframeHttpClients := Seq("greeter.api:sync", "greeter.api:grpc"),
      airframeHttpGeneratorOption := "-l debug",
      libraryDependencies ++= Seq(
        "org.wvlet.airframe" %% "airframe-http-finagle" % AIRFRAME_VERSION,
        "org.wvlet.airframe" %% "airframe-http-grpc"    % AIRFRAME_VERSION,
        "org.wvlet.airframe" %% "airframe-launcher"     % AIRFRAME_VERSION
      )
    )
    .dependsOn(api)

val AIRFRAME_VERSION = "20.10.2"
scalaVersion in ThisBuild := "2.12.12"

// RPC API definition. This project should contain only RPC interfaces
lazy val api =
  project
    .in(file("api"))
    .settings(
      libraryDependencies ++= Seq(
        "org.wvlet.airframe" %% "airframe-http" % AIRFRAME_VERSION
      )
    )

lazy val greeter =
  project
    .in(file("."))
    .enablePlugins(AirframeHttpPlugin, PackPlugin)
    .settings(
      // Generates HTTP clients
      airframeHttpClients := Seq("greeter.api:sync", "greeter.api:grpc"),
      airframeHttpGeneratorOption := "-l debug",
      libraryDependencies ++= Seq(
        "org.wvlet.airframe" %% "airframe-http-finagle" % AIRFRAME_VERSION,
        "org.wvlet.airframe" %% "airframe-http-grpc"    % AIRFRAME_VERSION,
        "org.wvlet.airframe" %% "airframe-launcher"     % AIRFRAME_VERSION
      )
    )
    .dependsOn(api)

Use Airframe 20.10.2 in the demo code

Use Airframe 20.10.2 in the demo code


package textapp

import javax.swing.UIManager

object TextAppMain {
  def main(args: Array[String]) {
    val serverApp = new ServerApp
    val clientApp = new ClientApp
    println("initialized")
  }
}

package textapp

object TextAppMain {
  def main(args: Array[String]) {
    val serverApp = new ServerApp
    val clientApp = new ClientApp
    println("Text Application started")
  }
}

Remove unused import and cleanup printing

Signed-off-by: Aki Saarinen <2c8035bb80cf98a391872dcbe797b269d759f6d9@reaktor.fi>


package tarski

import org.testng.annotations.Test
import org.testng.AssertJUnit._
import tarski.Base._
import tarski.Items._
import tarski.Types._
import tarski.TestUtils._
import tarski.Inference.{Var,Bound,Fixed,Bounded,infer,looseBounds}
import scala.language.implicitConversions

class TestInfer {
  implicit def toType(v: TypeParamItem): Type = ParamType(v)

  def v(s: String): Var = TypeParamItem(s)
  val T = v("T")

  def testInfer(goal: (Var,RefType)*)(ts: Type*)(as: Type*): Unit = {
    val (vs,rts) = goal.toList.unzip
    assertEquals(Some(rts),infer(vs,ts.toList,as.toList)(looseBounds))
  }

  @Test
  def simpleObject() = testInfer(T -> ObjectType)(T)(ObjectType)

  @Test
  def simpleInteger() = testInfer(T -> IntRefType)(T)(IntRefType)

  @Test
  def simpleInt() = testInfer(T -> IntRefType)(T)(IntType)

  @Test
  def lubIntegerFloat() = testInfer(T -> SimpleClassType(NumberItem))(T,T)(IntRefType,FloatRefType)

  @Test
  def lubIntFloat() = testInfer(T -> SimpleClassType(NumberItem))(T,T)(IntType,FloatRefType)
}

package tarski

import org.testng.annotations.Test
import org.testng.AssertJUnit._
import tarski.Base._
import tarski.Items._
import tarski.Types._
import tarski.TestUtils._
import tarski.Inference.{Var,Bound,Fixed,Bounded,infer,looseBounds}
import scala.language.implicitConversions

class TestInfer {
  implicit def toType(v: TypeParamItem): Type = ParamType(v)

  def v(s: String): Var = TypeParamItem(s)
  val T = v("T")

  def testInfer(goal: (Var,RefType)*)(ts: Type*)(as: Type*): Unit = {
    val (vs,rts) = goal.toList.unzip
    assertEquals(Some(rts),infer(vs,ts.toList,as.toList)(looseBounds))
  }

  def testInferFail(vs: Var*)(ts: Type*)(as: Type*): Unit = {
    assertEquals(None,infer(vs.toList,ts.toList,as.toList)(looseBounds))
  }

  @Test
  def simpleObject() = testInfer(T -> ObjectType)(T)(ObjectType)

  @Test
  def simpleInteger() = testInfer(T -> IntRefType)(T)(IntRefType)

  @Test
  def simpleInt() = testInfer(T -> IntRefType)(T)(IntType)

  @Test
  def lubIntegerFloat() = testInfer(T -> SimpleClassType(NumberItem))(T,T)(IntRefType,FloatRefType)

  @Test
  def lubIntFloat() = testInfer(T -> SimpleClassType(NumberItem))(T,T)(IntType,FloatRefType)

  @Test
  def intFail() = testInferFail()(IntRefType)(SimpleClassType(NumberItem))
}

Test that inference can fail

Test that inference can fail


package codesample.scala.coursera.course1.week4

object ScalaListsPartOne {

  def insSort(xs: List[Int]): List[Int] = xs match {
    case Nil => List()
    case head :: tail => insert(head, insSort(tail))
  }
  def insert(head: Int, tail: List[Int]): List[Int] = tail match {
    case Nil => List(head)
    case headOfTail :: tailOfTail => if (head <= headOfTail) head :: tail else headOfTail :: insert(head, tailOfTail)
  }

  def main(args: Array[String]): Unit = {
    val list = "Keks" :: "Magic" :: "And shit" :: Nil // You can not omit :: Nil
    val otherList = "abc" :: "def" :: Nil
    val mergedList: List[String] = list ::: otherList

    println("list: " + list)
    println("merged list: " + mergedList)

    println("Head of first: " + list.head)
    println("Tail of first: " + list.tail)

    // Isertion sort!
    val someList = List(9,5,3,2,1,6,3,2)
    println("Insertion sorted list: " + someList + " => " + insSort(someList))
  }

}

package codesample.scala.coursera.course1.week4

object ScalaListsPartOne {

  def insSort(xs: List[Int]): List[Int] = xs match {
    case Nil => List()
    case head :: tail => insert(head, insSort(tail))
  }
  def insert(head: Int, tail: List[Int]): List[Int] = tail match {
    case Nil => List(head)
    case headOfTail :: tailOfTail => if (head <= headOfTail) head :: tail else headOfTail :: insert(head, tailOfTail)
  }

  def bubbleSort(xs: List[Int]): List[Int] = xs match {
    case Nil => List()
    case head :: tail => mayBeSwap(head, bubbleSort(tail));
  }

  def mayBeSwap(head: Int, tail: List[Int]): List[Int] = tail match {
    case Nil => List(head)
    case headOfTail :: tailOfTail =>
      if (head > headOfTail) headOfTail :: mayBeSwap(head, tailOfTail)
      else head :: tail
  }

  def main(args: Array[String]): Unit = {
    val list = "Keks" :: "Magic" :: "And shit" :: Nil // You can not omit :: Nil
    val otherList = "abc" :: "def" :: Nil
    val mergedList: List[String] = list ::: otherList

    println("list: " + list)
    println("merged list: " + mergedList)

    println("Head of first: " + list.head)
    println("Tail of first: " + list.tail)

    // Isertion sort!
    val someList = List(9,5,3,2,1,6,3,2)
    println("Insertion sorted list: " + someList + " => " + insSort(someList))
    println("Bubble sorted list: " + someList + " => " + bubbleSort(someList))

  }

}

Add bubble sort to scala list examples...


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

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

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


package scalex
package search

import db.DefRepo

import com.github.ornicar.paginator._
import scalaz.Validation
import scalaz.Scalaz.{ success, failure }

object Search extends scalaz.Validations {

  private val mixedRegex = """^([^\:]*)\:\s(.+)$""".r

  val defs: List[index.Def] = db.IndexRepo.findAll

  def find(query: RawQuery): Validation[String, Results] = {
    val adapter = InMemoryAdapter(defs take 10)
    for {
      p <- validation(Paginator(adapter, query.currentPage, query.maxPerPage))
      defs = DefRepo byIds (p.currentPageResults map (_.id))
    } yield Results(p, defs)
  }
}

package scalex
package search

import db.DefRepo

import com.github.ornicar.paginator._
import scalaz.Validation
import scalaz.Scalaz.{ success, failure }

object Search extends scalaz.Validations {

  private val mixedRegex = """^([^\:]*)\:\s(.+)$""".r

  val defs: List[index.Def] = db.IndexRepo.findAll

  def find(query: RawQuery): Validation[String, Results] = for {
    q <- query.analyze
    val adapter = InMemoryAdapter(defs take 10)
    p <- validation(Paginator(adapter, query.currentPage, query.maxPerPage))
    defs = DefRepo byIds (p.currentPageResults map (_.id))
  } yield Results(p, defs)
}

Rewrite main search routine to make better use of scalaz validation


object Test {
  def foo(a: Function[String, _ <: String]): a.type = a
  foo(x => x)
}

object Test {
  def foo(a: Function[String, _ <: String]): a.type = a
  foo(x => x)

  def foo(a: PartialFunction[String, _ <: String]): a.type = a
  foo({ case x => x })
}

Test for already-working partial function inference


import org.specs2.mutable._
import org.specs2.runner._
import org.junit.runner._

import play.api.test._
import play.api.test.Helpers._

@RunWith(classOf[JUnitRunner])
class ApplicationSpec extends Specification {

  "Application" should {

    "send 404 on a bad request" in new WithApplication{
      route(FakeRequest(GET, "/boum")) must beSome.which (status(_) == NOT_FOUND)
    }
  }
}

import org.specs2.mutable._

import play.api.libs.json._
import play.api.test._
import play.api.test.Helpers._

class ApplicationSpec extends Specification {
  "Application" should {

    "send 404 on an invalid route" in new WithApplication {
      route(FakeRequest(GET, "/foo")) must beSome.which (status(_) == NOT_FOUND)
    }

    "have POST routes for" in {
      "request account" in new WithApplication {
        route(
          FakeRequest(POST, "/account/request")
        ) must not (beSome.which (status(_) == NOT_FOUND))
      }

      "new account" in new WithApplication {
        route(
          FakeRequest(POST, "/account/new")
        ) must not (beSome.which (status(_) == NOT_FOUND))
      }

      "location request" in new WithApplication {
        route(
          FakeRequest(POST, "/at")
        ) must not (beSome.which (status(_) == NOT_FOUND))
      }

      "location respond" in new WithApplication {
        route(
          FakeRequest(POST, "/where")
        ) must not (beSome.which (status(_) == NOT_FOUND))
      }
    }
  }
}

Test existence of POST routes

Test existence of POST routes


import org.specs2.mutable._

import play.api.libs.json._
import play.api.test._
import play.api.test.Helpers._

class ApplicationSpec extends Specification {
  "Application" should {

    "send 404 on an invalid route" in new WithApplication {
      route(FakeRequest(GET, "/foo")) must beSome.which (status(_) == NOT_FOUND)
    }

    "have POST routes for" in {
      "request account" in new WithApplication {
        route(
          FakeRequest(POST, "/account/request")
        ) must not (beSome.which (status(_) == NOT_FOUND))
      }

      "new account" in new WithApplication {
        route(
          FakeRequest(POST, "/account/new")
        ) must not (beSome.which (status(_) == NOT_FOUND))
      }

      "location request" in new WithApplication {
        route(
          FakeRequest(POST, "/at")
        ) must not (beSome.which (status(_) == NOT_FOUND))
      }

      "location respond" in new WithApplication {
        route(
          FakeRequest(POST, "/where")
        ) must not (beSome.which (status(_) == NOT_FOUND))
      }
    }
  }
}

import org.specs2.mutable._

import play.api.libs.json._
import play.api.test._
import play.api.test.Helpers._

class ApplicationSpec extends Specification {
  "Application" should {

    "send 404 on an invalid route" in new WithApplication {
      route(FakeRequest(GET, "/foo")) must beSome.which (status(_) == NOT_FOUND)
    }

    "have POST routes for" in {
      "request account" in new WithApplication {
        route(
          FakeRequest(POST, "/account/request")
        ) must not (beSome.which (status(_) == NOT_FOUND))
      }

      "new account" in new WithApplication {
        route(
          FakeRequest(POST, "/account/new")
        ) must not (beSome.which (status(_) == NOT_FOUND))
      }

      "location request" in new WithApplication {
        route(
          FakeRequest(POST, "/where")
        ) must not (beSome.which (status(_) == NOT_FOUND))
      }

      "location respond" in new WithApplication {
        route(
          FakeRequest(POST, "/at")
        ) must not (beSome.which (status(_) == NOT_FOUND))
      }
    }
  }
}

Fix swapped tests for /where and /at routes


package steve

import com.datasift.dropwizard.scala.ScalaApplication
import com.google.inject.Stage
import com.hubspot.dropwizard.guice.GuiceBundle
import com.typesafe.config.ConfigFactory
import health.SteveHealthCheck
import io.dropwizard.setup.{Bootstrap, Environment}
import org.flywaydb.core.Flyway

object SteveServer extends ScalaApplication[SteveConfiguration] {
  val guiceBundle = GuiceBundle.newBuilder()
    .addModule(new SteveModule)
    .enableAutoConfig("controller", "steve")
    .setConfigClass(classOf[SteveConfiguration])
    .build(Stage.PRODUCTION)

  override def init(bootstrap: Bootstrap[SteveConfiguration]): Unit = {
    val flyway = new Flyway()
    val dbConfig = ConfigFactory.load().getConfig("steveDatasource.properties")
    val jdbcURL = s"jdbc:postgresql://${dbConfig.getString("serverName")}:${dbConfig.getString("portNumber")}/${dbConfig.getString("databaseName")}"
    flyway.setDataSource(jdbcURL, dbConfig.getString("user"), dbConfig.getString("password"))
    flyway.migrate()
    bootstrap.addBundle(guiceBundle)
  }

  override def run(configuration: SteveConfiguration, environment: Environment): Unit = {
    environment.healthChecks().register("steve", new SteveHealthCheck)
    environment.jersey().setUrlPattern("/*")
  }
}

package steve

import com.datasift.dropwizard.scala.ScalaApplication
import com.google.inject.Stage
import com.hubspot.dropwizard.guice.GuiceBundle
import com.typesafe.config.ConfigFactory
import health.SteveHealthCheck
import io.dropwizard.setup.{Bootstrap, Environment}
import org.flywaydb.core.Flyway

object SteveServer extends ScalaApplication[SteveConfiguration] {
  val guiceBundle = GuiceBundle.newBuilder()
    .addModule(new SteveModule)
    .enableAutoConfig("controller", "steve")
    .setConfigClass(classOf[SteveConfiguration])
    .build(Stage.PRODUCTION)

  override def init(bootstrap: Bootstrap[SteveConfiguration]): Unit = {
    val flyway = new Flyway()
    val dbConfig = ConfigFactory.load().getConfig("steveDatasource.properties").resolve()
    val jdbcURL = s"jdbc:postgresql://${dbConfig.getString("serverName")}:${dbConfig.getString("portNumber")}/${dbConfig.getString("databaseName")}"
    flyway.setDataSource(jdbcURL, dbConfig.getString("user"), dbConfig.getString("password"))
    flyway.migrate()
    bootstrap.addBundle(guiceBundle)
  }

  override def run(configuration: SteveConfiguration, environment: Environment): Unit = {
    environment.healthChecks().register("steve", new SteveHealthCheck)
    environment.jersey().setUrlPattern("/*")
  }
}

Resolve so we can substitute environment variables (if any) in the YAML.

https://stackoverflow.com/questions/43086926/how-to-read-environment-variables-in-typesafe-config-in-scala


package au.gov.dva.sopapi.tests.parsers;

import au.gov.dva.dvasopapi.tests.TestUtils
import au.gov.dva.sopapi.sopref.data.sops.StoredSop
import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class LumbarSpondylosisTests extends FunSuite{

  test("Parse entire RH LS SoP") {
    val result = ParserTestUtils.executeWholeParsingPipeline("F2014L00933", "sops_rh/F2014L00933.pdf")
    System.out.print(TestUtils.prettyPrint(StoredSop.toJson(result)))

   // assert(result != null)
  }

  test("Parse entire BoP LS SoP")
  {
    val result = ParserTestUtils.executeWholeParsingPipeline("F2014L00930", "sops_bop/F2014L00930.pdf")
    System.out.println(TestUtils.prettyPrint(StoredSop.toJson(result)))
 //   assert(result != null)
  }

}

package au.gov.dva.sopapi.tests.parsers;

import au.gov.dva.dvasopapi.tests.TestUtils
import au.gov.dva.sopapi.sopref.data.sops.StoredSop
import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class LumbarSpondylosisTests extends FunSuite{

//  test("Parse entire RH LS SoP") {
//    val result = ParserTestUtils.executeWholeParsingPipeline("F2014L00933", "sops_rh/F2014L00933.pdf")
//    System.out.print(TestUtils.prettyPrint(StoredSop.toJson(result)))
//
//   // assert(result != null)
//  }
//
//  test("Parse entire BoP LS SoP")
//  {
//    val result = ParserTestUtils.executeWholeParsingPipeline("F2014L00930", "sops_bop/F2014L00930.pdf")
//    System.out.println(TestUtils.prettyPrint(StoredSop.toJson(result)))
// //   assert(result != null)
//  }

}

Comment out entire LS tests.

Comment out entire LS tests.


//Copyright 2013 Joshua R. Rodgers
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//  limitations under the License.
//========================================================================

package com.theenginerd.analogredstone

import cpw.mods.fml.common.{FMLLog, Mod}
import cpw.mods.fml.common.Mod.EventHandler
import cpw.mods.fml.common.event.FMLInitializationEvent

@Mod(name = "Analog Redstone", modid = "analog_redstone", version = "1.0", modLanguage = "scala")
object AnalogRedstoneMod
{
  @EventHandler
  def init(event: FMLInitializationEvent)
  {
    FMLLog.info("Analog Redstone has been loaded.")
  }
}

//Copyright 2013 Joshua R. Rodgers
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//  limitations under the License.
//========================================================================

package com.theenginerd.analogredstone

import cpw.mods.fml.common.{FMLLog, Mod}
import cpw.mods.fml.common.Mod.EventHandler
import cpw.mods.fml.common.event.FMLInitializationEvent

@Mod(name = "Analog Redstone", modid = "analog_redstone", version = "1.0", modLanguage = "scala")
object AnalogRedstoneMod
{
    @EventHandler
    def init(event: FMLInitializationEvent)
    {
        FMLLog info "Analog Redstone has been loaded."
    }
}

Add copyright and licensing notices to file headers.


import sbt._, Keys._

object Dependencies {
  val servletApiDep = "jakarta.servlet" % "jakarta.servlet-api" % "5.0.0"

  val specs2Dep = Def.setting {
    "org.specs2" %% "specs2-core" % "4.17.0"
  }

  def okHttp = "com.squareup.okhttp3" % "okhttp" % "4.10.0" :: Nil

  def integrationTestDeps = Def.setting((specs2Dep.value :: okHttp) map { _ % "test" })

  val commonsCodecVersion = "1.15"
  val scalaXmlVersion = "2.1.0"
  val commonsIoVersion = "2.11.0"
  val commonsFileUploadVersion = "1.4"
  val jettyVersion = "11.0.12"
  val nettyVersion = "4.1.82.Final"
  val scalatestVersion = "3.2.14"
  val scalatestScalacheckVersion = s"${scalatestVersion}.0"
  val json4sVersion = "4.0.6"
  val asyncHttpClientVersion = "1.8.17"
  val javaxActivationVersion = "1.1.1"
}

import sbt._, Keys._

object Dependencies {
  val servletApiDep = "jakarta.servlet" % "jakarta.servlet-api" % "5.0.0"

  val specs2Dep = Def.setting {
    "org.specs2" %% "specs2-core" % "4.17.0"
  }

  def okHttp = "com.squareup.okhttp3" % "okhttp" % "4.10.0" :: Nil

  def integrationTestDeps = Def.setting((specs2Dep.value :: okHttp) map { _ % "test" })

  val commonsCodecVersion = "1.15"
  val scalaXmlVersion = "2.1.0"
  val commonsIoVersion = "2.11.0"
  val commonsFileUploadVersion = "1.4"
  val jettyVersion = "11.0.12"
  val nettyVersion = "4.1.84.Final"
  val scalatestVersion = "3.2.14"
  val scalatestScalacheckVersion = s"${scalatestVersion}.0"
  val json4sVersion = "4.0.6"
  val asyncHttpClientVersion = "1.8.17"
  val javaxActivationVersion = "1.1.1"
}

Update netty-codec-http, netty-handler, ... to 4.1.84.Final in main