Simple ScalaFx TableView example not compiling - scala

I took a TableView code from a simple ScalaFx example (simplified from ScalaFx Custom cells):
import scalafx.application.JFXApp
import scalafx.beans.property.StringProperty
import scalafx.collections.ObservableBuffer
import scalafx.scene.Scene
import scalafx.scene.control.{TableColumn, TableView}
object MyTableApp extends JFXApp {
class Person(nameStr : String) {
val name = new StringProperty(this, "firstName", nameStr)
}
val characters = ObservableBuffer[Person](
new Person("Peggy Sue"),
new Person("Rocky Raccoon"),
new Person("Bungalow Bill")
)
stage = new JFXApp.PrimaryStage {
title = "Simple TableView"
scene = new Scene {
content = new TableView[Person](characters) {
columns ++= List(
new TableColumn[Person, String] {
text = "First Name"
cellValueFactory = { _.value.name }
prefWidth = 100
}
)
}
}
}
}
When compiling it, I get a confusing error:
Error:(24, 11) type mismatch;
found : scalafx.scene.control.TableColumn[MyTableApp.Person,String]
required: javafx.scene.control.TableColumn[MyTableApp.Person, ?]
new TableColumn[Person, String] {
What am I doing wrong?
My build.sbt contains:
scalaVersion := "2.11.8"
libraryDependencies += "org.scalafx" %% "scalafx" % "8.0.60-R9"

I did not copy the example source carefully, and I was missing an import:
import scalafx.scene.control.TableColumn._

Related

Fetch table size from dynamodb using scala

Hi I am using the following code to fetch various things from DynamoDB using Scala.
I am stuck at fetching the table description.
I get the following error when I build my project:
constructor DescribeTableRequest in class DescribeTableRequest cannot be accessed in class dynDBMetadata
val tableDescription = ddbClient.describeTable(new DescribeTableRequest("Music"))
package dynDBFetchAPIs
import software.amazon.awssdk.auth.credentials.{AwsBasicCredentials, StaticCredentialsProvider}
import software.amazon.awssdk.http.apache.ApacheHttpClient
import software.amazon.awssdk.regions.Region
import software.amazon.awssdk.services.dynamodb.DynamoDbClient
import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest
class dynDBMetadata {
def dynDBMetadataInit(): Unit = {
regionDetails()
}
def regionDetails(): Unit = {
val ddbClient = getDynDBClient()
val region = Region.US_EAST_1
var tableCount: Int = 0
var tableSize: Map[String, Int] = null
var regionSize: Int = 0
val tableList = ddbClient.listTables().tableNames()
val tableIterator = tableList.iterator()
while (tableIterator.hasNext) {
tableCount = tableCount + 1
tableIterator.next()
}
val descTabReq = new DescribeTableRequest("Music")
val tableDescription = ddbClient.describeTable(descTabReq)
println(tableDescription)
println("Region of AWS DynamoDB: " + region)
println("List of DynamoDB Tables: " + tableList)
println("Count of DynamoDB Tables: " + tableCount)
}
private def getDynDBClient(): DynamoDbClient = {
var awsBasicCredentials: AwsBasicCredentials = null
var dynamoDbClient: DynamoDbClient = null
try {
val accessKey = "****************************"
val secretKey = "****************************"
awsBasicCredentials = AwsBasicCredentials.create(accessKey, secretKey)
dynamoDbClient = DynamoDbClient.builder()
.region(Region.US_EAST_1)
.credentialsProvider(StaticCredentialsProvider.create(awsBasicCredentials))
.httpClient(ApacheHttpClient.builder().build())
.build();
} catch {
case e: Exception => {
e.printStackTrace()
}
}
dynamoDbClient
}
}
Why is the given constructor not accessible when I use Scala?
contents of build.sbt
name := "dynamodb"
version := "0.1"
scalaVersion := "2.11.12"
scalacOptions := Seq("-target:jvm-1.8")
libraryDependencies ++= Seq(
"software.amazon.awssdk" % "dynamodb" % "2.15.1"
)
I believe that happends because class software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest doesn't have a primary constructor.
You should create with the builder, like this
val tableRequest = DescribeTableRequest.builder
.tableName(tableName)
.build
com.amazonaws.services.dynamodbv2.model.DescribeTableRequest instead, does have a primary constructor. So, maybe you've just included a wrong dependency.

Streaming ByteArrayOutputStream in Action Result in scala Play Framework

I am trying to convert an svg image to a jpeg image in scala play framework.
I used batik and it worked ok.
Now I like to stream the output in the action result, instead of converting ByteArrayOutputStream to a
ByteArray which loads the entire output in memory.
How can I do that?
Here is the project code, which works without streaming the output:
build.sbt
name := "svg2png"
version := "1.0-SNAPSHOT"
lazy val root = (project in file(".")).enablePlugins(PlayScala)
resolvers += Resolver.sonatypeRepo("snapshots")
scalaVersion := "2.12.3"
libraryDependencies ++= Seq(
jdbc,
guice,
"org.apache.xmlgraphics" % "batik-transcoder" % "1.11",
"org.apache.xmlgraphics" % "batik-codec" % "1.11"
)
/project/plugins.sbt
addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.6.6")
/project/build.properties
sbt.version=1.0.2
/conf/routes
GET / controllers.Application.index
GET /image controllers.Application.getImage
/conf/application.conf
play.filters.enabled += "play.filters.cors.CORSFilter"
play.filters {
hosts {
allowed = ["."]
}
headers {
contentSecurityPolicy = null
}
}
play.i18n {
langs = [ "en" ]
}
contexts {
imageService {
fork-join-executor {
parallelism-factor = 4.0
parallelism-max = 8
}
}
}
/app/controllers/Application.scala
package controllers
import play.api.mvc._
import javax.inject._
import scala.concurrent.ExecutionContext
#Singleton
class Application #Inject()(imageService: services.ImageService,
cc: ControllerComponents)(implicit exec: ExecutionContext) extends AbstractController(cc) {
def index = Action {
Ok("test app").as(HTML)
}
def getImage : Action[AnyContent] = Action.async {
imageService.getImage.map{res => Ok(res).as("image/jpeg") }
}
}
/app/services/ImageService.scala
package services
import java.io.{ByteArrayOutputStream, StringReader}
import com.google.inject.{Inject, Singleton}
import scala.concurrent.{ExecutionContext, Future}
import akka.actor.ActorSystem
import org.apache.batik.transcoder.image.JPEGTranscoder
import org.apache.batik.transcoder.TranscoderInput
import org.apache.batik.transcoder.TranscoderOutput
#Singleton
class ImageService #Inject()(actorSystem: ActorSystem) {
implicit val AnalyticsServiceExecutionContext: ExecutionContext = actorSystem.dispatchers.lookup("contexts.imageService")
def getImage: Future[Array[Byte]] = {
Future {
val t: JPEGTranscoder = new JPEGTranscoder
t.addTranscodingHint(JPEGTranscoder.KEY_QUALITY, new java.lang.Float(0.8))
val imageSVGString: String =
"""<svg width="1000" height="1000" viewBox="0 0 1000 1000" version="1.1"
| xmlns="http://www.w3.org/2000/svg"
| xmlns:xlink="http://www.w3.org/1999/xlink">
| <circle cx="500" cy="500" r="300" fill="lightblue" />
|</svg>
""".stripMargin
val input: TranscoderInput = new TranscoderInput(new StringReader(imageSVGString))
val outputStream = new ByteArrayOutputStream
val output: TranscoderOutput = new TranscoderOutput(outputStream)
t.transcode(input, output)
outputStream.toByteArray
}
}
}
This works for me:
svg match {
case None => NotFound
case Some(svg) =>
val svgImage = new TranscoderInput(new StringReader(svg))
val pngOstream = new ByteArrayOutputStream
val outputPngImage = new TranscoderOutput(pngOstream)
val converter = fileExtension match {
case "png" => new PNGTranscoder()
case _ => new JPEGTranscoder()
}
if(converter.isInstanceOf[JPEGTranscoder]){
converter.addTranscodingHint(JPEGTranscoder.KEY_QUALITY, (0.8).toFloat)
}
converter.transcode(svgImage, outputPngImage)
Ok(pngOstream.toByteArray).as("image/" + fileExtension)
}

lambdista - No instance, of the ConcreteValue, compilation errors converting config to custom class

While trying to use lambdista config
I receive the following compilation errors:
No instance, of the ConcreteValue type class, found for config.ExampleConfig.FooConfig
not enough arguments for method as: (implicit evidence$1: com.lambdista.config.ConcreteValue[config.ExampleConfig.FooConfig])scala.util.Try[config.ExampleConfig.FooConfig]. Unspecified value parameter evidence$1.
Sample code copied from here:
package config
import java.io.InputStream
import java.nio.file.Paths
import scala.concurrent.duration._
import scala.util.{Failure, Success, Try}
import com.lambdista.config.exception.{
ConfigSyntaxException, ConversionException, KeyNotFoundException}
import com.lambdista.config._
object ExampleConfig extends App {
val confPath = "src//main//resources//example.conf"
val config: Try[Config] = Config.from(Paths.get(confPath))
case class Greek(alpha: String, beta: Int)
case class FooConfig(
bar: String,
baz: Option[Int],
list: List[Int],
map: Greek,
mapList: List[Greek],
range: Range,
duration: Duration,
missingValue: Option[String]
)
val fooConfig: Try[FooConfig] = for {
conf <- config
result <- conf.as[FooConfig]
} yield result
}
build.sbt:
name := "example"
version := "1.0"
scalaVersion := "2.10.5"
libraryDependencies ++= Seq(
"com.lambdista" %% "config" % "0.5.0"
)
resolvers += Resolver.mavenLocal
Input file:
// comment 1
{
bar = "hello",
# comment 2
baz = 42,
list = [1, // comment 3
2, 3],
map = {
alpha = "hello",
beta = 42
},
mapList = [
{
alpha = "hello",
beta = 42
},
{
alpha = "world",
beta = 24
}
],
range = 2 to 10 by 2,
duration = 5 seconds
}
How can I get this working?

How to use CheckBoxListCell in ScalaFX?

I am trying to make a list of checkBox with scalaFX.
With some research i found the CheckBoxListCell Component to resolve this problem.
But i didn't find a a good example with scalaFX ( there is only with javaFX).
Please any help ? Thanx
Here is a complete ScalaFX example:
package scalafx.controls
import scala.language.implicitConversions
import scalafx.Includes._
import scalafx.application.JFXApp
import scalafx.application.JFXApp.PrimaryStage
import scalafx.beans.property.BooleanProperty
import scalafx.collections.ObservableBuffer
import scalafx.scene.Scene
import scalafx.scene.control.cell.CheckBoxListCell
import scalafx.scene.control.{Button, ListView}
import scalafx.scene.layout.VBox
object CheckBoxListCellDemo extends JFXApp {
class Item(initialSelection: Boolean, val name: String) {
val selected = BooleanProperty(initialSelection)
override def toString = name
}
val data = ObservableBuffer[Item](
(1 to 10).map { i => new Item(i % 2 == 0, s"Item $i") }
)
stage = new PrimaryStage {
scene = new Scene {
title = "CheckBoxListCell Demo"
root = new VBox {
children = Seq(
new ListView[Item] {
prefHeight=250
items = data
cellFactory = CheckBoxListCell.forListView(_.selected)
},
new Button("Print State ") {
onAction = handle {
println("-------------")
println(data.map(d => d.name + ": " + d.selected()).mkString("\n"))
}
}
)
}
}
}
}

Scala Play Framework Slick session doesn't work

I'm trying a simple test application with Slick and the Play2 Framework, but the compiler keeps complaining the implicit session cannot be inferred.
Here is my Build.scala:
import sbt._
import Keys._
import play.Project._
object ApplicationBuild extends Build {
val appName = "dummy"
val appVersion = "1.0"
val appDependencies = Seq(
jdbc,
"mysql" % "mysql-connector-java" % "5.1.26",
"com.typesafe.slick" %% "slick" % "1.0.1"
)
val main = play.Project(appName, appVersion, appDependencies).settings(
// Add your own project settings here
)
}
And this is my Global singleton that holds my database connections:
package models
import play.api.Play.current
import play.api.db.DB
import slick.session.Session
import slick.driver.MySQLDriver.simple._
import scala.slick.session.Database.threadLocalSession
object Global {
lazy val database = Database.forDataSource(DB.getDataSource())
lazy val session = database.createSession()
}
And my controller:
package controllers
import scala.language.implicitConversions
import play.api._
import play.api.mvc._
import models.Global.session
import slick.driver.MySQLDriver.simple._
object Application extends Controller {
def index = Action {
/*slick.driver.MySQLDriver.simple.*/Query(Foo).foreach( _ => () ) // Do nothing for now
Ok(views.html.index("hola"))
}
object Foo extends Table[(Long, String, String)]("Foo") {
def * = column[Long]("id") ~ column[String]("bar1") ~ column[String]("bar2")
}
}
As you can see my Global.session val is imported, but it keeps saying no implicit session was found.
To make queries you need two things: connection to the database and a session, so your problem is how you define and use them.
With Database.threadLocalSession in scope, you can make your queries like this :
Database.forURL("jdbc:h2:mem:play", driver = "org.h2.Driver") withSession {
//create table
Foo.ddl.create
//insert data
Foo.insert((1.toLong,"foo","bar"))
//get data
val data : (Long,String,String) = (for{f<-Foo}yield(f)).first
}
or you can do it like this:
val database = Database.forDataSource(DB.getDataSource())
database.withSession{ implicit session : Session =>
Foo.ddl.create
Foo.insert((1.toLong,"foo","bar"))
val data : (Long,String,String) = (for{f<-Foo}yield(f)).first
}
I have create a test and it works fine, you can play with it:
"Foo should be creatable " in {
running(FakeApplication(additionalConfiguration = inMemoryDatabase())) {
val database = Database.forDataSource(DB.getDataSource())
database.withSession{ implicit session : Session =>
Foo.ddl.create
Foo.insert((1.toLong,"foo","bar"))
val data : (Long,String,String) = (for{f<-Foo}yield(f)).first
data._1 must equalTo(1)
}
}
}
Also you may look at here