Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .git-blame-ignore-revs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Scala Steward: Reformat with scalafmt 3.7.4
8e9ad92d2bad73ce88791cfec905dcad32d4ed6a
2 changes: 1 addition & 1 deletion .scalafmt.conf
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
version = 3.7.3
version = 3.7.4
runner.dialect = scala3
fileOverride {
"glob:**/scala-2-modules/**" {
Expand Down
2 changes: 1 addition & 1 deletion ammonite/Arguments.sc
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
@main
def main(name: String, age: Int) = {
println(s"Hello, $name. I'm $age")
}
}
2 changes: 1 addition & 1 deletion ammonite/Constants.sc
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
val aValue = 5
val anotherValue = 10
val anotherValue = 10
2 changes: 1 addition & 1 deletion ammonite/Doc.sc
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ def add(
n2: Int
): Unit = {
println(s"$n1 + $n2 = ${n1 + n2}")
}
}
2 changes: 1 addition & 1 deletion ammonite/FileSystem.sc
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ def countLines(path: String): Unit = {
val src = Source.fromFile(path)
println(src.getLines.size)
src.close()
}
}
2 changes: 1 addition & 1 deletion ammonite/MultipleMains.sc
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ def funA(arg: String): Unit = {
@main
def funB(n: Int): Unit = {
println(s"""funB called with param "$n"""")
}
}
2 changes: 1 addition & 1 deletion ammonite/SimpleScript.sc
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ val point = Coordinates(10, 15)
println(point.x)

val movedPoint = point.moveX(7)
println(movedPoint.x)
println(movedPoint.x)
4 changes: 2 additions & 2 deletions ammonite/Varargs.sc
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
@main
def main(fruits: String*) = {
fruits foreach {println(_)}
}
fruits foreach { println(_) }
}
131 changes: 68 additions & 63 deletions ammonite/ops/FileOps.sc
Original file line number Diff line number Diff line change
@@ -1,66 +1,71 @@
import ammonite.ops._

@main
@main
def fileOps() = {
val workingDir: os.Path = pwd / "base"

//cleaning up the working directory to avoid any issues with next run
rm! workingDir

mkdir! pwd / "base"
mkdir! workingDir / "sub1" / "sub2" / "sub3"

val simpleTextFile = workingDir / "text" / "simple.txt"

rm! simpleTextFile

//Write text file
write(simpleTextFile, "This is a simple text file written using ammonite ops.", createFolders = true)

//read from the text file
val content = read(simpleTextFile)
assert(content == "This is a simple text file written using ammonite ops.")

//append new text to the file
write.append(simpleTextFile, "Append new contents", createFolders = true)
val appendContent = read(simpleTextFile)
assert(appendContent == "This is a simple text file written using ammonite ops.Append new contents")

//overwrite entire file contents
write.over(simpleTextFile, "Overwrite contents", createFolders = true)
val contentOverwrite = read(simpleTextFile)
assert(contentOverwrite == "Overwrite contents")

write(workingDir / "dummy.txt", "Line 1")

//list directory contents
val items: LsSeq = ls! workingDir
assert(items.size == 3)
val onlyFiles = items.filter(_.isFile)
assert(onlyFiles.size == 1)

write.append(workingDir / "dummy.txt", "\nLine 2")
write.append(workingDir / "dummy.txt", "\nLine 3")

//Read the file contents as lines
val contentAsLines = read.lines(workingDir / "dummy.txt")
assert(contentAsLines.size == 3)

//copy and move operations
cp.into(workingDir / "dummy.txt", workingDir / "text")
mv(workingDir / "text" / "dummy.txt", workingDir / "text" / "renamed.txt")

val isRenamed = exists! workingDir / "text" / "renamed.txt"
assert(isRenamed)

import ammonite.ops.ImplicitWd._
//ls and writes the response to output stream
%("ls")

//ls and set the response to the variable lsResults
val lsResults = %%("ls")
assert(lsResults.exitCode == 0)
assert(lsResults.out.lines.size == 2)


}
val workingDir: os.Path = pwd / "base"

// cleaning up the working directory to avoid any issues with next run
rm ! workingDir

mkdir ! pwd / "base"
mkdir ! workingDir / "sub1" / "sub2" / "sub3"

val simpleTextFile = workingDir / "text" / "simple.txt"

rm ! simpleTextFile

// Write text file
write(
simpleTextFile,
"This is a simple text file written using ammonite ops.",
createFolders = true
)

// read from the text file
val content = read(simpleTextFile)
assert(content == "This is a simple text file written using ammonite ops.")

// append new text to the file
write.append(simpleTextFile, "Append new contents", createFolders = true)
val appendContent = read(simpleTextFile)
assert(
appendContent == "This is a simple text file written using ammonite ops.Append new contents"
)

// overwrite entire file contents
write.over(simpleTextFile, "Overwrite contents", createFolders = true)
val contentOverwrite = read(simpleTextFile)
assert(contentOverwrite == "Overwrite contents")

write(workingDir / "dummy.txt", "Line 1")

// list directory contents
val items: LsSeq = ls ! workingDir
assert(items.size == 3)
val onlyFiles = items.filter(_.isFile)
assert(onlyFiles.size == 1)

write.append(workingDir / "dummy.txt", "\nLine 2")
write.append(workingDir / "dummy.txt", "\nLine 3")

// Read the file contents as lines
val contentAsLines = read.lines(workingDir / "dummy.txt")
assert(contentAsLines.size == 3)

// copy and move operations
cp.into(workingDir / "dummy.txt", workingDir / "text")
mv(workingDir / "text" / "dummy.txt", workingDir / "text" / "renamed.txt")

val isRenamed = exists ! workingDir / "text" / "renamed.txt"
assert(isRenamed)

import ammonite.ops.ImplicitWd._
// ls and writes the response to output stream
%("ls")

// ls and set the response to the variable lsResults
val lsResults = %%("ls")
assert(lsResults.exitCode == 0)
assert(lsResults.out.lines.size == 2)

}
19 changes: 15 additions & 4 deletions app-packaging/build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ val mainClassPath = "com.baeldung.packaging.mainMethod"

// sbt-assembly configurations
assembly / assemblyJarName := "assemblyApp.jar"
assembly / mainClass := Some(mainClassPath) //since @main method name will be the class name of the main class in scala 3
assembly / mainClass := Some(
mainClassPath
) //since @main method name will be the class name of the main class in scala 3

// sbt native packager settings
enablePlugins(JavaAppPackaging)
Expand All @@ -28,7 +30,16 @@ jlinkIgnoreMissingDependency := JlinkIgnore.only(

//SBT Proguard plugin
enablePlugins(SbtProguard)
Proguard / proguardOptions ++= Seq("-dontoptimize","-dontnote", "-dontwarn", "-ignorewarnings")
Proguard / proguardOptions += ProguardOptions.keepMain("com.baeldung.packaging.mainMethod")
Proguard / proguardOptions ++= Seq(
"-dontoptimize",
"-dontnote",
"-dontwarn",
"-ignorewarnings"
)
Proguard / proguardOptions += ProguardOptions.keepMain(
"com.baeldung.packaging.mainMethod"
)
Proguard / proguardInputs := (Compile / dependencyClasspath).value.files
Proguard / proguardFilteredInputs ++= ProguardOptions.noFilter((Compile / packageBin).value)
Proguard / proguardFilteredInputs ++= ProguardOptions.noFilter(
(Compile / packageBin).value
)
2 changes: 1 addition & 1 deletion app-packaging/scalacli-app/ScalaCliApp.scala
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,4 @@ object ScalaCliApp {
}

// package this app using scala-cli, use the command `scala-cli package ScalaCliApp.scala -o cliapp --assembly`
// This will generate cliapp and it can be executed as ./cliapp
// This will generate cliapp and it can be executed as ./cliapp
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.baeldung.packaging
import os._

@main def mainMethod() =
@main def mainMethod() =
val osName = System.getProperty("os.name")
val path = os.pwd.toString
println(s"""
Expand Down
5 changes: 2 additions & 3 deletions play-scala/async-tasks/app/actors/AsyncTaskInActor.scala
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ import akka.actor.Actor
import org.joda.time.DateTime

class AsyncTaskInActor extends Actor {
override def receive: Receive = {
case msg: String =>
Console.println(s"Message ${msg} received at ${DateTime.now()}")
override def receive: Receive = { case msg: String =>
Console.println(s"Message ${msg} received at ${DateTime.now()}")
}
}
11 changes: 6 additions & 5 deletions play-scala/async-tasks/app/controllers/AsyncTaskController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@ import scala.concurrent.duration._
import scala.language.postfixOps

@Singleton
class AsyncTaskController @Inject()(
val controllerComponents: ControllerComponents,
val actorSystem: ActorSystem,
@Named("async-job-actor"
) actor: ActorRef)(implicit ec: ExecutionContext) extends BaseController {
class AsyncTaskController @Inject() (
val controllerComponents: ControllerComponents,
val actorSystem: ActorSystem,
@Named("async-job-actor") actor: ActorRef
)(implicit ec: ExecutionContext)
extends BaseController {
def runAsync(): Action[AnyContent] = Action {
Console.println(s"In route handler: ${DateTime.now()}")
actorSystem.scheduler.scheduleOnce(30 seconds) {
Expand Down
19 changes: 8 additions & 11 deletions play-scala/caching-in-play/app/controllers/TwitterController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,20 @@ import services.TwitterSearchService

import scala.concurrent.ExecutionContext

/**
* This controller creates an `Action` to handle HTTP requests to the
/** This controller creates an `Action` to handle HTTP requests to the
* application's home page.
*/
@Singleton
class TwitterController @Inject()(
twitterSearchService: TwitterSearchService,
override val controllerComponents: ControllerComponents,
implicit val executionContext: ExecutionContext
class TwitterController @Inject() (
twitterSearchService: TwitterSearchService,
override val controllerComponents: ControllerComponents,
implicit val executionContext: ExecutionContext
) extends BaseController {

/**
* Create an Action to search Twitter using their recentSearch capability.
/** Create an Action to search Twitter using their recentSearch capability.
*
* The configuration in the `routes` file means that this method
* will be called when the application receives a `GET` request with
* a path of `/`.
* The configuration in the `routes` file means that this method will be
* called when the application receives a `GET` request with a path of `/`.
*/
def recentSearch(twitterAccount: String): Action[AnyContent] = Action.async {
twitterSearchService.recentSearch(twitterAccount).map { response =>
Expand Down
20 changes: 12 additions & 8 deletions play-scala/caching-in-play/app/services/TwitterSearchService.scala
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,22 @@ import play.api.libs.json.JsValue
import wrappers.TwitterWebApi

import scala.concurrent.duration.Duration
import scala.concurrent.{ ExecutionContext, Future }
import scala.concurrent.{ExecutionContext, Future}

class TwitterSearchService @Inject()(twitterWebApi: TwitterWebApi,
cache: AsyncCacheApi,
configuration: Configuration,
implicit val executionContext: ExecutionContext) {
class TwitterSearchService @Inject() (
twitterWebApi: TwitterWebApi,
cache: AsyncCacheApi,
configuration: Configuration,
implicit val executionContext: ExecutionContext
) {

val cacheExpiry: Duration = configuration.get[Duration]("twitterCache.expiry")

def recentSearch(twitterUser: String): Future[Map[String, JsValue]] = {
cache.getOrElseUpdate[JsValue](twitterUser, cacheExpiry) {
twitterWebApi.recentSearch(twitterUser)
}.map(_.as[Map[String, JsValue]])
cache
.getOrElseUpdate[JsValue](twitterUser, cacheExpiry) {
twitterWebApi.recentSearch(twitterUser)
}
.map(_.as[Map[String, JsValue]])
}
}
18 changes: 10 additions & 8 deletions play-scala/caching-in-play/app/wrappers/TwitterWebApi.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,21 @@ package wrappers
import javax.inject.Inject
import play.api.Configuration
import play.api.http.Status._
import play.api.http.{ HeaderNames, MimeTypes }
import play.api.http.{HeaderNames, MimeTypes}
import play.api.libs.json.JsValue
import play.api.libs.ws.WSClient

import scala.concurrent.{ ExecutionContext, Future }
import scala.concurrent.{ExecutionContext, Future}

class TwitterWebApi @Inject()(
wsClient: WSClient,
configuration: Configuration,
implicit val executionContext: ExecutionContext
class TwitterWebApi @Inject() (
wsClient: WSClient,
configuration: Configuration,
implicit val executionContext: ExecutionContext
) {

val bearerToken: String = configuration.get[String]("twitter.bearerToken")
val recentSearchUrl: String = configuration.get[String]("twitter.recentSearchUrl")
val recentSearchUrl: String =
configuration.get[String]("twitter.recentSearchUrl")

def recentSearch(fromTwitterUser: String): Future[JsValue] = {
val url = String.format(recentSearchUrl, fromTwitterUser)
Expand All @@ -25,7 +26,8 @@ class TwitterWebApi @Inject()(
.withHttpHeaders(
HeaderNames.ACCEPT -> MimeTypes.JSON,
HeaderNames.AUTHORIZATION -> s"Bearer $bearerToken"
).get()
)
.get()
.map { response =>
if (response.status == OK) {
response.json
Expand Down
6 changes: 3 additions & 3 deletions play-scala/caching-in-play/app/wrappers/package.scala
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package object wrappers {
case class ApiError(
status: Int,
statusText: Option[String] = None,
data: Option[Any] = None
status: Int,
statusText: Option[String] = None,
data: Option[Any] = None
) extends Exception(statusText.orNull)
}
Loading