Skip to content

Commit 3972bd4

Browse files
author
Hariharan Ramanathan
committed
Refactored retrieve command to sttp
1 parent 96f1842 commit 3972bd4

File tree

5 files changed

+90
-143
lines changed

5 files changed

+90
-143
lines changed

src/main/scala/de/upb/cs/swt/delphi/cli/DelphiCLI.scala

Lines changed: 35 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,47 @@
1616

1717
package de.upb.cs.swt.delphi.cli
1818

19-
import de.upb.cs.swt.delphi.cli.commands.TestCommand
19+
import com.softwaremill.sttp.{HttpURLConnectionBackend, Id, SttpBackend}
20+
import de.upb.cs.swt.delphi.cli.commands._
2021

2122
/**
2223
* The application class for the Delphi command line interface
2324
*/
2425
object DelphiCLI {
2526

27+
28+
def main(args: Array[String]): Unit = {
29+
30+
def getEnvOrElse(envVar: String, defaultPath: String) = sys.env.getOrElse(envVar, defaultPath)
31+
32+
val javaLibPath = getEnvOrElse("JAVA_LIB_PATH", "/usr/lib/jvm/default-java/lib/")
33+
34+
val trustStorePath = getEnvOrElse("JAVA_TRUSTSTORE", "/usr/lib/jvm/default-java/lib/security/cacerts")
35+
36+
System.setProperty("java.library.path", javaLibPath)
37+
System.setProperty("javax.net.ssl.trustStore", trustStorePath)
38+
39+
cliParser.parse(args, Config()) match {
40+
case Some(c) =>
41+
42+
implicit val config: Config = c
43+
implicit val backend: SttpBackend[Id, Nothing] = HttpURLConnectionBackend()
44+
45+
if (!config.silent) cliParser.showHeader()
46+
47+
config.mode match {
48+
case "test" => TestCommand.execute
49+
case "retrieve" => RetrieveCommand.execute
50+
// case "search" => SearchCommand.execute(config)
51+
case x => config.consoleOutput.outputError(s"Unknown command: $x")
52+
}
53+
54+
55+
case None =>
56+
}
57+
58+
}
59+
2660
private def cliParser = {
2761
val parser = {
2862
new scopt.OptionParser[Config]("delphi-cli") {
@@ -64,23 +98,4 @@ object DelphiCLI {
6498
}
6599
parser
66100
}
67-
68-
def main(args: Array[String]): Unit = {
69-
70-
System.setProperty("java.library.path", javaLibPath.get)
71-
System.setProperty("javax.net.ssl.trustStore", trustStorePath.get)
72-
System.setProperty("picocli.ansi", "true")
73-
cliParser.parse(args, config) match {
74-
case Some(config) =>
75-
if (!config.silent) cliParser.showHeader()
76-
config.mode match {
77-
case "test" => TestCommand.execute
78-
// case "retrieve" => RetrieveCommand.execute(config)
79-
// case "search" => SearchCommand.execute(config)
80-
case x => config.consoleOutput.outputError(s"Unknown command: $x")
81-
}
82-
case None =>
83-
}
84-
85-
}
86101
}

src/main/scala/de/upb/cs/swt/delphi/cli/commands/Command.scala

Lines changed: 4 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -16,19 +16,9 @@
1616

1717
package de.upb.cs.swt.delphi.cli.commands
1818

19-
import akka.actor.ActorSystem
20-
import akka.http.scaladsl.Http
21-
import akka.http.scaladsl.model.Uri.Query
22-
import akka.http.scaladsl.model.{HttpRequest, HttpResponse, StatusCodes, Uri}
23-
import akka.stream.ActorMaterializer
24-
import akka.util.ByteString
2519
import com.softwaremill.sttp._
2620
import de.upb.cs.swt.delphi.cli.Config
2721

28-
import scala.concurrent.duration._
29-
import scala.concurrent.{Await, Future}
30-
import scala.util.Failure
31-
3222
/**
3323
* Represents the implementation of a command of the CLI
3424
*/
@@ -39,54 +29,18 @@ trait Command {
3929
*
4030
* @param config The current configuration for the command
4131
*/
42-
def execute(implicit config: Config): Unit = {}
43-
44-
/**
45-
* Implements a common request type using currying to avoid code duplication
46-
*
47-
* @param target The endpoint to perform a Get request on
48-
* @param config The current configuration for the command
49-
*/
50-
protected def executeGet(target: String, parameters: Map[String, String] = Map())(config: Config, system: ActorSystem): Option[String] = {
51-
implicit val sys: ActorSystem = system
52-
implicit val materializer = ActorMaterializer()
53-
implicit val executionContext = sys.dispatcher
54-
55-
val uri = Uri(config.server)
56-
config.consoleOutput.outputInformation(s"Contacting server ${uri}...")
32+
def execute(implicit config: Config, backend: SttpBackend[Id, Nothing]): Unit = {}
5733

58-
val responseFuture = Http().singleRequest(HttpRequest(uri = uri.withPath(uri.path + target).withQuery(Query(parameters))))
59-
60-
responseFuture.onComplete {
61-
case Failure(_) => error(config)(s"Could not reach server ${config.server}.")
62-
case _ =>
63-
}
64-
65-
val result = Await.result(responseFuture, 30 seconds)
66-
val resultString = result match {
67-
case HttpResponse(StatusCodes.OK, headers, entity, _) =>
68-
entity.dataBytes.runFold(ByteString(""))(_ ++ _).map { body =>
69-
Some(body.utf8String)
70-
}
71-
case resp@HttpResponse(code, _, _, _) => {
72-
error(config)("Artifact not found.")
73-
resp.discardEntityBytes()
74-
Future(None)
75-
}
76-
}
77-
78-
Await.result(resultString, Duration.Inf)
79-
}
8034

8135
/**
8236
* Generic http GET request
8337
*
84-
* @param target Sub url in delphi server
38+
* @param target Sub url in delphi server
8539
* @param parameters Query params
8640
* @return GET response
8741
*/
88-
protected def executeGet1(target: String, parameters: Map[String, String] = Map())
89-
(implicit config: Config, backend: SttpBackend[Id, Nothing]): Option[String] = {
42+
protected def executeGet(target: String, parameters: Map[String, String] = Map())
43+
(implicit config: Config, backend: SttpBackend[Id, Nothing]): Option[String] = {
9044

9145
val request = sttp.get(uri"${config.server}/$target?$parameters")
9246
config.consoleOutput.outputInformation(s"Sending request ${request.uri}")

src/main/scala/de/upb/cs/swt/delphi/cli/commands/RetrieveCommand.scala

Lines changed: 43 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -16,31 +16,21 @@
1616

1717
package de.upb.cs.swt.delphi.cli.commands
1818

19-
import akka.actor.ActorSystem
20-
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
21-
import akka.http.scaladsl.unmarshalling.Unmarshal
22-
import akka.stream.ActorMaterializer
23-
import de.upb.cs.swt.delphi.cli.Config
19+
import com.softwaremill.sttp.{Id, SttpBackend}
20+
import de.upb.cs.swt.delphi.cli._
2421
import de.upb.cs.swt.delphi.cli.artifacts.RetrieveResult
25-
import de.upb.cs.swt.delphi.cli.artifacts.SearchResultJson._
26-
import de.upb.cs.swt.delphi.cli.commands.SearchCommand.information
27-
import spray.json.DefaultJsonProtocol
22+
import spray.json._
2823

29-
import scala.concurrent.Await
30-
import scala.concurrent.duration.Duration
3124
import scala.io.Source
32-
import scala.util.{Failure, Success}
3325

3426
/**
3527
* The implementation of the retrieve command.
3628
* Retrieves the contents of the file at the endpoint specified by the config file, and prints them to stdout
3729
*/
38-
object RetrieveCommand extends Command with SprayJsonSupport with DefaultJsonProtocol {
30+
object RetrieveCommand extends Command with DefaultJsonProtocol {
3931

4032

41-
def execute(config: Config)(implicit system: ActorSystem): Unit = {
42-
implicit val ec = system.dispatcher
43-
implicit val materializer = ActorMaterializer()
33+
override def execute(implicit config: Config, backend: SttpBackend[Id, Nothing]): Unit = {
4434

4535
//Checks whether the ID should be loaded from a file or not, and either returns the first line
4636
// of the given file if it is, or the specified ID otherwise
@@ -56,37 +46,54 @@ object RetrieveCommand extends Command with SprayJsonSupport with DefaultJsonPro
5646
}
5747

5848
val result = executeGet(
59-
s"/retrieve/$checkTarget",
49+
s"retrieve/$checkTarget",
6050
Map("pretty" -> "")
61-
)(config, system)
51+
)
6252

63-
result.map(s => {
53+
result.foreach(s => {
6454
if (config.raw) {
65-
reportResult(config)(s)
55+
reportResult.apply(s)
6656
}
67-
6857
if (!config.raw || !config.csv.equals("")) {
69-
val unmarshalledFuture = Unmarshal(s).to[List[RetrieveResult]]
58+
import artifacts.SearchResultJson._
7059

71-
unmarshalledFuture.transform {
72-
case Success(unmarshalled) => {
73-
val unmarshalled = Await.result(unmarshalledFuture, Duration.Inf)
74-
success(config)(s"Found ${unmarshalled.size} item(s).")
75-
reportResult(config)(unmarshalled)
60+
//TODO: convertTo[List[RetrieveResult]] not working ???
7661

77-
if(!config.csv.equals("")) {
78-
exportResult(config)(unmarshalled)
79-
information(config)("Results written to file '" + config.csv + "'")
80-
}
62+
val jsonArr = s.parseJson.asInstanceOf[JsArray].elements
63+
val retrieveResults = jsonArr.map(r => r.convertTo[RetrieveResult])
8164

82-
Success(unmarshalled)
83-
}
84-
case Failure(e) => {
85-
error(config)(s)
86-
Failure(e)
87-
}
65+
success.apply(s"Found ${retrieveResults.size} item(s).")
66+
reportResult.apply(retrieveResults)
67+
if (!config.csv.equals("")) {
68+
exportResult.apply(retrieveResults)
69+
information.apply("Results written to file '" + config.csv + "'")
8870
}
8971
}
72+
73+
9074
})
9175
}
9276
}
77+
78+
/* if (!config.raw || !config.csv.equals("")) {
79+
val unmarshalledFuture = Unmarshal(s).to[List[RetrieveResult]]
80+
81+
unmarshalledFuture.transform {
82+
case Success(unmarshalled) => {
83+
val unmarshalled = Await.result(unmarshalledFuture, Duration.Inf)
84+
success.apply(s"Found ${unmarshalled.size} item(s).")
85+
reportResult.apply(unmarshalled)
86+
87+
if (!config.csv.equals("")) {
88+
exportResult.apply(unmarshalled)
89+
information.apply("Results written to file '" + config.csv + "'")
90+
}
91+
92+
Success(unmarshalled)
93+
}
94+
case Failure(e) => {
95+
error.apply(s)
96+
Failure(e)
97+
}
98+
}
99+
}*/

src/main/scala/de/upb/cs/swt/delphi/cli/commands/TestCommand.scala

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,18 +16,19 @@
1616

1717
package de.upb.cs.swt.delphi.cli.commands
1818

19+
import com.softwaremill.sttp.{Id, SttpBackend}
1920
import de.upb.cs.swt.delphi.cli.Config
20-
import de.upb.cs.swt.delphi.cli._
2121

2222
/**
2323
* The implementation of the test command.
2424
* Tries to connect to the Delphi server and reports on the results of the version call.
2525
*/
2626
object TestCommand extends Command {
27-
override def execute(implicit config: Config): Unit = executeGet1(
28-
"version"
29-
).map(s => {
30-
success(config)("Successfully contacted Delphi server. ")
31-
information(config)("Server version: " + s)
32-
})
27+
override def execute(implicit config: Config,backend: SttpBackend[Id, Nothing]): Unit = {
28+
executeGet("version")
29+
.foreach(s => {
30+
success.apply("Successfully contacted Delphi server. ")
31+
information.apply("Server version: " + s)
32+
})
33+
}
3334
}

src/main/scala/de/upb/cs/swt/delphi/cli/package.scala

Lines changed: 0 additions & 30 deletions
This file was deleted.

0 commit comments

Comments
 (0)