├── .gitignore ├── LICENSE ├── NOTES.md ├── README.md ├── build.sbt ├── project └── plugins.sbt ├── src ├── main │ └── scala │ │ └── com │ │ └── github │ │ └── scalaspring │ │ └── akka │ │ └── http │ │ ├── AkkaHttpClient.scala │ │ ├── AkkaHttpServer.scala │ │ ├── AkkaHttpServerAutoConfiguration.scala │ │ ├── AkkaHttpService.scala │ │ ├── AkkaStreamsAutoConfiguration.scala │ │ ├── ServerBindingLifecycle.scala │ │ └── ServerSettings.scala └── test │ ├── resources │ └── application.yml │ └── scala │ ├── com │ └── github │ │ └── scalaspring │ │ └── akka │ │ └── http │ │ ├── MissingRouteSpec.scala │ │ ├── MultiServiceSpec.scala │ │ ├── RouteTestSpec.scala │ │ └── SingleServiceSpec.scala │ └── sample │ ├── Application.scala │ └── EchoServiceSpec.scala └── version.sbt /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | *.log 3 | 4 | # sbt specific 5 | .cache 6 | .history 7 | .lib/ 8 | dist/* 9 | target/ 10 | lib_managed/ 11 | src_managed/ 12 | project/boot/ 13 | project/plugins/project/ 14 | 15 | # Scala-IDE specific 16 | .scala_dependencies 17 | .worksheet 18 | 19 | # IntelliJ IDEA specific 20 | .idea/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /NOTES.md: -------------------------------------------------------------------------------- 1 | 2 | #### Akka Streams Notes 3 | 4 | * Remember it's *pull* based, not push based. Walk through flows from the end to the beginning, not the other way around. 5 | * Get to know the operators 6 | ** Example: prefixAndTail - is it really a tuple? nope, it's a stream of tuples 7 | * Use logging to help 8 | ** Provide practical example of using it to debug 9 | 10 | * Examples 11 | ** Broadcast with subsequent zip 12 | *** Streams must be same size - add buffers on non-drop side to equalize 13 | ** Broadcast with concat - NO! 14 | 15 | * Bad flows 16 | ** Parsing response by splitting into 2 streams 17 | ````scala 18 | val bcast = b.add(Broadcast[Array[String]](2)) 19 | val header = b.add(Flow[Array[String]].take(1).expand[Array[String], Array[String]](identity)(s => (s, s))/*.buffer(1, OverflowStrategy.backpressure)*/) 20 | val rows = b.add(Flow[Array[String]].drop(1)) 21 | val zip = b.add(Zip[Array[String], Array[String]]) 22 | val print = b.add(Sink.fold[Int, Array[String]](0){ (i, r) => logger.info(s"parsed record $i: ${r.mkString(",")}"); i + 1 }) 23 | val merge = b.add(Flow[(Array[String], Array[String])].map(t => t._1.zip(t._2).foldLeft(mutable.LinkedHashMap[String, String]())((m, p) => m += p ).asInstanceOf[Quote]).log("merge", extractMerged).withAttributes(logLevels)) 24 | 25 | parse ~> bcast ~> header ~> zip.in0 26 | bcast ~> rows ~> zip.in1 27 | zip.out ~> merge 28 | bcast ~> print 29 | ```` 30 | ** Converting stream of objects into CSV by splitting streams into header/rows 31 | ````scala 32 | // Convert a stream of quotes to CSV, first writing header then rows 33 | lazy val quoteToCsvFlow = Flow() { implicit b => 34 | val columns = b.add(Flow[Quote].take(1).map(_.keys.toSeq).expand[Seq[String], Seq[String]](identity)(s => (s, s))) 35 | val header = b.add(Flow[(Seq[String], Quote)].take(1).map(_._1.mkString(","))) 36 | val rows = b.add(Flow[(Seq[String], Quote)].mapConcat { t => 37 | val (cols, quote) = t 38 | immutable.Seq("\n", cols.map(quote(_)).mkString(",")) 39 | }) 40 | 41 | val in = b.add(Broadcast[Quote](3)) 42 | val print = b.add(Sink.fold[Int, Quote](0){ (i, q) => logger.info(s"received quote $i: $q"); i + 1 }) 43 | val zip = b.add(Zip[Seq[String], Quote]) 44 | val bcast = b.add(Broadcast[(Seq[String], Quote)](2)) 45 | val concat = b.add(Concat[String]) 46 | 47 | in ~> columns ~> zip.in0 48 | in ~> zip.in1 49 | zip.out ~> bcast ~> header ~> concat 50 | bcast ~> rows ~> concat 51 | in ~> print 52 | 53 | (in.in, concat.out) 54 | } 55 | ```` 56 | 57 | * Logging 58 | ````scala 59 | val logLevels = OperationAttributes.logLevels(onElement = DebugLevel) 60 | 61 | var i = 0 62 | def extractRecord(record: Array[String]): String = { 63 | i = i + 1 64 | s"$i: ${record(0)}" 65 | } 66 | var j = 0 67 | def extractMerged(merged: (collection.Map[String, String])): String = { 68 | j = j + 1 69 | s"$j: ${merged.values.head}" 70 | } 71 | ```` -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ### Akka HTTP Spring Boot Integration (akka-http-spring-boot) 2 | 3 | Integrates Scala Akka HTTP and Spring Boot for rapid, robust service development with minimal configuration. 4 | Pre-configured server components require little more than a route to get a service up and running. 5 | 6 | #### Key Benefits 7 | 1. Simple creation of microservices 8 | * Create your service route and implement it via a trivial server class to get going 9 | * Easily send outbound requests to aggregate data from other services 10 | 2. Highly testable, easily composable services 11 | * Full support for testing service routes and injecting an HTTP client to mock outbound requests during testing 12 | * Services are implemented via stackable Scala traits to promote bite-sized, reusable services that are easily composed in your server class. Ditch the monster service route. 13 | 3. Pre-configured server that's managed for you 14 | * No need to manage the server lifecycle. An Akka HTTP server will be started when your application starts and terminated when your application is stopped. 15 | * Provide your own configuration via standard Spring Boot configuration (application.yaml or other property source) to override defaults, if needed 16 | 4. Full Spring dependency injection support 17 | * Autowire any dependency into your services and leverage the full Spring ecosystem 18 | * Use existing Spring components to enable gradual migration or reuse of suitable existing enterprise components 19 | * Avoid the downsides of using Scala implicits or abstract types to implement dependency injection. While both implicits and abstract types are excellent language features, they can also lead to tight coupling and less maintainable code. 20 | 21 | #### Getting Started 22 | 23 | ##### build.sbt 24 | 25 | ````scala 26 | libraryDependencies ++= "com.github.scalaspring" %% "akka-http-spring-boot" % "0.3.1" 27 | ```` 28 | 29 | ##### Creating a service 30 | 31 | Extend `AkkaHttpService` and override the `route` method to define your service 32 | 33 | ````scala 34 | // Echo a path segment 35 | trait EchoService extends AkkaHttpService { 36 | abstract override def route: Route = { 37 | (get & path("echo" / Segment)) { name => 38 | complete(name) 39 | } 40 | } ~ super.route 41 | } 42 | ```` 43 | 44 | ###### Notes on the code 45 | 46 | * Be sure to use `abstract override` and to concatenate `super.route` when defining your route to make your services composable. See `MultiServiceSpec` in the test source for an example of a server implementing multiple, stackable services. 47 | 48 | ##### Create the server configuration and run it 49 | 50 | Extend `AkkaHttpServer` and import `AkkaHttpServerAutoConfiguration` to implement your service(s) 51 | 52 | ````scala 53 | @Configuration 54 | @Import(Array(classOf[AkkaHttpServerAutoConfiguration])) 55 | class Application extends AkkaHttpServer with EchoService 56 | 57 | object Application extends App { 58 | SpringApplication.run(classOf[Application], args: _*) 59 | } 60 | ```` 61 | 62 | #### Testing 63 | 64 | Create a ScalaTest-based test that extends the service trait to test your service route 65 | 66 | ````scala 67 | @Configuration 68 | @ContextConfiguration(classes = Array(classOf[EchoServiceSpec])) 69 | @Import(Array(classOf[AkkaStreamsAutoConfiguration])) 70 | class EchoServiceSpec extends FlatSpec with TestContextManagement with EchoService with ScalatestRouteTest with Matchers { 71 | 72 | "Echo service" should "echo" in { 73 | Get(s"/echo/test") ~> route ~> check { 74 | status shouldBe OK 75 | responseAs[String] shouldBe "test" 76 | } 77 | } 78 | 79 | } 80 | ```` 81 | 82 | #### Outbound Requests 83 | 84 | Inject the Akka HTTP-based client into your service and call its `request` method to make outbound requests. 85 | The HttpClient bean is automatically created as part of the `AkkaHttpServerAutoConfiguration` configuration. 86 | 87 | ````scala 88 | // Primitive site proxy (ex: http://localhost:8080/finance.yahoo.com) 89 | trait ProxyService extends AkkaHttpService { 90 | 91 | @Autowired val client: HttpClient = null 92 | 93 | abstract override def route: Route = { 94 | (get & path("proxy" / Segment)) { site => 95 | complete(client.request(Get(s"http://$site/"))) 96 | } 97 | } ~ super.route 98 | } 99 | ```` 100 | 101 | ##### Notes on the code 102 | 103 | * The autowired `HttpClient` will be injected by Spring (standard injection) upon startup. 104 | * Configuration Properties 105 | * Use the `http.server.lifecycle.phase` configuration property to control when the server is unbound and terminated. The default value is 10 to ensure its termination before the underlying actor system. 106 | 107 | #### Putting it all together - stackable services 108 | 109 | ````scala 110 | // Echo a path segment 111 | trait EchoService extends AkkaHttpService { 112 | abstract override def route: Route = { 113 | (get & path("echo" / Segment)) { name => 114 | complete(name) 115 | } 116 | } ~ super.route 117 | } 118 | 119 | // Primitive site proxy (ex: http://localhost:8080/finance.yahoo.com) 120 | trait ProxyService extends AkkaHttpService { 121 | 122 | @Autowired val client: HttpClient = null 123 | 124 | abstract override def route: Route = { 125 | (get & path("proxy" / Segment)) { site => 126 | complete(client.request(Get(s"http://$site/"))) 127 | } 128 | } ~ super.route 129 | } 130 | 131 | @SpringBootApplication 132 | @Import(Array(classOf[AkkaHttpServerAutoConfiguration])) 133 | class Application extends AkkaHttpServer with EchoService with ProxyService 134 | 135 | object Application extends App { 136 | SpringApplication.run(classOf[Application], args: _*) 137 | } 138 | ```` -------------------------------------------------------------------------------- /build.sbt: -------------------------------------------------------------------------------- 1 | import sbt.Keys._ 2 | 3 | // Common dependency versions 4 | val akkaVersion = "2.4.2" 5 | val akkaHttpVersion = "2.4.2" 6 | val akkaHttpTestKitVersion = "2.4.2-RC3" 7 | val springVersion = "4.2.5.RELEASE" 8 | val springBootVersion = "1.3.3.RELEASE" 9 | 10 | lazy val `akka-http-spring-boot` = (project in file(".")). 11 | settings(net.virtualvoid.sbt.graph.Plugin.graphSettings: _*). 12 | settings( 13 | organization := "com.github.scalaspring", 14 | name := "akka-http-spring-boot", 15 | description := "Integrates Scala Akka HTTP and Spring Boot for rapid, robust service development with minimal configuration.\nPre-configured server components require little more than a route to get a service up and running.", 16 | scalaVersion := "2.11.8", 17 | crossScalaVersions := Seq("2.10.6"), 18 | javacOptions := Seq("-source", "1.7", "-target", "1.7"), 19 | scalacOptions ++= Seq("-feature", "-deprecation"), 20 | resolvers += "Sonatype OSS Snapshots" at "https://oss.sonatype.org/content/repositories/snapshots", 21 | libraryDependencies ++= Seq( 22 | "com.typesafe.scala-logging" %% "scala-logging" % "3.+", 23 | //"com.typesafe.akka" %% "akka-actor" % akkaVersion, 24 | "org.springframework" % "spring-context" % springVersion, 25 | "org.springframework.boot" % "spring-boot-starter" % springBootVersion, 26 | "com.typesafe.akka" %% "akka-http-experimental" % akkaHttpVersion, 27 | "com.typesafe.akka" %% "akka-http-spray-json-experimental" % akkaHttpVersion, 28 | "com.github.scalaspring" %% "akka-spring-boot" % "0.3.1" 29 | // The following dependencies support configuration validation 30 | //"javax.validation" % "validation-api" % "1.1.0.Final", 31 | //"javax.el" % "javax.el-api" % "3.0.1-b04", 32 | //"org.hibernate" % "hibernate-validator" % "5.1.3.Final", 33 | ), 34 | // Runtime dependencies 35 | libraryDependencies ++= Seq( 36 | "ch.qos.logback" % "logback-classic" % "1.1.2" 37 | ).map { _ % "runtime" }, 38 | // Test dependencies 39 | libraryDependencies ++= Seq( 40 | "org.scalatest" %% "scalatest" % "2.2.4", 41 | "com.github.scalaspring" %% "scalatest-spring" % "0.3.1", 42 | "org.springframework" % "spring-test" % springVersion, 43 | "com.typesafe.akka" %% "akka-testkit" % akkaVersion, 44 | "com.typesafe.akka" %% "akka-http-testkit-experimental" % akkaHttpTestKitVersion, 45 | "com.jsuereth" %% "scala-arm" % "1.4" 46 | ).map { _ % "test" }, 47 | // Publishing settings 48 | publishMavenStyle := true, 49 | publishArtifact in Test := false, 50 | pomIncludeRepository := { _ => false }, 51 | publishTo := { 52 | val nexus = "https://oss.sonatype.org/" 53 | if (isSnapshot.value) 54 | Some("snapshots" at nexus + "content/repositories/snapshots") 55 | else 56 | Some("releases" at nexus + "service/local/staging/deploy/maven2") 57 | }, 58 | pomExtra := 59 | http://github.com/scalaspring/akka-http-spring-boot 60 | 61 | 62 | Apache License, Version 2.0 63 | http://www.apache.org/licenses/LICENSE-2.0.html 64 | repo 65 | 66 | 67 | 68 | git@github.com:scalaspring/akka-http-spring-boot.git 69 | scm:git:git@github.com:scalaspring/akka-http-spring-boot.git 70 | 71 | 72 | 73 | lancearlaus 74 | Lance Arlaus 75 | http://lancearlaus.github.com 76 | 77 | 78 | ) 79 | -------------------------------------------------------------------------------- /project/plugins.sbt: -------------------------------------------------------------------------------- 1 | 2 | addSbtPlugin("net.virtual-void" % "sbt-dependency-graph" % "0.7.5") 3 | 4 | addSbtPlugin("com.jsuereth" % "sbt-pgp" % "1.0.0") 5 | 6 | addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "0.2.2") -------------------------------------------------------------------------------- /src/main/scala/com/github/scalaspring/akka/http/AkkaHttpClient.scala: -------------------------------------------------------------------------------- 1 | package com.github.scalaspring.akka.http 2 | 3 | import akka.actor.ActorSystem 4 | import akka.http.scaladsl.Http 5 | import akka.http.scaladsl.Http.OutgoingConnection 6 | import akka.http.scaladsl.model.{HttpRequest, HttpResponse, Uri} 7 | import akka.stream.scaladsl.{Flow, Sink, Source} 8 | import com.github.scalaspring.akka.http.AkkaHttpClient.ConnectionFlow 9 | import org.springframework.stereotype.Component 10 | 11 | import scala.concurrent.Future 12 | 13 | 14 | /** 15 | * Defines a basic HTTP client useful for common request operations. 16 | */ 17 | trait HttpClient { 18 | 19 | /** Send an HTTP request */ 20 | def request(request: HttpRequest): Future[HttpResponse] 21 | 22 | } 23 | 24 | /** 25 | * Defines Akka HTTP client components useful for common request operations. 26 | * 27 | * @param connectionFlow provides connection flow instances for requests 28 | */ 29 | @Component 30 | class AkkaHttpClient(connectionFlow: Uri => ConnectionFlow) extends HttpClient with AkkaStreamsAutowiredImplicits { 31 | 32 | override def request(request: HttpRequest): Future[HttpResponse] = 33 | Source.single(request).via(connectionFlow(request.uri)).runWith(Sink.head) 34 | 35 | } 36 | 37 | object AkkaHttpClient { 38 | 39 | type ConnectionFlow = Flow[HttpRequest, HttpResponse, Future[OutgoingConnection]] 40 | 41 | def apply()(implicit system: ActorSystem): AkkaHttpClient = apply(defaultConnectionFlow _) 42 | def apply(connectionFlow: Uri => ConnectionFlow): AkkaHttpClient = new AkkaHttpClient(connectionFlow) 43 | 44 | /** 45 | * Default simple connection flow provider. 46 | */ 47 | protected def defaultConnectionFlow(uri: Uri)(implicit system: ActorSystem): Flow[HttpRequest, HttpResponse, Future[OutgoingConnection]] = 48 | Http().outgoingConnection(uri.authority.host.address, uri.authority.port) 49 | 50 | } -------------------------------------------------------------------------------- /src/main/scala/com/github/scalaspring/akka/http/AkkaHttpServer.scala: -------------------------------------------------------------------------------- 1 | package com.github.scalaspring.akka.http 2 | 3 | trait AkkaHttpServer extends AkkaStreamsAutowiredImplicits { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/main/scala/com/github/scalaspring/akka/http/AkkaHttpServerAutoConfiguration.scala: -------------------------------------------------------------------------------- 1 | package com.github.scalaspring.akka.http 2 | 3 | import akka.http.scaladsl.server.Route 4 | import com.github.scalaspring.akka.{ActorSystemLifecycle, SpringLogging} 5 | import org.springframework.beans.factory.BeanCreationException 6 | import org.springframework.beans.factory.annotation.Autowired 7 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean 8 | import org.springframework.boot.context.properties.EnableConfigurationProperties 9 | import org.springframework.context.annotation.{Import, Bean, Configuration} 10 | 11 | import scala.reflect.runtime.universe.typeTag 12 | 13 | /** 14 | * Defines an Akka HTTP server that serves all Akka HTTP routes found in the application context. 15 | * 16 | * Usage: Import this configuration into your application context. 17 | * 18 | * Example: 19 | * 20 | * {{{ 21 | * @Configuration 22 | * @Import(Array(classOf[AkkaHttpServerAutoConfiguration])) 23 | * class Configuration extends MyService 24 | * }}} 25 | */ 26 | @Configuration 27 | @EnableConfigurationProperties 28 | @Import(Array(classOf[AkkaStreamsAutoConfiguration])) 29 | class AkkaHttpServerAutoConfiguration extends AkkaStreamsAutowiredImplicits with SpringLogging { 30 | 31 | // Note: This is intentionally not required, even though a route is required, so that we can provide a useful message 32 | // below if the user doesn't define a route 33 | @Autowired(required=false) 34 | private val route: Route = null 35 | 36 | /** 37 | * Defines a server settings bean with values read from configuration. 38 | * Set the `http.server.interface` and `http.server.port` configuration properties to set server configuration. 39 | * Note: This an automatic bean definition that can be overridden by supplying your own bean definition. 40 | */ 41 | @Bean @ConditionalOnMissingBean(Array(classOf[ServerSettings])) 42 | def serverSettings = new ServerSettings() 43 | 44 | /** 45 | * Defines the server binding lifecycle bean that creates the server for the route defined in the application context. 46 | * Note: This an automatic bean definition that can be overridden by supplying your own bean definition. 47 | */ 48 | @Bean @ConditionalOnMissingBean(Array(classOf[ServerBindingLifecycle])) 49 | def serverBindingLifecycle(settings: ServerSettings): ServerBindingLifecycle = { 50 | if (route == null) { 51 | val msg = s"Error starting server: No route defined. Please define a bean named 'route' of type ${typeTag[Route].tpe}. Akka HTTP applications require a route definition." 52 | log.error(msg) 53 | throw new BeanCreationException(msg) 54 | } 55 | else ServerBindingLifecycle(settings, route) 56 | } 57 | 58 | /** 59 | * Defines an HTTP client that can be used for outgoing HTTP connections. 60 | * Note: This an automatic bean definition that can be overridden by supplying your own bean definition. 61 | */ 62 | @Bean @ConditionalOnMissingBean(Array(classOf[HttpClient])) 63 | def httpClient: HttpClient = AkkaHttpClient() 64 | 65 | } 66 | -------------------------------------------------------------------------------- /src/main/scala/com/github/scalaspring/akka/http/AkkaHttpService.scala: -------------------------------------------------------------------------------- 1 | package com.github.scalaspring.akka.http 2 | 3 | import akka.actor.ActorSystem 4 | import akka.http.scaladsl.server.Directives._ 5 | import akka.http.scaladsl.server._ 6 | import akka.stream.Materializer 7 | import org.springframework.beans.BeanInstantiationException 8 | import org.springframework.context.annotation.Bean 9 | import org.springframework.util.ClassUtils 10 | 11 | import scala.concurrent.ExecutionContextExecutor 12 | 13 | /** 14 | * Base trait used to define services. Defines the service route bean used by [AkkaHttpServerAutoConfiguration]. 15 | * 16 | * This trait is designed to be stackable, allowing multiple services to be implemented in a single server. 17 | * 18 | * Usage: Extend this trait and override the route function to create your service. 19 | * 20 | * Example: Note the use of `abstract override` and the concatenation of `super.route` to make the service stackable. 21 | * {{{ 22 | * 23 | * // Define the service route in trait 24 | * trait EchoService extends AkkaHttpService { 25 | * abstract override def route: Route = { 26 | * get { 27 | * path("echo" / Segment) { name => 28 | * complete(name) 29 | * } 30 | * } 31 | * } ~ super.route 32 | * } 33 | * 34 | * // Implement the trait in your application configuration 35 | * @Configuration 36 | * @Import(Array(classOf[AkkaHttpServerAutoConfiguration])) 37 | * class Configuration extends EchoService 38 | * 39 | * }}} 40 | */ 41 | trait AkkaHttpService { 42 | 43 | protected implicit val system: ActorSystem 44 | protected implicit def executor: ExecutionContextExecutor 45 | protected implicit def materializer: Materializer 46 | 47 | def route: Route = reject 48 | 49 | @Bean(name = Array("route")) 50 | def akkaHttpRoute: Route = { 51 | if (route == reject) throw new BeanInstantiationException(classOf[Route], 52 | s"Please supply a route definition by overriding the route function in ${ClassUtils.getUserClass(this).getName}. " + 53 | s"See the example in the documentation for ${classOf[AkkaHttpService].getName}.") 54 | else route 55 | } 56 | 57 | } 58 | 59 | -------------------------------------------------------------------------------- /src/main/scala/com/github/scalaspring/akka/http/AkkaStreamsAutoConfiguration.scala: -------------------------------------------------------------------------------- 1 | package com.github.scalaspring.akka.http 2 | 3 | import akka.stream.{ActorMaterializer, Materializer} 4 | import com.github.scalaspring.akka.{AkkaAutoConfiguration, AkkaAutowiredImplicits, SpringLogging} 5 | import org.springframework.beans.factory.annotation.Autowired 6 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean 7 | import org.springframework.context.annotation.{Bean, Configuration, Import} 8 | 9 | /** 10 | * Configures Spring to materialize Akka Streams flows via Akka. 11 | */ 12 | @Configuration 13 | @Import(Array(classOf[AkkaAutoConfiguration])) 14 | class AkkaStreamsAutoConfiguration extends AkkaAutowiredImplicits with SpringLogging { 15 | 16 | @Bean @ConditionalOnMissingBean(Array(classOf[Materializer])) 17 | def materializer = ActorMaterializer() 18 | 19 | } 20 | 21 | /** 22 | * Defines autowired implicits needed to materialize Akka Streams flows. 23 | */ 24 | trait AkkaStreamsAutowiredImplicits extends AkkaAutowiredImplicits { 25 | 26 | @Autowired implicit val materializer: Materializer = null 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/scala/com/github/scalaspring/akka/http/ServerBindingLifecycle.scala: -------------------------------------------------------------------------------- 1 | package com.github.scalaspring.akka.http 2 | 3 | import java.util.concurrent.atomic.AtomicReference 4 | 5 | import akka.http.scaladsl.Http 6 | import akka.http.scaladsl.Http.ServerBinding 7 | import akka.http.scaladsl.server.Route 8 | import com.github.scalaspring.akka.ActorSystemLifecycle 9 | import com.typesafe.scalalogging.StrictLogging 10 | import org.springframework.beans.factory.annotation.Value 11 | import org.springframework.context.SmartLifecycle 12 | 13 | import scala.concurrent.duration._ 14 | import scala.concurrent.{Await, Future} 15 | import scala.util.{Failure, Success} 16 | 17 | object ServerBindingLifecycle { 18 | 19 | sealed trait State 20 | case object Stopped extends State 21 | case object Starting extends State 22 | case object Started extends State 23 | case object Stopping extends State 24 | 25 | def apply(settings: ServerSettings, route: Route) = 26 | new ServerBindingLifecycle(settings, route) 27 | 28 | } 29 | 30 | /** 31 | * Manages the lifecycle of an Akka HTTP `ServerBinding`, ensuring its lifecycle matches that of the containing 32 | * Spring application context. 33 | * 34 | * This is an internal management class and is not intended for direct use. An instance is automatically created by 35 | * [AkkaHttpServerAutoConfiguration]. 36 | * 37 | * The Spring lifecycle phase (default 10) can be adjusted by setting the http.server.lifecycle.phase configuration 38 | * property. Note that the phase MUST be greater than that of the ActorSystemLifecycle bean to ensure the underlying 39 | * ActorSystem is started before, and is terminated after, the Akka HTTP server. 40 | * 41 | * @param settings binding settings 42 | * @param route route definition 43 | */ 44 | class ServerBindingLifecycle (val settings: ServerSettings, val route: Route) 45 | extends SmartLifecycle with AkkaStreamsAutowiredImplicits with StrictLogging 46 | { 47 | 48 | import ServerBindingLifecycle._ 49 | 50 | // Read-only state property 51 | private val _state: AtomicReference[State] = new AtomicReference(Stopped) 52 | def state = _state.get() 53 | 54 | // Read-only binding property 55 | private var _binding: Option[Future[ServerBinding]] = None 56 | def binding = _binding 57 | 58 | @Value("${http.server.lifecycle.timeout:30 seconds}") 59 | protected val timeout: String = "30 seconds" 60 | 61 | @Value("${http.server.lifecycle.phase:10}") 62 | protected val phase: Int = 10 63 | override def getPhase: Int = phase 64 | 65 | override def isAutoStartup: Boolean = true 66 | 67 | override def isRunning: Boolean = (_state.get() == Started) 68 | 69 | override def start(): Unit = { 70 | 71 | if (_state.compareAndSet(Stopped, Starting)) { 72 | logger.info("Starting server") 73 | 74 | _binding = Some(doStart().andThen { 75 | case Success(binding) => { 76 | logger.info(s"Started server on ${binding.localAddress.getHostString}:${binding.localAddress.getPort}") 77 | _state.set(Started) 78 | } 79 | case Failure(t) => { 80 | logger.error("Failed to start server", t) 81 | _binding = None 82 | _state.set(Stopped) 83 | } 84 | }) 85 | 86 | // Wait for the server binding to complete before returning 87 | Await.result(_binding.get, Duration(timeout)) 88 | 89 | } else { 90 | logger.warn(s"Unexpected server state (state=${state}), ignoring call to start()") 91 | } 92 | } 93 | 94 | override def stop(callback: Runnable): Unit = { 95 | 96 | _binding.map { future => 97 | future.andThen { 98 | 99 | case Success(binding) => { 100 | if (_state.compareAndSet(Started, Stopping)) { 101 | logger.info(s"Stopping server on ${binding.localAddress.getHostString}:${binding.localAddress.getPort}") 102 | 103 | doStop(binding).andThen { 104 | case Success(_) => logger.info(s"Server on ${binding.localAddress.getHostString}:${binding.localAddress.getPort} stopped") 105 | case Failure(t) => logger.error(s"Error stopping server on ${binding.localAddress.getHostString}:${binding.localAddress.getPort}", t) 106 | }.andThen { 107 | case r => { 108 | _state.set(Stopped) 109 | _binding = None 110 | callback.run() 111 | } 112 | } 113 | 114 | } else { 115 | logger.warn(s"Unexpected server state (state=${state}), ignoring call to stop()") 116 | callback.run() 117 | } 118 | } 119 | 120 | case Failure(t) => { 121 | logger.info("Server failed to bind, ignoring call to stop()") 122 | callback.run() 123 | } 124 | } 125 | 126 | }.getOrElse { 127 | logger.info("No server binding, ignoring call to stop()") 128 | callback.run() 129 | } 130 | 131 | } 132 | 133 | protected def doStart(): Future[ServerBinding] = { 134 | Http().bindAndHandle(Route.handlerFlow(route), settings.interface, settings.port) 135 | } 136 | 137 | protected def doStop(binding: ServerBinding): Future[Unit] = { 138 | binding.unbind() 139 | } 140 | 141 | // Intentionally left unimplemented since it should never be called 142 | override def stop(): Unit = ??? 143 | 144 | } 145 | -------------------------------------------------------------------------------- /src/main/scala/com/github/scalaspring/akka/http/ServerSettings.scala: -------------------------------------------------------------------------------- 1 | package com.github.scalaspring.akka.http 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties 4 | 5 | import scala.beans.BeanProperty 6 | import ServerSettings._ 7 | 8 | /** 9 | * HTTP server settings with defaults. 10 | * 11 | * This is a standard Spring Boot configuration properties class that will be populated by Spring using property 12 | * sources available in the application context. 13 | * HTTP server settings are read from properties prefixed with 'http.server' 14 | * 15 | * Example YAML configuration (application.yaml) 16 | * 17 | * {{{ 18 | * http: 19 | * server: 20 | * interface: localhost 21 | * port: 8080 22 | * }}} 23 | * 24 | */ 25 | @ConfigurationProperties(prefix = "http.server") 26 | class ServerSettings( 27 | @BeanProperty var interface: String = DefaultInterface, 28 | @BeanProperty var port: Int = DefaultPort) { 29 | 30 | //def this() = this(interface = DefaultInterface, port = DefaultPort) 31 | 32 | } 33 | 34 | object ServerSettings { 35 | val DefaultInterface = "localhost" 36 | val DefaultPort = 8080 37 | } 38 | -------------------------------------------------------------------------------- /src/test/resources/application.yml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #http: 4 | # server: 5 | # port: 8081 6 | -------------------------------------------------------------------------------- /src/test/scala/com/github/scalaspring/akka/http/MissingRouteSpec.scala: -------------------------------------------------------------------------------- 1 | package com.github.scalaspring.akka.http 2 | 3 | import akka.pattern.AskSupport 4 | import com.typesafe.scalalogging.StrictLogging 5 | import org.scalatest.concurrent.ScalaFutures 6 | import org.scalatest.{FlatSpec, Matchers} 7 | import org.springframework.beans.factory.BeanCreationException 8 | import org.springframework.boot.SpringApplication 9 | import org.springframework.context.annotation.Import 10 | import resource._ 11 | 12 | import scala.concurrent.duration._ 13 | 14 | class MissingRouteSpec extends FlatSpec with AkkaStreamsAutowiredImplicits with Matchers with AskSupport with ScalaFutures with StrictLogging { 15 | 16 | implicit val patience = PatienceConfig((10.seconds)) // Allow time for server startup 17 | 18 | "Context startup" should "fail when no route supplied" in { 19 | a [BeanCreationException] should be thrownBy 20 | managed(SpringApplication.run(classOf[MissingRouteSpec.Configuration])).map(identity).opt.get 21 | } 22 | 23 | } 24 | 25 | object MissingRouteSpec { 26 | 27 | // Missing route definition 28 | trait NoRouteService extends AkkaHttpService 29 | 30 | @Configuration 31 | @Import(Array(classOf[AkkaHttpServerAutoConfiguration])) 32 | class Configuration extends AkkaHttpServer with NoRouteService 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/test/scala/com/github/scalaspring/akka/http/MultiServiceSpec.scala: -------------------------------------------------------------------------------- 1 | package com.github.scalaspring.akka.http 2 | 3 | import java.net.ServerSocket 4 | 5 | import akka.http.scaladsl.client.RequestBuilding._ 6 | import akka.http.scaladsl.model.StatusCodes._ 7 | import akka.http.scaladsl.server.Directives._ 8 | import akka.http.scaladsl.server._ 9 | import akka.http.scaladsl.unmarshalling.Unmarshal 10 | import com.github.scalaspring.scalatest.TestContextManagement 11 | import com.typesafe.scalalogging.StrictLogging 12 | import org.scalatest.concurrent.ScalaFutures 13 | import org.scalatest.{FlatSpec, Matchers} 14 | import org.springframework.beans.factory.annotation.Autowired 15 | import org.springframework.boot.test.SpringApplicationContextLoader 16 | import org.springframework.context.annotation.{Bean, Import} 17 | import org.springframework.test.context.ContextConfiguration 18 | import resource._ 19 | 20 | import scala.concurrent.duration._ 21 | 22 | @ContextConfiguration( 23 | loader = classOf[SpringApplicationContextLoader], 24 | classes = Array(classOf[MultiServiceSpec.Configuration]) 25 | ) 26 | class MultiServiceSpec extends FlatSpec with TestContextManagement with AkkaStreamsAutowiredImplicits with Matchers with ScalaFutures with StrictLogging { 27 | 28 | implicit val patience = PatienceConfig((10.seconds)) // Allow time for server startup 29 | 30 | @Autowired val settings: ServerSettings = null 31 | @Autowired val client: HttpClient = null 32 | 33 | "Echo service" should "echo" in { 34 | val name = "name" 35 | val future = client.request(Get(s"http://${settings.interface}:${settings.port}/multi/echo/$name")) 36 | 37 | whenReady(future) { response => 38 | response.status shouldBe OK 39 | whenReady(Unmarshal(response.entity).to[String])(_ shouldBe name) 40 | } 41 | } 42 | 43 | "Reverse service" should "reverse" in { 44 | val name = "name" 45 | val future = client.request(Get(s"http://${settings.interface}:${settings.port}/multi/reverse/$name")) 46 | 47 | whenReady(future) { response => 48 | response.status shouldBe OK 49 | whenReady(Unmarshal(response.entity).to[String])(_ shouldBe name.reverse) 50 | } 51 | } 52 | 53 | } 54 | 55 | object MultiServiceSpec { 56 | 57 | @Configuration 58 | @Import(Array(classOf[AkkaHttpServerAutoConfiguration])) 59 | class Configuration extends AkkaHttpServer with EchoService with ReverseService { 60 | @Bean 61 | def serverSettings = new ServerSettings(port = managed(new ServerSocket(0)).map(_.getLocalPort).opt.get) 62 | } 63 | 64 | trait EchoService extends AkkaHttpService { 65 | abstract override def route: Route = { 66 | (get & path("multi"/"echo"/Segment)) { name => 67 | complete(name) 68 | } ~ super.route 69 | } 70 | } 71 | 72 | trait ReverseService extends AkkaHttpService { 73 | abstract override def route: Route = { 74 | (get & path("multi"/"reverse"/Segment)) { name => 75 | complete(name.reverse) 76 | } 77 | } ~ super.route 78 | } 79 | 80 | } 81 | -------------------------------------------------------------------------------- /src/test/scala/com/github/scalaspring/akka/http/RouteTestSpec.scala: -------------------------------------------------------------------------------- 1 | package com.github.scalaspring.akka.http 2 | 3 | import akka.http.scaladsl.model.StatusCodes._ 4 | import akka.http.scaladsl.server.Directives._ 5 | import akka.http.scaladsl.server._ 6 | import akka.http.scaladsl.testkit.ScalatestRouteTest 7 | import com.github.scalaspring.akka.http.RouteTestSpec.EchoService 8 | import com.typesafe.scalalogging.StrictLogging 9 | import org.scalatest.concurrent.ScalaFutures 10 | import org.scalatest.{FlatSpec, Matchers} 11 | 12 | 13 | class RouteTestSpec extends FlatSpec with EchoService with ScalatestRouteTest with Matchers with ScalaFutures with StrictLogging { 14 | 15 | "Echo service" should "echo" in { 16 | Get(s"/single/echo/hello") ~> route ~> check { 17 | status shouldBe OK 18 | } 19 | } 20 | 21 | } 22 | 23 | 24 | object RouteTestSpec { 25 | 26 | trait EchoService extends AkkaHttpService { 27 | abstract override def route: Route = { 28 | get { 29 | path("single"/ "echo" / Segment) { name => 30 | complete(name) 31 | } 32 | } 33 | } ~ super.route 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/test/scala/com/github/scalaspring/akka/http/SingleServiceSpec.scala: -------------------------------------------------------------------------------- 1 | package com.github.scalaspring.akka.http 2 | 3 | import java.net.ServerSocket 4 | 5 | import akka.http.scaladsl.client.RequestBuilding._ 6 | import akka.http.scaladsl.model.StatusCodes._ 7 | import akka.http.scaladsl.server.Directives._ 8 | import akka.http.scaladsl.server._ 9 | import akka.http.scaladsl.unmarshalling.Unmarshal 10 | import com.github.scalaspring.scalatest.TestContextManagement 11 | import com.typesafe.scalalogging.StrictLogging 12 | import org.scalatest.concurrent.ScalaFutures 13 | import org.scalatest.{FlatSpec, Matchers} 14 | import org.springframework.beans.factory.annotation.Autowired 15 | import org.springframework.boot.test.SpringApplicationContextLoader 16 | import org.springframework.context.annotation.{Bean, Import} 17 | import org.springframework.test.context.ContextConfiguration 18 | import resource._ 19 | 20 | import scala.concurrent.duration._ 21 | 22 | @ContextConfiguration( 23 | loader = classOf[SpringApplicationContextLoader], 24 | classes = Array(classOf[SingleServiceSpec.Configuration]) 25 | ) 26 | class SingleServiceSpec extends FlatSpec with TestContextManagement with AkkaStreamsAutowiredImplicits with Matchers with ScalaFutures with StrictLogging { 27 | 28 | implicit val patience = PatienceConfig(10.seconds) // Allow time for server startup 29 | 30 | @Autowired val settings: ServerSettings = null 31 | @Autowired val client: HttpClient = null 32 | 33 | "Echo service" should "echo" in { 34 | val name = "name" 35 | val future = client.request(Get(s"http://${settings.interface}:${settings.port}/single/echo/$name")) 36 | 37 | whenReady(future) { response => 38 | //logger.info(s"""received response "$response"""") 39 | response.status shouldBe OK 40 | whenReady(Unmarshal(response.entity).to[String])(_ shouldBe name) 41 | } 42 | } 43 | 44 | } 45 | 46 | 47 | object SingleServiceSpec { 48 | 49 | @Configuration 50 | @Import(Array(classOf[AkkaHttpServerAutoConfiguration])) 51 | class Configuration extends AkkaHttpServer with EchoService { 52 | @Bean 53 | def serverSettings = new ServerSettings(port = managed(new ServerSocket(0)).map(_.getLocalPort).opt.get) 54 | } 55 | 56 | trait EchoService extends AkkaHttpService { 57 | abstract override def route: Route = { 58 | get { 59 | path("single"/ "echo" / Segment) { name => 60 | complete(name) 61 | } 62 | } 63 | } ~ super.route 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /src/test/scala/sample/Application.scala: -------------------------------------------------------------------------------- 1 | package sample 2 | 3 | import akka.http.scaladsl.client.RequestBuilding._ 4 | import akka.http.scaladsl.server.Directives._ 5 | import akka.http.scaladsl.server._ 6 | import com.github.scalaspring.akka.http._ 7 | import org.springframework.beans.factory.annotation.Autowired 8 | import org.springframework.boot.SpringApplication 9 | import org.springframework.boot.autoconfigure.SpringBootApplication 10 | import org.springframework.context.annotation.Import 11 | 12 | 13 | // Echo a path segment 14 | trait EchoService extends AkkaHttpService { 15 | abstract override def route: Route = { 16 | (get & path("echo" / Segment)) { name => 17 | complete(name) 18 | } 19 | } ~ super.route 20 | } 21 | 22 | // Primitive site proxy (ex: http://localhost:8080/finance.yahoo.com) 23 | trait ProxyService extends AkkaHttpService { 24 | 25 | @Autowired val client: HttpClient = null 26 | 27 | abstract override def route: Route = { 28 | (get & path("proxy" / Segment)) { site => 29 | complete(client.request(Get(s"http://$site/"))) 30 | } 31 | } ~ super.route 32 | } 33 | 34 | @SpringBootApplication 35 | @Import(Array(classOf[AkkaHttpServerAutoConfiguration])) 36 | class Application extends AkkaHttpServer with EchoService with ProxyService 37 | 38 | object Application extends App { 39 | SpringApplication.run(classOf[Application], args: _*) 40 | } 41 | -------------------------------------------------------------------------------- /src/test/scala/sample/EchoServiceSpec.scala: -------------------------------------------------------------------------------- 1 | package sample 2 | 3 | import akka.http.scaladsl.model.StatusCodes._ 4 | import akka.http.scaladsl.testkit.ScalatestRouteTest 5 | import com.github.scalaspring.akka.http.AkkaStreamsAutoConfiguration 6 | import com.github.scalaspring.scalatest.TestContextManagement 7 | import org.scalatest.{FlatSpec, Matchers} 8 | import org.springframework.context.annotation.{Configuration, Import} 9 | import org.springframework.test.context.ContextConfiguration 10 | 11 | @Configuration 12 | @ContextConfiguration(classes = Array(classOf[EchoServiceSpec])) 13 | @Import(Array(classOf[AkkaStreamsAutoConfiguration])) 14 | class EchoServiceSpec extends FlatSpec with TestContextManagement with EchoService with ScalatestRouteTest with Matchers { 15 | 16 | "Echo service" should "echo" in { 17 | Get(s"/echo/test") ~> route ~> check { 18 | status shouldBe OK 19 | responseAs[String] shouldBe "test" 20 | } 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /version.sbt: -------------------------------------------------------------------------------- 1 | version := "0.3.1" --------------------------------------------------------------------------------