repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
frozenspider/fs-common-utils
|
src/main/scala/org/fs/utility/collection/RichCollectionImplicits.scala
|
package org.fs.utility.collection
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.util.zip.GZIPInputStream
import java.util.zip.GZIPOutputStream
import scala.collection.{ GenIterableLike => GIL }
import scala.collection.{ GenTraversableLike => GTL }
import scala.collection.IndexedSeqLike
import scala.collection.generic.{ CanBuildFrom => CBF }
import org.fs.utility.internal.Helpers
/**
* Implicit helpers for collections
*
* @author FS
*/
trait RichCollectionImplicits {
/** Iterable[X] enriched with some of most general support methods */
implicit class RichIterable[A, Repr](iter: GIL[A, Repr]) {
/**
* Map an iterable with its index.
*
* Roughly equivalent to `.zipWithIndex.map`, but allows inlining two-argument functions
* without pattern matching.
*/
def mapWithIndex[B, Repr2 <: GTL[(A, Int), Repr2], Repr3](
f: (A, Int) => B
)(implicit bf1: CBF[Repr, (A, Int), Repr2], bf2: CBF[Repr2, B, Repr3]): Repr3 =
{
iter.zipWithIndex map (x => f(x._1, x._2))
}
/**
* Applies a two-argument function to every element of an iterable along with its index.
*
* Roughly equivalent to `.zipWithIndex.foreach`, but allows inlining two-argument functions
* without pattern matching.
*/
def foreachWithIndex[U, That <: GTL[(A, Int), _]](
f: (A, Int) => U
)(implicit bf1: CBF[Repr, (A, Int), That]): Unit =
{
iter.zipWithIndex foreach (x => f(x._1, x._2))
}
/** Same as `dropWhile`, just reversed */
def dropRightWhile(pred: A => Boolean)(implicit bf: CBF[Repr, A, Repr]): Repr = {
val content = iter.toSeq.reverse.dropWhile(pred).reverse
val builder = bf()
content.foreach(builder += _)
builder.result()
}
}
/** IndexedSeqLike[X] enriched with some of most general support methods */
implicit class RichIndexedSeqLike[A, Repr](is: IndexedSeqLike[A, Repr]) {
/** Retrieve an element by its index if it's present, returning `None` otherwise */
def get(i: Int): Option[A] = {
if (i < 0 || i >= is.length) None
else Some(is(i))
}
/** Retrieve an element by its index if it's present, returning result of `default` evaluation otherwise */
def getOrElse[B >: A](i: Int, default: => B): B =
get(i).getOrElse(default)
}
/** Traversable[Option[X]] enriched with some of most general support methods */
implicit class RichOptionsTraversable[A, Repr <: GTL[Option[A], Repr]](iter: GTL[Option[A], Repr]) {
/** @return collection of defined values */
def yieldDefined[Repr2 <: GTL[A, Repr2]](implicit bf: CBF[Repr, A, Repr2]): Repr2 = {
iter filter (_.isDefined) map (_.get)
}
}
/** Iterable[Option[X]] enriched with some of most general support methods */
implicit class RichOptionsIterable[A](iter: Iterable[Option[A]]) {
/** @return map from indices to defined values */
def toDefinedMap: Map[Int, A] = {
val indexed = iter.zipWithIndex
val collected = indexed.collect({
case (Some(v), i) => (i, v)
})
collected.toMap
}
}
implicit class RichByteSeq(bs: Seq[Byte]) {
/** @return lowercase hex string of 2 characters per byte */
def toHexString: String = {
val sb = new StringBuilder(bs.length * 2)
for (b <- bs) {
val t = (if (b > 0) b else 256 + b).toHexString
if (t.length() == 1) {
sb.append("0")
}
if (t.length() == 3) {
sb.append("00")
} else {
sb.append(t)
}
}
sb.toString
}
/** @return content compressed using GZIP */
def gzip: Array[Byte] = {
val baos = new ByteArrayOutputStream()
val gzOs = new GZIPOutputStream(baos)
try {
gzOs.write(bs.toArray)
} finally {
gzOs.close()
}
baos.toByteArray
}
/** @return content decompressed using GZIP */
def gunzip: Array[Byte] = {
Helpers.readFully(new GZIPInputStream(new ByteArrayInputStream(bs.toArray)))
}
}
implicit class RichByteArray(bs: Array[Byte]) {
/** @return lowercase hex string of 2 characters per byte */
def toHexString: String = RichByteSeq(bs).toHexString
/** @return content compressed using GZIP */
def gzip: Array[Byte] = RichByteSeq(bs).gzip
/** @return content decompressed using GZIP */
def gunzip: Array[Byte] = RichByteSeq(bs).gunzip
}
}
object RichCollectionImplicits extends RichCollectionImplicits
|
frozenspider/fs-common-utils
|
src/test/scala/org/fs/utility/StopWatchSpec.scala
|
package org.fs.utility
import org.junit.runner.RunWith
import org.scalatest.Spec
import org.scalatest.junit.JUnitRunner
@RunWith(classOf[JUnitRunner])
class StopWatchSpec extends Spec {
def `peek ` = {
val sw = new StopWatch
Thread.sleep(100)
val peek = sw.peek
assert(peek >= 100 && peek <= 150)
}
def `measure ` = {
val (r, t) = StopWatch.measure {
Thread.sleep(100)
123
}
assert(t >= 100 && t <= 150)
assert(r == 123)
}
def `measure and call` = {
var rc: Int = 0
var tc: Long = 0
val r = StopWatch.measureAndCall {
Thread.sleep(100)
123
} { (r, t) =>
rc = r
tc = t
}
assert(r == 123)
assert(rc == 123)
assert(tc >= 100 && tc <= 150)
}
}
|
frozenspider/fs-common-utils
|
src/test/scala/org/fs/utility/RichGeneralImplicitsSpec.scala
|
package org.fs.utility
import org.junit.runner.RunWith
import org.scalatest.Spec
import org.scalatest.junit.JUnitRunner
@RunWith(classOf[JUnitRunner])
class RichGeneralImplicitsSpec extends Spec {
object `rich throwable -` {
import RichGeneralImplicits.RichThrowable
def `stackTraceString ` = {
val t = new Throwable("My message")
val s = t.stackTraceString
val lines = s.lines.toSeq
assert(lines.size > 1)
assert(lines(0) == "java.lang.Throwable: My message")
assert(lines(1) startsWith s"\tat ${classOf[RichGeneralImplicitsSpec].getCanonicalName}")
}
}
object `rich long -` {
import RichGeneralImplicits.RichLong
def `hhMmSsString ` = {
val h = 123L
val m = 53L
val s = 18L
val ms = 336L
val long = (((h * 60) + m) * 60 + s) * 1000 + ms
assert(long.hhMmSsString == s"$h:$m:$s")
}
}
}
|
frozenspider/fs-common-utils
|
src/main/scala/org/fs/utility/internal/Helpers.scala
|
<filename>src/main/scala/org/fs/utility/internal/Helpers.scala
package org.fs.utility.internal
import java.io.ByteArrayOutputStream
import java.io.InputStream
/**
* @author FS
*/
object Helpers {
// We won't rely on IOUtils.readFully to avoid dependency on commons-io
protected[utility] def readFully(is: InputStream): Array[Byte] = {
require(is != null, "Input stream was null")
try {
val result = new ByteArrayOutputStream()
val buffer = Array.ofDim[Byte](1024)
var length: Int = 0
do {
result.write(buffer, 0, length)
length = is.read(buffer)
} while (length != -1)
result.toByteArray
} finally {
try {
is.close()
} catch {
case _: Throwable => // Ignore
}
}
}
}
|
frozenspider/fs-common-utils
|
src/main/scala/org/fs/utility/Imports.scala
|
<gh_stars>0
package org.fs.utility
import org.fs.utility.collection.RichCollectionImplicits
trait Imports
extends RichGeneralImplicits
with RichCollectionImplicits
object Imports extends Imports
|
frozenspider/fs-common-utils
|
build.sbt
|
<reponame>frozenspider/fs-common-utils<filename>build.sbt
name := "fs-common-utils"
version := "0.1.3"
scalaVersion := "2.12.3"
crossScalaVersions := Seq("2.11.11", "2.12.3")
coverageExcludedPackages := "org.fs.utility.internal.*"
libraryDependencies ++= Seq(
// Test
"junit" % "junit" % "4.12" % "test",
"org.scalactic" %% "scalactic" % "3.0.4" % "test",
"org.scalatest" %% "scalatest" % "3.0.4" % "test"
)
|
frozenspider/fs-common-utils
|
src/test/scala/org/fs/utility/collection/RichCollectionImplicitsSpec.scala
|
<filename>src/test/scala/org/fs/utility/collection/RichCollectionImplicitsSpec.scala
package org.fs.utility.collection
import org.junit.runner.RunWith
import org.scalatest.Spec
import org.scalatest.junit.JUnitRunner
import scala.collection.GenIterableLike
import scala.collection.GenIterable
import scala.collection.IndexedSeqLike
import scala.collection.GenTraversableLike
@RunWith(classOf[JUnitRunner])
class RichCollectionImplicitsSpec extends Spec {
object `RichIterable -` {
import RichCollectionImplicits.RichIterable
val coll: GenIterableLike[String, GenIterable[String]] = Seq("a", "b", "c")
val empty: GenIterableLike[String, GenIterable[String]] = Seq.empty
def `map with index` = {
assert(coll.mapWithIndex((el, i) => el + i) === Seq("a0", "b1", "c2"))
assert(empty.mapWithIndex((el, i) => fail()) === empty)
}
def `foreach with index` = {
var acc = Seq.empty[String]
coll.foreachWithIndex((el, i) => acc = acc :+ (el + i))
assert(acc === Seq("a0", "b1", "c2"))
empty.foreachWithIndex((el, i) => fail())
}
def `drop right while` = {
assert(coll.dropRightWhile(_ != "c") === coll)
assert(coll.dropRightWhile(_ != "b") === Seq("a", "b"))
assert(coll.dropRightWhile(_ != "a") === Seq("a"))
assert(empty.dropRightWhile(_ != fail()) === empty)
}
}
object `RichIndexedSeqLike -` {
import RichCollectionImplicits.RichIndexedSeqLike
val coll: IndexedSeqLike[String, IndexedSeq[String]] = IndexedSeq("a", "b", "c")
val empty: IndexedSeqLike[String, IndexedSeq[String]] = IndexedSeq.empty
def `get ` = {
assert(coll.get(0) === Some("a"))
assert(coll.get(-1) === None)
assert(coll.get(3) === None)
assert(empty.get(0) === None)
}
def `get or else` = {
assert(coll.getOrElse(0, fail()) === "a")
assert(coll.getOrElse(-1, "x") === "x")
assert(coll.getOrElse(3, "x") === "x")
assert(empty.getOrElse(0, "x") === "x")
}
}
object `RichOptionsTraversable -` {
import RichCollectionImplicits.RichOptionsTraversable
val coll: GenTraversableLike[Option[String], Seq[Option[String]]] = Seq(None, Some("a"), None, Some("b"), Some("c"), None)
val empty: GenTraversableLike[Option[String], Seq[Option[String]]] = Seq.empty
def `yield defined` = {
assert(coll.yieldDefined === Seq("a", "b", "c"))
assert(empty.yieldDefined === Seq.empty)
}
}
object `RichOptionsIterable -` {
import RichCollectionImplicits.RichOptionsIterable
val coll: Iterable[Option[String]] = Seq(None, Some("a"), None, Some("b"), Some("c"), None)
val empty: Iterable[Option[String]] = Seq.empty
def `to defined map` = {
assert(coll.toDefinedMap === Map(1 -> "a", 3 -> "b", 4 -> "c"))
assert(empty.toDefinedMap === Map.empty)
}
}
object `RichByte* - ` {
// GZIP output is OS-dependant, so we won't check it vs original
val gzipPrefix = Seq(0x1F, 0x8B, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00) map (_.toByte)
// GZIPped via external resourcs
val emptyGzip = gzipPrefix ++ Seq(0xFF, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00).map(_.toByte)
val collGzip = gzipPrefix ++ Seq(0xFF, 0x4B, 0x4C, 0x4A, 0x4E, 0x01, 0x00, 0x11, 0xCD, 0x82, 0xED, 0x04, 0x00, 0x00, 0x00).map(_.toByte)
object `Seq -` {
import RichCollectionImplicits.RichByteSeq
val coll: Seq[Byte] = "abcd" map (_.toByte)
val empty: Seq[Byte] = Seq.empty
def `to hex string` = {
assert(coll.toHexString === "61626364")
assert(empty.toHexString === "")
assert(Seq(0x00, 0x01, 0xFF).map(_.toByte).toHexString === "0001ff")
}
def `gzip ` = {
assert(coll.gzip startsWith gzipPrefix)
assert(empty.gzip startsWith gzipPrefix)
assert(coll.gzip !== empty.gzip)
assert(coll.gzip.toSeq.gunzip === coll)
assert(empty.gzip.toSeq.gunzip === empty)
}
def `gunzip ` = {
assert(emptyGzip.gunzip === empty)
assert(collGzip.gunzip === coll)
}
}
object `Array -` {
import RichCollectionImplicits.RichByteArray
val coll: Array[Byte] = "abcd".map(_.toByte).toArray
val empty: Array[Byte] = Array.empty
def `to hex string` = {
assert(coll.toHexString === "61626364")
assert(empty.toHexString === "")
assert(Array(0x00, 0x01, 0xFF).map(_.toByte).toHexString === "0001ff")
}
def `gzip ` = {
assert(coll.gzip startsWith gzipPrefix)
assert(empty.gzip startsWith gzipPrefix)
assert(coll.gzip !== empty.gzip)
assert(coll.gzip.gunzip === coll)
assert(empty.gzip.gunzip === empty)
}
def `gunzip ` = {
assert(emptyGzip.toArray.gunzip === empty)
assert(collGzip.toArray.gunzip === coll)
}
}
}
}
|
frozenspider/fs-common-utils
|
src/main/scala/org/fs/utility/StopWatch.scala
|
<reponame>frozenspider/fs-common-utils<gh_stars>0
package org.fs.utility
/**
* @author FS
*/
class StopWatch {
val startMs = System.currentTimeMillis
def peek: Long =
System.currentTimeMillis - startMs
}
/**
* @author FS
*/
object StopWatch {
/** Execute code block and return execution result along with time taken */
def measure[R](block: => R): (R, Long) = {
val sw = new StopWatch
val res = block
(res, sw.peek)
}
/** Execute code block and return execution result, calling afterCall function with the measurement results */
def measureAndCall[R](block: => R)(afterCall: (R, Long) => Unit): R = {
val sw = new StopWatch
val res = block
afterCall(res, sw.peek)
res
}
}
|
precog/tectonic2
|
test/src/test/scala/tectonic/csv/ParserSpecs.scala
|
/*
* Copyright 2020 Precog Data
*
* 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 tectonic
package csv
import org.specs2.mutable.Specification
import tectonic.test.Event
import tectonic.test.csv._
import scala.List
class ParserSpecs extends Specification {
import Event._
"excel-style" should {
implicit val c = Parser.Config()
"parse a single value in one column" in {
"abc\r\nfubar\r\n" must parseAs(NestMap("abc"), Str("fubar"), Unnest, FinishRow)
}
"parse three values across three columns" in {
val input = "a,b,c\r\nr1c1,r1c2,r1c3\r\nr2c1,r2c2,r2c3\r\nr3c1,r3c2,r3c3\r\n"
input must parseAs(
NestMap("a"), Str("r1c1"), Unnest,
NestMap("b"), Str("r1c2"), Unnest,
NestMap("c"), Str("r1c3"), Unnest, FinishRow,
NestMap("a"), Str("r2c1"), Unnest,
NestMap("b"), Str("r2c2"), Unnest,
NestMap("c"), Str("r2c3"), Unnest, FinishRow,
NestMap("a"), Str("r3c1"), Unnest,
NestMap("b"), Str("r3c2"), Unnest,
NestMap("c"), Str("r3c3"), Unnest, FinishRow)
}
"allow \\r in values" in {
"a\r\nfu\rbar\r\n" must parseAs(NestMap("a"), Str("fu\rbar"), Unnest, FinishRow)
}
"allow , in quoted values" in {
"a\r\n\"fu,bar\"\r\n" must parseAs(NestMap("a"), Str("fu,bar"), Unnest, FinishRow)
}
"consume record delimiter following a quoted value" in {
"a,b\r\n\"fu,bar\",baz\r\n" must parseAs(
NestMap("a"), Str("fu,bar"), Unnest,
NestMap("b"), Str("baz"), Unnest, FinishRow)
}
"allow \" in quoted values with escaping" in {
"a\r\n\"fu\"\"bar\"\r\n" must parseAs(NestMap("a"), Str("fu\"bar"), Unnest, FinishRow)
}
"infer headers when unspecified" in {
implicit val c = Parser.Config().copy(header = false)
val input = "r1c1,r1c2,r1c3\r\nr2c1,r2c2,r2c3\r\nr3c1,r3c2,r3c3\r\n"
input must parseAs(
NestMap("A"), Str("r1c1"), Unnest,
NestMap("B"), Str("r1c2"), Unnest,
NestMap("C"), Str("r1c3"), Unnest, FinishRow,
NestMap("A"), Str("r2c1"), Unnest,
NestMap("B"), Str("r2c2"), Unnest,
NestMap("C"), Str("r2c3"), Unnest, FinishRow,
NestMap("A"), Str("r3c1"), Unnest,
NestMap("B"), Str("r3c2"), Unnest,
NestMap("C"), Str("r3c3"), Unnest, FinishRow)
}
"infer a really really long header" in {
import scala.Predef, Predef._
implicit val c = Parser.Config().copy(header = false)
val input = (0 until 52).mkString(",") + "\r\n"
val headers = List(
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
"AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ", "AK", "AL", "AM", "AN", "AO", "AP", "AQ", "AR", "AS", "AT", "AU", "AV", "AW", "AX", "AY", "AZ")
val generated = headers.zipWithIndex flatMap {
case (header, i) =>
List(NestMap(header), Str(i.toString), Unnest)
}
(input + input) must parseAs(generated ::: List(FinishRow) ::: generated ::: List(FinishRow): _*)
}
"parse a single value with a row ending in EOF" in {
"abc\r\nfubar" must parseAs(NestMap("abc"), Str("fubar"), Unnest, FinishRow)
}
"parse two values with a row ending in EOF" in {
"abc,def\r\nfubar,baz" must parseAs(
NestMap("abc"), Str("fubar"), Unnest,
NestMap("def"), Str("baz"), Unnest, FinishRow)
}
"parse a single value with an inferred header ending in EOF" in {
implicit val c = Parser.Config().copy(header = false)
"fubar" must parseAs(NestMap("A"), Str("fubar"), Unnest, FinishRow)
}
"parse a single quoted value with a row ending in EOF" in {
"abc\r\n\"fubar\"" must parseAs(NestMap("abc"), Str("fubar"), Unnest, FinishRow)
}
"parse a single quoted value with an inferred header ending in EOF" in {
implicit val c = Parser.Config().copy(header = false)
"\"fubar\"" must parseAs(NestMap("A"), Str("fubar"), Unnest, FinishRow)
}
"deal with doubled row delimiter sequence" in {
"foo\r\n\r\n" must parseAs(NestMap("foo"), Str(""), Unnest, FinishRow)
}
"allow row delimiter sequence in quoted record" in {
"a\r\n\"fu\r\nbar\"\r\n" must parseAs(NestMap("a"), Str("fu\r\nbar"), Unnest, FinishRow)
}
}
"excel-style with unix newlines" should {
implicit val c = Parser.Config().copy(row1 = '\n', row2 = 0)
"parse a single value" in {
"abc\nfubar\n" must parseAs(NestMap("abc"), Str("fubar"), Unnest, FinishRow)
}
"parse three values across three columns" in {
val input = "a,b,c\nr1c1,r1c2,r1c3\nr2c1,r2c2,r2c3\nr3c1,r3c2,r3c3\n"
input must parseAs(
NestMap("a"), Str("r1c1"), Unnest,
NestMap("b"), Str("r1c2"), Unnest,
NestMap("c"), Str("r1c3"), Unnest, FinishRow,
NestMap("a"), Str("r2c1"), Unnest,
NestMap("b"), Str("r2c2"), Unnest,
NestMap("c"), Str("r2c3"), Unnest, FinishRow,
NestMap("a"), Str("r3c1"), Unnest,
NestMap("b"), Str("r3c2"), Unnest,
NestMap("c"), Str("r3c3"), Unnest, FinishRow)
}
"infer headers when unspecified" in {
implicit val c = Parser.Config().copy(header = false, row1 = '\n', row2 = 0)
val input = "r1c1,r1c2,r1c3\nr2c1,r2c2,r2c3\nr3c1,r3c2,r3c3\n"
input must parseAs(
NestMap("A"), Str("r1c1"), Unnest,
NestMap("B"), Str("r1c2"), Unnest,
NestMap("C"), Str("r1c3"), Unnest, FinishRow,
NestMap("A"), Str("r2c1"), Unnest,
NestMap("B"), Str("r2c2"), Unnest,
NestMap("C"), Str("r2c3"), Unnest, FinishRow,
NestMap("A"), Str("r3c1"), Unnest,
NestMap("B"), Str("r3c2"), Unnest,
NestMap("C"), Str("r3c3"), Unnest, FinishRow)
}
}
"error reporting" should {
implicit val c = Parser.Config(row1 = '\n', row2 = 0)
"disallow empty headers" in {
"abc,,def" must failParseWithError {
case ParseException(msg, _, _, _) =>
msg must startWith("empty header cell")
}
}
"disallow empty quoted headers" in {
"abc,\"\",def" must failParseWithError {
case ParseException(msg, _, _, _) =>
msg must startWith("empty header cell")
}
}
"catch EOF in header" in {
"abc,def" must failParseWithError {
case ParseException(msg, _, _, _) =>
msg must startWith("unexpected end of file in header row")
}
}
"catch missing records at EOF" in {
"abc,def\nfoo" must failParseWithError {
case ParseException(msg, _, _, _) =>
msg must startWith("unexpected end of file: missing records")
}
}
"detect unexpected trailing characters" in {
"abc\n\"def\"derp\n" must failParseWithError {
case ParseException(msg, _, _, _) =>
msg must startWith("unexpected character found at record boundary")
}
}
"detect unclosed quoting" in {
"foo\n\"abc" must failParseWithError {
case ParseException(msg, _, _, _) =>
msg must startWith("unexpected end of file: unclosed quoted record")
}
}
"detect unclosed quoting after escaped close" in {
"abc\n\"def\"\"derp\n" must failParseWithError {
case ParseException(msg, _, _, _) =>
msg must startWith("unexpected end of file: unclosed quoted record")
}
}
}
}
|
precog/tectonic2
|
test/src/test/scala/tectonic/MultiplexingPlateSpecs.scala
|
/*
* Copyright 2020 <NAME>
*
* 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 tectonic
package test
import scala._
import cats.effect.IO
import org.specs2.mutable.Specification
class MultiplexingPlateSpecs extends Specification {
"MultiplexingPlate" should {
"retain state" >> {
"arr" in {
val mutant = MutantPlate[IO]().unsafeRunSync()
val reified = ReifiedTerminalPlate[IO](true).unsafeRunSync()
val plate = MultiplexingPlate[List[Event]](reified, mutant)
plate.arr()
mutant.mutant mustEqual "arr"
plate.finishBatch(true) mustEqual List(Event.Arr)
}
"map" in {
val mutant = MutantPlate[IO]().unsafeRunSync()
val reified = ReifiedTerminalPlate[IO](true).unsafeRunSync()
val plate = MultiplexingPlate[List[Event]](reified, mutant)
plate.map()
mutant.mutant mustEqual "map"
plate.finishBatch(true) mustEqual List(Event.Map)
}
"fls" in {
val mutant = MutantPlate[IO]().unsafeRunSync()
val reified = ReifiedTerminalPlate[IO](true).unsafeRunSync()
val plate = MultiplexingPlate[List[Event]](reified, mutant)
plate.fls()
mutant.mutant mustEqual "fls"
plate.finishBatch(true) mustEqual List(Event.Fls)
}
"tru" in {
val mutant = MutantPlate[IO]().unsafeRunSync()
val reified = ReifiedTerminalPlate[IO](true).unsafeRunSync()
val plate = MultiplexingPlate[List[Event]](reified, mutant)
plate.tru()
mutant.mutant mustEqual "tru"
plate.finishBatch(true) mustEqual List(Event.Tru)
}
"nul" in {
val mutant = MutantPlate[IO]().unsafeRunSync()
val reified = ReifiedTerminalPlate[IO](true).unsafeRunSync()
val plate = MultiplexingPlate[List[Event]](reified, mutant)
plate.nul()
mutant.mutant mustEqual "nul"
plate.finishBatch(true) mustEqual List(Event.Nul)
}
"num" in {
val mutant = MutantPlate[IO]().unsafeRunSync()
val reified = ReifiedTerminalPlate[IO](true).unsafeRunSync()
val plate = MultiplexingPlate[List[Event]](reified, mutant)
plate.num("42", 0, 0)
mutant.mutant mustEqual "num42"
plate.finishBatch(true) mustEqual List(Event.Num("42", 0, 0))
}
"str" in {
val mutant = MutantPlate[IO]().unsafeRunSync()
val reified = ReifiedTerminalPlate[IO](true).unsafeRunSync()
val plate = MultiplexingPlate[List[Event]](reified, mutant)
plate.str("foo")
mutant.mutant mustEqual "strfoo"
plate.finishBatch(true) mustEqual List(Event.Str("foo"))
}
"nestArr" in {
val mutant = MutantPlate[IO]().unsafeRunSync()
val reified = ReifiedTerminalPlate[IO](true).unsafeRunSync()
val plate = MultiplexingPlate[List[Event]](reified, mutant)
plate.nestArr()
mutant.mutant mustEqual "nestArr"
plate.finishBatch(true) mustEqual List(Event.NestArr)
}
"nestMap" in {
val mutant = MutantPlate[IO]().unsafeRunSync()
val reified = ReifiedTerminalPlate[IO](true).unsafeRunSync()
val plate = MultiplexingPlate[List[Event]](reified, mutant)
plate.nestMap("foo")
mutant.mutant mustEqual "nestMapfoo"
plate.finishBatch(true) mustEqual List(Event.NestMap("foo"))
}
"nestMeta" in {
val mutant = MutantPlate[IO]().unsafeRunSync()
val reified = ReifiedTerminalPlate[IO](true).unsafeRunSync()
val plate = MultiplexingPlate[List[Event]](reified, mutant)
plate.nestMeta("foo")
mutant.mutant mustEqual "nestMetafoo"
plate.finishBatch(true) mustEqual List(Event.NestMeta("foo"))
}
"unnest" in {
val mutant = MutantPlate[IO]().unsafeRunSync()
val reified = ReifiedTerminalPlate[IO](true).unsafeRunSync()
val plate = MultiplexingPlate[List[Event]](reified, mutant)
plate.unnest
mutant.mutant mustEqual "unnest"
plate.finishBatch(true) mustEqual List(Event.Unnest)
}
"skipped" in {
val mutant = MutantPlate[IO]().unsafeRunSync()
val reified = ReifiedTerminalPlate[IO](true).unsafeRunSync()
val plate = MultiplexingPlate[List[Event]](reified, mutant)
plate.skipped(12)
mutant.mutant mustEqual "skipped12"
plate.finishBatch(true) mustEqual List(Event.Skipped(12))
}
"finishBatch" in {
val mutant = MutantPlate[IO]().unsafeRunSync()
val reified = ReifiedTerminalPlate[IO](true).unsafeRunSync()
val plate = MultiplexingPlate[List[Event]](reified, mutant)
plate.finishBatch(true) mustEqual List()
mutant.mutant mustEqual "finishBatchtrue"
}
"finishRow" in {
val mutant = MutantPlate[IO]().unsafeRunSync()
val reified = ReifiedTerminalPlate[IO](true).unsafeRunSync()
val plate = MultiplexingPlate[List[Event]](reified, mutant)
plate.finishRow()
mutant.mutant mustEqual "finishRow"
plate.finishBatch(true) mustEqual List(Event.FinishRow)
}
}
}
}
|
precog/tectonic2
|
test/src/main/scala/tectonic/test/json/package.scala
|
/*
* Copyright 2020 <NAME>
*
* 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 tectonic
package test
import cats.effect.IO
import org.specs2.matcher.{Matcher, MatchersImplicits}
import tectonic.json.Parser
import scala.{List, StringContext}
package object json {
private object MatchersImplicits extends MatchersImplicits
import MatchersImplicits._
def parseRowAs[A: Absorbable](expected: Event*): Matcher[A] =
parseAs(expected :+ Event.FinishRow: _*)
def parseAs[A: Absorbable](expected: Event*): Matcher[A] =
parseAsWithPlate(expected: _*)(p => p)
def parseAsWithPlate[A: Absorbable](expected: Event*)(f: Plate[List[Event]] => Plate[List[Event]]): Matcher[A] = { input: A =>
val resultsF = for {
parser <- Parser(ReifiedTerminalPlate[IO]().map(f), Parser.ValueStream)
left <- Absorbable[A].absorb(parser, input)
right <- parser.finish
} yield (left, right)
resultsF.unsafeRunSync() match {
case (ParseResult.Complete(init), ParseResult.Complete(tail)) =>
val results = init ++ tail
(results == expected.toList, s"$results != ${expected.toList}")
case (ParseResult.Partial(a, remaining), _) =>
(false, s"left partially succeded with partial result $a and $remaining bytes remaining")
case (_, ParseResult.Partial(a, remaining)) =>
(false, s"right partially succeded with partial result $a and $remaining bytes remaining")
case (ParseResult.Failure(err), _) =>
(false, s"failed to parse with error '${err.getMessage}' at ${err.line}:${err.col} (i=${err.index})")
case (_, ParseResult.Failure(err)) =>
(false, s"failed to parse with error '${err.getMessage}' at ${err.line}:${err.col} (i=${err.index})")
}
}
def failToParseWith[A: Absorbable](expected: ParseException): Matcher[A] = { input: A =>
val resultsF = for {
parser <- Parser(ReifiedTerminalPlate[IO](), Parser.ValueStream)
left <- Absorbable[A].absorb(parser, input)
right <- parser.finish
} yield (left, right)
resultsF.unsafeRunSync() match {
case (ParseResult.Complete(_), ParseResult.Complete(_)) =>
(false, s"blergh", s"input parsed successfully (expected failure)")
case (ParseResult.Partial(a, remaining), _) =>
(false, "", s"left partially succeded with partial result $a and $remaining bytes remaining")
case (_, ParseResult.Partial(a, remaining)) =>
(false, "", s"right partially succeded with partial result $a and $remaining bytes remaining")
case (ParseResult.Failure(err), _) =>
(err == expected, s"input failed to parse and $err == $expected", s"input failed to parse but $err != $expected")
case (_, ParseResult.Failure(err)) =>
(err == expected, s"input failed to parse and $err == $expected", s"input failed to parse but $err != $expected")
}
}
}
|
precog/tectonic2
|
fs2/src/test/scala/tectonic/fs2/StreamParserSpecs.scala
|
<filename>fs2/src/test/scala/tectonic/fs2/StreamParserSpecs.scala<gh_stars>0
/*
* Copyright 2020 Precog Data
*
* 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 tectonic
package fs2
import cats.effect.IO
import cats.instances.list._
import _root_.fs2.{Chunk, Pipe, Stream}
import tectonic.json.Parser
import tectonic.test.{Event, ReifiedTerminalPlate}
import org.specs2.mutable.Specification
import scodec.bits.ByteVector
import scala.{Boolean, Byte, Int, List, Unit}
import java.lang.CharSequence
import java.nio.ByteBuffer
class StreamParserSpecs extends Specification {
import Event._
val parserF: IO[BaseParser[IO, List[Event]]] =
Parser(ReifiedTerminalPlate[IO](), Parser.ValueStream)
val parser: Pipe[IO, Byte, Event] =
StreamParser.foldable(parserF)
"stream parser transduction" should {
"parse a single value" in {
val results = Stream.chunk(Chunk.Bytes("42".getBytes)).through(parser)
results.compile.toList.unsafeRunSync() mustEqual List(Num("42", -1, -1), FinishRow)
}
"parse two values from a single chunk" in {
val results = Stream.chunk(Chunk.Bytes("16 true".getBytes)).through(parser)
val expected = List(Num("16", -1, -1), FinishRow, Tru, FinishRow)
results.compile.toList.unsafeRunSync() mustEqual expected
}
"parse a value split across two chunks" in {
val input = Stream.chunk(Chunk.Bytes("7".getBytes)) ++
Stream.chunk(Chunk.Bytes("9".getBytes))
val results = input.through(parser)
val expected = List(Num("79", -1, -1), FinishRow)
results.compile.toList.unsafeRunSync() mustEqual expected
}
"parse two values from two chunks" in {
val input = Stream.chunk(Chunk.Bytes("321 ".getBytes)) ++
Stream.chunk(Chunk.Bytes("true".getBytes))
val results = input.through(parser)
val expected = List(Num("321", -1, -1), FinishRow, Tru, FinishRow)
results.compile.toList.unsafeRunSync() mustEqual expected
}
"parse a value from a bytebuffer chunk" in {
val input = Stream.chunk(Chunk.ByteBuffer(ByteBuffer.wrap("123".getBytes)))
val results = input.through(parser)
val expected = List(Num("123", -1, -1), FinishRow)
results.compile.toList.unsafeRunSync() mustEqual expected
}
"parse two values from a split bytevector chunk" in {
val input = Stream.chunk(
Chunk.ByteVectorChunk(
ByteVector.view(ByteBuffer.wrap("456 ".getBytes)) ++
ByteVector.view(ByteBuffer.wrap("true".getBytes))))
val results = input.through(parser)
val expected = List(Num("456", -1, -1), FinishRow, Tru, FinishRow)
results.compile.toList.unsafeRunSync() mustEqual expected
}
// this test also tests the json parser
"parse two values with partial batch consumption" in {
val input = Stream.chunk(Chunk.Bytes("[123, false]".getBytes))
val plateF = ReifiedTerminalPlate[IO]() map { delegate =>
new Plate[List[Event]] {
import Signal.BreakBatch
def nul(): Signal = {
delegate.nul()
BreakBatch
}
def fls(): Signal = {
delegate.fls()
BreakBatch
}
def tru(): Signal = {
delegate.tru()
BreakBatch
}
def map(): Signal = {
delegate.map()
BreakBatch
}
def arr(): Signal = {
delegate.arr()
BreakBatch
}
def num(s: CharSequence, decIdx: Int, expIdx: Int): Signal = {
delegate.num(s, decIdx, expIdx)
BreakBatch
}
def str(s: CharSequence): Signal = {
delegate.str(s)
BreakBatch
}
def nestMap(pathComponent: CharSequence): Signal = {
delegate.nestMap(pathComponent)
BreakBatch
}
def nestArr(): Signal = {
delegate.nestArr()
BreakBatch
}
def nestMeta(pathComponent: CharSequence): Signal = {
delegate.nestMeta(pathComponent)
BreakBatch
}
def unnest(): Signal = {
delegate.unnest()
BreakBatch
}
def finishRow(): Unit =
delegate.finishRow()
def finishBatch(terminal: Boolean): List[Event] =
delegate.finishBatch(terminal)
def skipped(bytes: Int): Unit =
delegate.skipped(bytes)
}
}
val results = input.through(StreamParser.foldable(Parser(plateF, Parser.ValueStream)))
// note that we're getting visibility into the laziness by exposing chunk boundaries
results.chunks.compile.toList.unsafeRunSync().map(_.toList) mustEqual
List(
List(NestArr),
List(Num("123", -1, -1)),
List(Unnest, NestArr),
List(Fls),
List(Unnest, FinishRow))
}
}
}
|
precog/tectonic2
|
build.sbt
|
import scala.collection.Seq
ThisBuild / crossScalaVersions := Seq("2.12.12", "2.13.1")
ThisBuild / scalaVersion := "2.12.12"
ThisBuild / githubRepository := "tectonic2"
homepage in ThisBuild := Some(url("https://github.com/precog/tectonic2"))
scmInfo in ThisBuild := Some(ScmInfo(
url("https://github.com/precog/tectonic2"),
"scm:<EMAIL>:precog/tectonic2.git"))
val Fs2Version = "2.5.6"
ThisBuild / publishAsOSSProject := true
val commonOverrides = Seq(
githubRepository := "tectonic2",
organization := "com.precog.v2")
// Include to also publish a project's tests
lazy val publishTestsSettings = Seq(
publishArtifact in (Test, packageBin) := true)
lazy val root = project
.in(file("."))
.settings(noPublishSettings)
.aggregate(core, fs2, test, benchmarks, harness)
.settings(commonOverrides)
.enablePlugins(AutomateHeaderPlugin)
lazy val core = project
.in(file("core"))
.settings(name := "tectonic")
.settings(libraryDependencies += "org.typelevel" %% "cats-effect" % "2.5.1")
.settings(commonOverrides)
.enablePlugins(AutomateHeaderPlugin)
lazy val fs2 = project
.in(file("fs2"))
.dependsOn(
core,
test % "test->test")
.settings(commonOverrides)
.settings(name := "tectonic-fs2")
.settings(
libraryDependencies += "co.fs2" %% "fs2-core" % Fs2Version)
.enablePlugins(AutomateHeaderPlugin)
lazy val harness = project
.in(file("harness"))
.dependsOn(
fs2)
.settings(commonOverrides)
.settings(name := "tectonic-harness")
.settings(noPublishSettings) // mostly for internal testing
.settings(
libraryDependencies += "co.fs2" %% "fs2-io" % Fs2Version)
.enablePlugins(AutomateHeaderPlugin)
lazy val test = project
.in(file("test"))
.dependsOn(core)
.settings(name := "tectonic-test")
.settings(commonOverrides)
.settings(
libraryDependencies ++= Seq(
"org.specs2" %% "specs2-core" % "4.10.6",
"org.scalacheck" %% "scalacheck" % "1.15.4"),
libraryDependencies += "org.specs2" %% "specs2-scalacheck" % "4.10.6" % Test)
.enablePlugins(AutomateHeaderPlugin)
lazy val benchmarks = project
.in(file("benchmarks"))
.dependsOn(core, fs2)
.settings(name := "tectonic-benchmarks")
.settings(commonOverrides)
.settings(noPublishSettings)
.settings(
scalacStrictMode := false,
javaOptions += "-XX:+HeapDumpOnOutOfMemoryError",
javaOptions += s"-Dproject.resource.dir=${(Compile / resourceDirectory).value}",
javaOptions += s"-Dproject.managed.resource.dir=${(Jmh / resourceManaged).value}",
libraryDependencies ++= Seq(
"co.fs2" %% "fs2-core" % Fs2Version,
"co.fs2" %% "fs2-io" % Fs2Version,
"org.http4s" %% "jawn-fs2" % "1.1.3"))
.settings( // magic rewiring so sbt-jmh works sanely
Jmh / sourceDirectory := (Compile / sourceDirectory).value,
Jmh / classDirectory := (Compile / classDirectory).value,
Jmh / dependencyClasspath := (Compile / dependencyClasspath).value,
Jmh / compile := (Jmh / compile).dependsOn(Compile / compile).value,
Jmh / run := (Jmh / run).dependsOn(Jmh / compile).evaluated)
.settings(
Jmh / resourceGenerators += Def.task {
import scala.sys.process._
val targetDir = (Jmh / resourceManaged).value
val targetFile = targetDir / "worldcitiespop.txt"
if (!targetFile.exists()) {
// the original source took it offline, so now it's in my dropbox 🤷♂️
s"curl -L -o $targetDir/worldcitiespop.txt.gz https://www.dropbox.com/s/8tfbn4a7x2tam4n/worldcitiespop.txt.gz?dl=1".!!
s"gunzip $targetDir/worldcitiespop.txt.gz".!!
}
Seq(targetFile)
}.taskValue)
.enablePlugins(AutomateHeaderPlugin)
.enablePlugins(JmhPlugin)
|
precog/tectonic2
|
benchmarks/src/main/scala/tectonic/csv/ParserBenchmarks.scala
|
<reponame>precog/tectonic2<filename>benchmarks/src/main/scala/tectonic/csv/ParserBenchmarks.scala
/*
* Copyright 2020 <NAME>
*
* 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 tectonic
package csv
import cats.effect.{Blocker, ContextShift, IO}
import cats.instances.int._
import _root_.fs2.Chunk
import _root_.fs2.io.file
import org.openjdk.jmh.annotations.{Benchmark, BenchmarkMode, Mode, OutputTimeUnit, Param, Scope, State}
import tectonic.fs2.StreamParser
import scala.concurrent.ExecutionContext
import java.nio.file.Paths
import java.util.concurrent.{Executors, TimeUnit}
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@BenchmarkMode(Array(Mode.AverageTime))
@State(Scope.Benchmark)
class ParserBenchmarks {
val TectonicFramework = "tectonic"
val JacksonFramework = "jackson"
private[this] implicit val CS: ContextShift[IO] =
IO.contextShift(ExecutionContext.global)
private[this] val BlockingPool =
Blocker.liftExecutionContext(
ExecutionContext.fromExecutor(Executors newCachedThreadPool { r =>
val t = new Thread(r)
t.setDaemon(true)
t
}))
private[this] val ChunkSize = 65536
private[this] val ResourceDir =
Paths.get(System.getProperty("project.managed.resource.dir"))
// params
@Param(Array("tectonic"/*, "jackson"*/))
var framework: String = _
// benchmarks
// includes the cost of file IO; not sure if that's a good thing?
@Benchmark
def parseThroughFs2(): Unit = {
val inputFile = "worldcitiespop.txt"
val countingPlate = IO {
new Plate[Int] {
private[this] final var count = 0
private[this] final val c = Signal.Continue
def nul(): Signal = c
def fls(): Signal = c
def tru(): Signal = c
def map(): Signal = c
def arr(): Signal = c
def num(s: CharSequence, decIdx: Int, expIdx: Int): Signal = c
def str(s: CharSequence): Signal = c
def nestMap(pathComponent: CharSequence): Signal = c
def nestArr(): Signal = c
def nestMeta(pathComponent: CharSequence): Signal = c
def unnest(): Signal = c
def finishRow(): Unit = count += 1
def finishBatch(terminal: Boolean): Int = {
val back = count
count = 0
back
}
def skipped(bytes: Int) = ()
}
}
val contents = file.readAll[IO](
ResourceDir.resolve(inputFile),
BlockingPool,
ChunkSize)
val processed = if (framework == TectonicFramework) {
val parser =
StreamParser[IO, Int, Int](
Parser(countingPlate, Parser.Config().copy(row1 = '\n', row2 = 0)))(Chunk.singleton(_))
contents.through(parser).foldMonoid
} else {
???
}
processed.compile.drain.unsafeRunSync()
}
@Benchmark
def lineCountThroughFs2(): Unit = {
val inputFile = "worldcitiespop.txt"
val contents = file.readAll[IO](
ResourceDir.resolve(inputFile),
BlockingPool,
ChunkSize)
val counts = contents.chunks map { bytes =>
val buf = bytes.toByteBuffer
val buflen = buf.limit() - buf.position()
val temp: Array[Byte] = new Array[Byte](buflen)
buf.get(temp, 0, buflen)
var i = 0
var c = 0
while (i < temp.length) {
if ((temp(i) & 0xff) == '\n') {
c += 1
}
i += 1
}
c
}
counts.foldMonoid.compile.drain.unsafeRunSync()
}
}
|
precog/tectonic2
|
version.sbt
|
<filename>version.sbt<gh_stars>0
version in ThisBuild := "15.0.0"
|
kharole/fpinscala
|
answers/src/main/scala/fpinscala/iomonad/fp13.scala
|
<filename>answers/src/main/scala/fpinscala/iomonad/fp13.scala<gh_stars>0
package fpinscala.iomonad
import fpinscala.iomonad
import fpinscala.parallelism.Nonblocking.Par
object fp13 {
//13.1
def freeMonad[F[_]]: Monad[({type f[a] = Free[F, a]})#f] = new Monad[({type f[a] = Free[F, a]})#f] {
override def unit[A](a: => A): Free[F, A] = IO3.Return(a)
override def flatMap[A, B](a: Free[F, A])(f: A => Free[F, B]): Free[F, B] = IO3.FlatMap(a, f)
}
//13.2
@annotation.tailrec
def runTrampoline[A](a: Free[Function0, A]): A = a match {
case IO3.Return(a) => a
case IO3.Suspend(s) => s()
case IO3.FlatMap(s, f) => {
s match {
case IO3.Return(a) => runTrampoline(f(a))
case IO3.Suspend(r) => runTrampoline(f(r()))
case IO3.FlatMap(y, g) => runTrampoline(y flatMap (a => g(a) flatMap f))
}
}
}
//13.3
def run[F[_], A](a: Free[F, A])(implicit F: Monad[F]): F[A] = step(a) match {
case IO3.Suspend(x) => F.flatMap(x)((a: A) => run(IO3.Return(a)))
case IO3.Return(a) => F.unit(a)
case IO3.FlatMap(x, f) => x match {
case IO3.Suspend(r) => F.flatMap(r)(a => run(f(a)))
case _ => sys.error("Impossible; `step` eliminates these cases")
}
}
@annotation.tailrec
def step[F[_], A](a: Free[F, A]): Free[F, A] = a match {
case IO3.FlatMap(IO3.FlatMap(x, f), g) => step(x flatMap (a => f(a) flatMap g))
case _ => a
}
sealed trait Console[A] {
def toPar: Par[A]
def toThunk: () => A
}
case object ReadLine extends Console[Option[String]] {
def toPar = Par.lazyUnit(run)
def toThunk = () => run
def run: Option[String] =
try Some(readLine())
catch {
case e: Exception => None
}
}
case class PrintLine(line: String) extends Console[Unit] {
def toPar = Par.lazyUnit(println(line))
def toThunk = () => println(line)
}
trait Translate[F[_], G[_]] {
def apply[A](f: F[A]): G[A]
}
type ~>[F[_], G[_]] = Translate[F, G]
def runFree[F[_], G[_], A](free: Free[F, A])(t: F ~> G)(
implicit G: Monad[G]): G[A] =
step(free) match {
case IO3.Return(a) => G.unit(a)
case IO3.Suspend(r) => t(r)
case IO3.FlatMap(IO3.Suspend(r), f) => G.flatMap(t(r))(a => runFree(f(a))(t))
case _ => sys.error("Impossible; `step` eliminates these cases")
}
//13.4
def translate[F[_],G[_],A](f: Free[F,A])(fg: F ~> G): Free[G,A] = {
type FreeG[A] = Free[G,A]
val t = new (F ~> FreeG) {
def apply[A](a: F[A]): Free[G,A] = IO3.Suspend { fg(a) }
}
runFree(f)(t)(freeMonad[G])
}
def runConsole[A](a: Free[Console,A]): A =
runTrampoline { translate(a)(new (Console ~> Function0) {
def apply[A](c: Console[A]) = c.toThunk
})}
//13.5
import java.nio._
import java.nio.channels._
def read(file: AsynchronousFileChannel,
fromPosition: Long,
numBytes: Int): Par[Either[Throwable, Array[Byte]]] =
Par.async { (cb: Either[Throwable, Array[Byte]] => Unit) =>
val buf = ByteBuffer.allocate(numBytes)
file.read(buf, fromPosition, (), new CompletionHandler[Integer, Unit] {
def completed(bytesRead: Integer, ignore: Unit) = {
val arr = new Array[Byte](bytesRead)
buf.slice.get(arr, 0, bytesRead)
cb(Right(arr))
}
def failed(err: Throwable, ignore: Unit) =
cb(Left(err))
})
}
}
|
kharole/fpinscala
|
answers/src/main/scala/fpinscala/testing/fp8.scala
|
import fpinscala.parallelism.Par
import fpinscala.parallelism.Par.Par
object fp8 {
import java.util.concurrent.{Callable, CountDownLatch, ExecutorService}
import RNG._
import fpinscala.parallelism.Actor
import fpinscala.testing.Prop.Passed
import scala.collection.immutable
//8.1
/*
sum: List[Int] => Int
import fpinscala.testing.Gen
val intList = Gen.listOf(Gen.choose(0,100))
val prop = forAll(intList)(ns => sum(ns.reverse) == sum(ns))
val intList = List.fill(100)(Gen.choose(0,100))
val prop = forAll(intList)(ns => sum(ns) == 100*ns.head)
val prop = forAll(intList)(ns => sum(ns) == ns.head + sum(ns.tail))
*/
//8.2
/*
max: List[Int] => Int //listOf1
val prop = forAll(intList)(ns => ns.forall(_ <= max(ns)))
*/
//8.3
trait Prop2 {
def check: Boolean
def &&(p: Prop2): Prop2 = new Prop2 {
def check: Boolean = this.check && p.check
}
}
trait RNG {
def nextInt: (Int, RNG) // Should generate a random `Int`. We'll later define other functions in terms of `nextInt`.
}
object RNG {
// NB - this was called SimpleRNG in the book text
case class Simple(seed: Long) extends RNG {
def nextInt: (Int, RNG) = {
val newSeed = (seed * 0x5DEECE66DL + 0xBL) & 0xFFFFFFFFFFFFL // `&` is bitwise AND. We use the current seed to generate a new seed.
val nextRNG = Simple(newSeed) // The next state, which is an `RNG` instance created from the new seed.
val n = (newSeed >>> 16).toInt // `>>>` is right binary shift with zero fill. The value `n` is our new pseudo-random integer.
(n, nextRNG) // The return value is a tuple containing both a pseudo-random integer and the next `RNG` state.
}
}
// We need to be quite careful not to skew the generator.
// Since `Int.Minvalue` is 1 smaller than `-(Int.MaxValue)`,
// it suffices to increment the negative numbers by 1 and make them positive.
// This maps Int.MinValue to Int.MaxValue and -1 to 0.
def nonNegativeInt(rng: RNG): (Int, RNG) = {
val (i, r) = rng.nextInt
(if (i < 0) -(i + 1) else i, r)
}
// We generate an integer >= 0 and divide it by one higher than the
// maximum. This is just one possible solution.
def double(rng: RNG): (Double, RNG) = {
val (i, r) = nonNegativeInt(rng)
(i / (Int.MaxValue.toDouble + 1), r)
}
def boolean(rng: RNG): (Boolean, RNG) =
rng.nextInt match {
case (i, rng2) => (i % 2 == 0, rng2)
}
def intDouble(rng: RNG): ((Int, Double), RNG) = {
val (i, r1) = rng.nextInt
val (d, r2) = double(r1)
((i, d), r2)
}
def doubleInt(rng: RNG): ((Double, Int), RNG) = {
val ((i, d), r) = intDouble(rng)
((d, i), r)
}
def double3(rng: RNG): ((Double, Double, Double), RNG) = {
val (d1, r1) = double(rng)
val (d2, r2) = double(r1)
val (d3, r3) = double(r2)
((d1, d2, d3), r3)
}
// There is something terribly repetitive about passing the RNG along
// every time. What could we do to eliminate some of this duplication
// of effort?
// A simple recursive solution
def ints(count: Int)(rng: RNG): (List[Int], RNG) =
if (count == 0)
(List(), rng)
else {
val (x, r1) = rng.nextInt
val (xs, r2) = ints(count - 1)(r1)
(x :: xs, r2)
}
// A tail-recursive solution
def ints2(count: Int)(rng: RNG): (List[Int], RNG) = {
def go(count: Int, r: RNG, xs: List[Int]): (List[Int], RNG) =
if (count == 0)
(xs, r)
else {
val (x, r2) = r.nextInt
go(count - 1, r2, x :: xs)
}
go(count, rng, List())
}
type Rand[+A] = RNG => (A, RNG)
val int: Rand[Int] = _.nextInt
def unit[A](a: A): Rand[A] =
rng => (a, rng)
def map[A, B](s: Rand[A])(f: A => B): Rand[B] =
rng => {
val (a, rng2) = s(rng)
(f(a), rng2)
}
val _double: Rand[Double] =
map(nonNegativeInt)(_ / (Int.MaxValue.toDouble + 1))
// This implementation of map2 passes the initial RNG to the first argument
// and the resulting RNG to the second argument. It's not necessarily wrong
// to do this the other way around, since the results are random anyway.
// We could even pass the initial RNG to both `f` and `g`, but that might
// have unexpected results. E.g. if both arguments are `RNG.int` then we would
// always get two of the same `Int` in the result. When implementing functions
// like this, it's important to consider how we would test them for
// correctness.
def map2[A, B, C](ra: Rand[A], rb: Rand[B])(f: (A, B) => C): Rand[C] =
rng => {
val (a, r1) = ra(rng)
val (b, r2) = rb(r1)
(f(a, b), r2)
}
def both[A, B](ra: Rand[A], rb: Rand[B]): Rand[(A, B)] =
map2(ra, rb)((_, _))
val randIntDouble: Rand[(Int, Double)] =
both(int, double)
val randDoubleInt: Rand[(Double, Int)] =
both(double, int)
// In `sequence`, the base case of the fold is a `unit` action that returns
// the empty list. At each step in the fold, we accumulate in `acc`
// and `f` is the current element in the list.
// `map2(f, acc)(_ :: _)` results in a value of type `Rand[List[A]]`
// We map over that to prepend (cons) the element onto the accumulated list.
//
// We are using `foldRight`. If we used `foldLeft` then the values in the
// resulting list would appear in reverse order. It would be arguably better
// to use `foldLeft` followed by `reverse`. What do you think?
def sequence[A](fs: List[Rand[A]]): Rand[List[A]] =
fs.foldRight(unit(List[A]()))((f, acc) => map2(f, acc)(_ :: _))
// It's interesting that we never actually need to talk about the `RNG` value
// in `sequence`. This is a strong hint that we could make this function
// polymorphic in that type.
def _ints(count: Int): Rand[List[Int]] =
sequence(List.fill(count)(int))
def flatMap[A, B](f: Rand[A])(g: A => Rand[B]): Rand[B] =
rng => {
val (a, r1) = f(rng)
g(a)(r1) // We pass the new state along
}
def nonNegativeLessThan(n: Int): Rand[Int] = {
flatMap(nonNegativeInt) { i =>
val mod = i % n
if (i + (n - 1) - mod >= 0) unit(mod) else nonNegativeLessThan(n)
}
}
def _map[A, B](s: Rand[A])(f: A => B): Rand[B] =
flatMap(s)(a => unit(f(a)))
def _map2[A, B, C](ra: Rand[A], rb: Rand[B])(f: (A, B) => C): Rand[C] =
flatMap(ra)(a => map(rb)(b => f(a, b)))
}
case class State[S, +A](run: S => (A, S)) {
def map[B](f: A => B): State[S, B] =
flatMap(a => State.unit(f(a)))
def map2[B, C](sb: State[S, B])(f: (A, B) => C): State[S, C] =
flatMap(a => sb.map(b => f(a, b)))
def flatMap[B](f: A => State[S, B]): State[S, B] = State(s => {
val (a, s1) = run(s)
f(a).run(s1)
})
}
object State {
type Rand[A] = State[RNG, A]
def unit[S, A](a: A): State[S, A] =
State(s => (a, s))
// The idiomatic solution is expressed via foldRight
def sequenceViaFoldRight[S, A](sas: List[State[S, A]]): State[S, List[A]] =
sas.foldRight(unit[S, List[A]](List()))((f, acc) => f.map2(acc)(_ :: _))
// This implementation uses a loop internally and is the same recursion
// pattern as a left fold. It is quite common with left folds to build
// up a list in reverse order, then reverse it at the end.
// (We could also use a collection.mutable.ListBuffer internally.)
def sequence[S, A](sas: List[State[S, A]]): State[S, List[A]] = {
def go(s: S, actions: List[State[S, A]], acc: List[A]): (List[A], S) =
actions match {
case Nil => (acc.reverse, s)
case h :: t => h.run(s) match {
case (a, s2) => go(s2, t, a :: acc)
}
}
State((s: S) => go(s, sas, List()))
}
// We can also write the loop using a left fold. This is tail recursive like the
// previous solution, but it reverses the list _before_ folding it instead of after.
// You might think that this is slower than the `foldRight` solution since it
// walks over the list twice, but it's actually faster! The `foldRight` solution
// technically has to also walk the list twice, since it has to unravel the call
// stack, not being tail recursive. And the call stack will be as tall as the list
// is long.
def sequenceViaFoldLeft[S, A](l: List[State[S, A]]): State[S, List[A]] =
l.reverse.foldLeft(unit[S, List[A]](List()))((acc, f) => f.map2(acc)(_ :: _))
def modify[S](f: S => S): State[S, Unit] = for {
s <- get // Gets the current state and assigns it to `s`.
_ <- set(f(s)) // Sets the new state to `f` applied to `s`.
} yield ()
def get[S]: State[S, S] = State(s => (s, s))
def set[S](s: S): State[S, Unit] = State(_ => ((), s))
}
case class Gen[+A](sample: State[RNG, A]) {
//8.6
def flatMap[B](f: A => Gen[B]): Gen[B] = Gen(sample.flatMap(f.andThen(_.sample)))
def map[B](f: A => B): Gen[B] = ???
def listOfN(size: Gen[Int]): Gen[List[A]] = size.flatMap(sz => Gen.listOfN(sz, this))
//8.10
def unsized: SGen[A] = SGen(_ => this)
def **[B](g: Gen[B]): Gen[(A, B)] = ??? // (this map2 g)((_,_))
}
object Gen {
//8.4
def choose(start: Int, stopExclusive: Int): Gen[Int] = {
val r = RNG.nonNegativeLessThan(stopExclusive - start)
val rr = RNG.map(r)(_ + start)
Gen(State(rr))
}
//8.5
def unit[A](a: => A): Gen[A] = Gen(State.unit(a))
def boolean: Gen[Boolean] = Gen(State(RNG.boolean))
def listOfN[A](n: Int, g: Gen[A]): Gen[List[A]] = {
val s: Rand[A] = g.sample.run
val list: List[Rand[A]] = List.fill(n)(s)
Gen(State(sequence(list)))
}
//8.7
def union[A](g1: Gen[A], g2: Gen[A]): Gen[A] = Gen.boolean.flatMap(b => if (b) g1 else g2)
//8.8
def weighted[A](g1: (Gen[A], Double), g2: (Gen[A], Double)): Gen[A] =
Gen(State(RNG.double)).flatMap(d => if (d * ((g1._2 + g2._2)) < g1._2) g1._1 else g2._1)
//8.19
def fn[A, B](n: Int, a: Gen[A], b: Gen[B]): Gen[A => B] = {
val gas = listOfN(n, a)
val gbs = listOfN(n, b)
for {
as <- gas
bs <- gbs
d <- b
} yield as.zip(bs).toMap.withDefault(_ => d)
}
}
object Prop {
type SuccessCount = Int
type TestCases = Int
type MaxSize = Int
type FailedCase = String
sealed trait Result {
def isFalsified: Boolean
}
case object Passed extends Result {
def isFalsified = false
}
case class Falsified(failure: FailedCase,
successes: SuccessCount) extends Result {
def isFalsified = true
}
/* Produce an infinite random stream from a `Gen` and a starting `RNG`. */
/* def randomStream[A](g: Gen[A])(rng: RNG): Stream[A] =
Stream.unfold(rng)(rng => Some(g.sample.run(rng)))*/
def forAll[A](as: Gen[A])(f: A => Boolean): Prop = ???
//8.15 - replace random stream with stream of all cases e.g. with implicit transformation
/* Prop {
(n,rng) => randomStream(as)(rng).zip(Stream.from(0)).take(n).map {
case (a, i) => try {
if (f(a)) Passed else Falsified(a.toString, i)
} catch { case e: Exception => Falsified(buildMsg(a, e), i) }
}.find(_.isFalsified).getOrElse(Passed)
}*/
def forAllPar[A](g: Gen[A])(f: A => Par[Boolean]): Prop = ???
// String interpolation syntax. A string starting with `s"` can refer to
// a Scala value `v` as `$v` or `${v}` in the string.
// This will be expanded to `v.toString` by the Scala compiler.
def buildMsg[A](s: A, e: Exception): String =
s"test case: $s\n" +
s"generated an exception: ${e.getMessage}\n" +
s"stack trace:\n ${e.getStackTrace.mkString("\n")}"
}
case class Prop(run: (Prop.TestCases, RNG) => Prop.Result) {
//8.9
def &&(p: Prop): Prop = Prop { (n, rng) =>
val r = run(n, rng)
val pr = p.run(n, rng)
(r, pr) match {
case (Prop.Passed, Prop.Passed) => Prop.Passed
case (f: Prop.Falsified, _) => f
case (_, f: Prop.Falsified) => f
}
}
def ||(p: Prop): Prop = Prop { (n, rng) =>
val r = run(n, rng)
val pr = p.run(n, rng)
(r, pr) match {
case (f: Prop.Falsified, pf: Prop.Falsified) => f
case _ => Prop.Passed
}
}
}
object SGen {
//8.12
def listOfN[A](g: Gen[A]): SGen[List[A]] = SGen(n => Gen.listOfN(n, g))
//8.13
def listOf1[A](g: Gen[A]): SGen[List[A]] = SGen(n => Gen.listOfN(n + 1, g))
private def fork[A](n: Int, g: Gen[Par[A]]): Gen[Par[A]] = if (n == 0) g else fork(n - 1, g.map(Par.fork(_)))
//8.16
def deepPar[A](g: Gen[A]): SGen[Par[A]] = SGen(n => fork(n, g.map(Par.unit(_))))
//8.11
def union[A](g1: SGen[A], g2: SGen[A]): SGen[A] = SGen(n => Gen.union(g1.forSize(n), g2.forSize(n)))
}
case class SGen[+A](forSize: Int => Gen[A]) {
//8.11
def flatMap[B](f: A => SGen[B]): SGen[B] =
SGen(n => forSize(n).flatMap(a => f(a).forSize(n)))
}
//8.14
val intList = Gen.listOfN(100, Gen.choose(0, 100))
val prop = Prop.forAll(intList) { ns =>
val s = ns.sorted
s.zip(s.tail).forall(p => p._1 > p._2)
}
def equal[A](p: Par[A], p2: Par[A]): Par[Boolean] = Par.map2(p, p2)(_ == _)
val pint = Gen.choose(0, 10) map (Par.unit(_))
val pint2: Gen[Par[Int]] = Gen.choose(-100, 100).listOfN(Gen.choose(0, 20)).map(l =>
l.foldLeft(Par.unit(0))((p, i) =>
Par.fork {
Par.map2(p, Par.unit(i))(_ + _)
}))
val p4 =
Prop.forAllPar(pint)(n => equal(Par.map(n)(y => y), n))
//8.17
val p5 =
Prop.forAllPar(pint)(x => equal(Par.fork(x), x))
//8.18
val isEven = (i: Int) => i % 2 == 0
val takeWhileProp =
Prop.forAll(Gen.listOfN(100, Gen.choose(0, 100)))(ns => ns.takeWhile(isEven).forall(isEven))
val takeWhileProp2 =
Prop.forAll(Gen.listOfN(100, Gen.choose(0, 100))) { ns =>
val dw = ns.dropWhile(isEven)
val tw = ns.takeWhile(isEven)
dw ::: tw == ns
}
//8.19
def genStringFn[A](g: Gen[A]): Gen[String => A] = Gen {
State { (rng: RNG) =>
val (seed, rng2) = rng.nextInt
val f = (s: String) => g.sample.run(RNG.Simple(seed.toLong ^ s.hashCode.toLong))._1
(f, rng2)
}
}
trait Cogen[-A] {
def sample(a: A, rng: RNG): RNG
}
class HashCogen[-A] extends Cogen[A] {
def sample(a: A, rng: RNG): RNG = {
val (seed, _) = rng.nextInt
RNG.Simple(seed.toLong ^ a.hashCode.toLong)
}
}
def fn[A, B](in: Cogen[A])(out: Gen[B]): Gen[A => B] = Gen {
State { (rng: RNG) =>
val f = (a: A) => out.sample.run(in.sample(a, rng))._1
val (_, rng2) = rng.nextInt
(f, rng2)
}
}
//8.20
val cg: Cogen[Int] = ???
val gp: Gen[Int => Boolean] = fn(cg)(Gen.boolean)
val gl = Gen.listOfN(100, Gen.choose(0, 100))
val filterProp =
Prop.forAll(gp ** gl) { case (p, l) => l.filter(p).forall(!p(_)) }
}
|
kharole/fpinscala
|
answers/src/main/scala/fpinscala/monads/fp11.scala
|
<filename>answers/src/main/scala/fpinscala/monads/fp11.scala<gh_stars>0
package fpinscala.monads
import fpinscala.datastructures
import fpinscala.laziness.Stream
import fpinscala.monads.fp11.Reader
import fpinscala.parallelism.Nonblocking.Par
import fpinscala.parsing.Sliceable
import fpinscala.parsing.SliceableTypes.Parser
import fpinscala.state.State
object fp11 {
trait Monad[F[_]] extends Functor[F] {
def unit[A](a: => A): F[A]
def flatMap[A, B](ma: F[A])(f: A => F[B]): F[B]
def map[A, B](ma: F[A])(f: A => B): F[B] =
flatMap(ma)(a => unit(f(a)))
def map2[A, B, C](ma: F[A], mb: F[B])(f: (A, B) => C): F[C] =
flatMap(ma)(a => map(mb)(b => f(a, b)))
//11.3
def sequence[A](lma: List[F[A]]): F[List[A]] = {
val z = unit(List[A]())
lma.foldLeft(z)((s, e) => map2(e, s)(_ :: _))
}
/*
lma match {
case head :: tail => flatMap(head)(h => map(sequence(tail))(t => h :: t))
case Nil =>
}
*/
def traverse[A, B](la: List[A])(f: A => F[B]): F[List[B]] = sequence(la.map(f))
//11.4
def replicateM[A](n: Int, ma: F[A]): F[List[A]] = sequence(List.fill(n)(ma))
def product[A, B](ma: F[A], mb: F[B]): F[(A, B)] = map2(ma, mb)((_, _))
//11.6
def filterM[A](ms: List[A])(f: A => F[Boolean]): F[List[A]] = ms match {
case head :: tail => flatMap(f(head)) { b =>
if (b) {
map(filterM(tail)(f))(t => head :: t)
} else {
filterM(tail)(f)
}
}
case Nil => unit(Nil)
}
//11.7
def compose[A, B, C](f: A => F[B], g: B => F[C]): A => F[C] = a => flatMap(f(a))(g(_))
//11.8
def flatMap2[A, B](ma: F[A])(f: A => F[B]): F[B] = {
val u: Unit => F[A] = _ => ma
val ff: Unit => F[B] = compose(u, f)
ff(())
}
//11.9
/*
x.flatMap(f).flatMap(g) == x.flatMap(a => f(a).flatMap(g))
flatMap(flatMap(x)(f))(g) == flatMap(x)(a => flatMap(f(a))(g))
compose(compose(f, g), h) == compose(f, compose(g, h))
x => flatMap(compose(f, g)(x))(h)
x => flatMap(flatMap(f(x))(g)(h)
--
x => flatMap(f(x))(compose(g, h))
x => flatMap(f(x))(a => flatMap(g(a))(h))
*/
//11.10
/*
compose(f, unit) == f
x => flatMap(f(x))(unit)
flatMap(x)(unit) == x
compose(unit, f) == f
y => flatMap(unit(y))(f)
flatMap(unit(y))(f) == f(y)
*/
//11.11
/*
Some(v).flatMap(unit) == Some(v)
None.flatMap(unit) == None
*/
//11.12
def join[A](mma: F[F[A]]): F[A] = flatMap(mma)(identity)
//11.13
def flatMap3[A, B](ma: F[A])(f: A => F[B]): F[B] = join(map(ma)(f))
//11.14
/*
flatMap(x)(unit) == x
join(map(x)(unit)) == x
flatMap(unit(y))(f) == f(y)
join(map(unit(y))(f)) == f(y)
*/
//11.15
/*
Regardless if u flatMap sequentially to f then to g or flatMap par computation to f flatMap g callback receives same result
a followed by (b followed by c) is same parser as (a followed by b) followed by c
*/
//11.16
/*
Gen flatMapped to unit produce same value as original Gen
List flatMapped to unit first wrap each element to a single element list then unwrap in back
*/
//12.11
def compose[G[_]](G: Monad[G]): Monad[({type f[x] = F[G[x]]})#f] = new Monad[({type f[x] = F[G[x]]})#f] {
override def unit[A](a: => A): F[G[A]] =
Monad.this.unit(G.unit(a))
override def flatMap[A, B](ma: F[G[A]])(f: A => F[G[B]]): F[G[B]] =
???
//Monad.this.flatMap(na => G.flatMap(na)(a => ???))
}
}
//11.1
val parMonad = new Monad[Par] {
override def unit[A](a: => A): Par[A] = Par.unit(a)
override def flatMap[A, B](ma: Par[A])(f: A => Par[B]): Par[B] = Par.flatMap(ma)(f)
}
val parserMonad = new Monad[Parser] {
override def unit[A](a: => A): Parser[A] = Sliceable.succeed(a)
override def flatMap[A, B](ma: Parser[A])(f: A => Parser[B]): Parser[B] = Sliceable.flatMap(ma)(f)
}
val optionMonad = new Monad[Option] {
override def unit[A](a: => A): Option[A] = Some(a)
override def flatMap[A, B](ma: Option[A])(f: A => Option[B]): Option[B] = ma.flatMap(f)
}
val streamMonad = new Monad[Stream] {
override def unit[A](a: => A): Stream[A] = Stream(a)
override def flatMap[A, B](ma: Stream[A])(f: A => Stream[B]): Stream[B] = ma.flatMap(f)
}
val listMonad = new Monad[datastructures.List] {
override def unit[A](a: => A): datastructures.List[A] = datastructures.List(a)
override def flatMap[A, B](ma: datastructures.List[A])(f: A => datastructures.List[B]): datastructures.List[B] = datastructures.List.flatMap(ma)(f)
}
val list2Monad = new Monad[List] {
override def unit[A](a: => A): List[A] = List(a)
override def flatMap[A, B](ma: List[A])(f: A => List[B]): List[B] = ma flatMap f
}
//11.2
class ZState[S] {
type ZS[+A] = State[S, A]
val stateMonad = new Monad[ZS] {
override def unit[A](a: => A): ZS[A] = State.unit(a)
override def flatMap[A, B](ma: State[S, A])(f: A => State[S, B]): State[S, B] = ma.flatMap(f)
}
}
//11.17
case class Id[A](value: A) {
def map[B](f: A => B): Id[B] = Id(f(value))
def flatMap[B](f: A => Id[B]): Id[B] = f(value)
}
val idMonad = new Monad[Id] {
override def unit[A](a: => A): Id[A] = Id(a)
override def flatMap[A, B](ma: Id[A])(f: A => Id[B]): Id[B] = ma flatMap f
}
def stateMonadLambda[S] = new Monad[({type f[x] = State[S, x]})#f] {
def unit[A](a: => A): State[S, A] = State(s => (a, s))
def flatMap[A, B](st: State[S, A])(f: A => State[S, B]): State[S, B] = st flatMap f
}
val F = stateMonadLambda[Int]
def getState[S]: State[S, S] = State(s => (s, s))
def setState[S](s: S): State[S, Unit] = State(_ => ((), s))
def zipWithIndex[A](as: List[A]): List[(Int, A)] = as.foldLeft(F.unit(List[(Int, A)]()))((acc, a) => for {
xs <- acc
n <- getState
_ <- setState(n + 1)
} yield (n, a) :: xs).run(0)._1.reverse
//11.18
// sequence - transform list of states to a state of list
//replicateM - repeat an element n times inside that state
// map2 - join two states into one merging corresponding values with function
//11.19
//What laws do you expect to mutually hold for getState, setState, unit, and flatMap?
val law1 = for {
_ <- setState(42)
n <- getState
} yield n
val law2: State[Unit, Unit] = for {
n <- getState
_ <- setState(n)
} yield ()
//11.20
case class Reader[R, A](run: R => A)
object Reader {
def readerMonad[R] = new Monad[({type f[x] = Reader[R, x]})#f] {
def unit[A](a: => A): Reader[R, A] =
Reader(_ => a)
def flatMap[A, B](st: Reader[R, A])(f: A => Reader[R, B]): Reader[R, B] =
Reader((r: R) => (st.run andThen f) (r).run(r))
}
}
}
object MonoadsApp extends App {
//11.5 Cartesian product
val is = List(1, 2)
println(fp11.list2Monad.replicateM(2, is))
val os = Some(true)
println(fp11.optionMonad.replicateM(3, os))
val irm = fp11.Reader.readerMonad[Int]
val iir1: fp11.Reader[Int, Int] = fp11.Reader(_ + 1)
val iir2: fp11.Reader[Int, Int] = fp11.Reader(_ + 2)
val isr: fp11.Reader[Int, fp11.Reader[Int, String]] = fp11.Reader(i => fp11.Reader(ii => (ii + i).toString))
//join - chaining incoming param to nested reader
println(irm.join(isr).run(7))
//replicateM - build list of n times reader runs
println(irm.replicateM(7, iir1).run(5))
//sequence - builds reader that given a param apply it to original readers and gathers the results to list
println(irm.sequence(List(iir1, iir2)).run(5))
}
|
kharole/fpinscala
|
answers/src/main/scala/fpinscala/localeffects/fp14.scala
|
package fpinscala.localeffects
import scala.annotation.tailrec
object fp14 {
sealed trait ST[S, A] {
self =>
protected def run(s: S): (A, S)
def map[B](f: A => B): ST[S, B] = new ST[S, B] {
def run(s: S) = {
val (a, s1) = self.run(s)
(f(a), s1)
}
}
def flatMap[B](f: A => ST[S, B]): ST[S, B] = new ST[S, B] {
def run(s: S) = {
val (a, s1) = self.run(s)
f(a).run(s1)
}
}
}
object ST {
def runST[A](st: RunnableST[A]): A =
st.apply[Unit].run(())._1
def apply[S, A](a: => A) = {
lazy val memo = a
new ST[S, A] {
def run(s: S) = (memo, s)
}
}
}
sealed trait STRef[S, A] {
protected var cell: A
def read: ST[S, A] = ST(cell)
def write(a: A): ST[S, Unit] = new ST[S, Unit] {
def run(s: S) = {
cell = a
((), s)
}
}
}
object STRef {
def apply[S, A](a: A): ST[S, STRef[S, A]] = ST(new STRef[S, A] {
var cell = a
})
}
sealed abstract class STArray[S, A](implicit manifest: Manifest[A]) {
protected def value: Array[A]
def size: ST[S, Int] = ST(value.size)
def write(i: Int, a: A): ST[S, Unit] = new ST[S, Unit] {
def run(s: S) = {
value(i) = a
((), s)
}
}
private def get: ST[S, Array[A]] = ST(value)
def read(i: Int): ST[S, A] = ST(value(i))
def freeze: ST[S, List[A]] = ST(value.toList)
def fill(xs: Map[Int, A]): ST[S, Unit] =
xs.foldLeft(ST[S, Unit](()))((a, e) => a.flatMap(_ => write(e._1, e._2)))
}
object STArray {
def apply[S, A: Manifest](sz: Int, v: A): ST[S, STArray[S, A]] =
ST(new STArray[S, A] {
lazy val value = Array.fill(sz)(v)
})
}
trait RunnableST[A] {
def apply[S]: ST[S, A]
}
def main(args: Array[String]): Unit = {
println("Hello ST")
val p = new RunnableST[(Int, Int)] {
def apply[S] = for {
r1 <- STRef(1)
r2 <- STRef(2)
x <- r1.read
y <- r2.read
_ <- r1.write(y + 1)
_ <- r2.write(x + 1)
a <- r1.read
b <- r2.read} yield (a, b)
}
val zz = new RunnableST[List[String]] {
override def apply[S]: ST[S, List[String]] = {
for {
a <- STArray[S, String](5, "a")
_ <- a.fill(Map(1 -> "1", 2 -> "2"))
f <- a.freeze
} yield f
}
}
println(ST.runST(zz))
}
}
|
kharole/fpinscala
|
answers/src/main/scala/fpinscala/applicative/fp12.scala
|
<reponame>kharole/fpinscala
package fpinscala.applicative
import fpinscala.monads.{Functor, fp11}
import fpinscala.monoids.fp10
import fpinscala.state.State
object fp12 {
//noinspection DuplicatedCode
//12.1
trait Applicative[F[_]] extends Functor[F] {
// primitive combinators
def map2[A, B, C](fa: F[A], fb: F[B])(f: (A, B) => C): F[C]
def unit[A](a: => A): F[A]
// derived combinators
def map[A, B](fa: F[A])(f: A => B): F[B] =
map2(fa, unit(()))((a, _) => f(a))
def sequence[A](lma: List[F[A]]): F[List[A]] =
lma.foldRight(unit(List[A]()))((ma, mla) => map2(ma, mla)(_ :: _))
def traverse[A, B](as: List[A])(f: A => F[B]): F[List[B]] =
as.foldRight(unit(List[B]()))((a, fbs) => map2(f(a), fbs)(_ :: _))
//12.12
def sequenceMap[K, V](ofa: Map[K, F[V]]): F[Map[K, V]] =
ofa.foldRight(unit(Map[K, V]()))((e, acc) => map2(e._2, acc)((x, y) => y.updated(e._1, x)))
// Using `sequence` and the `List.fill` function of the standard library:
def replicateM[A](n: Int, ma: F[A]): F[List[A]] =
sequence(List.fill(n)(ma))
def product[A, B](fa: F[A], fb: F[B]): F[(A, B)] =
map2(fa, fb)((a, b) => (a, b))
//12.8
def product[G[_]](G: Applicative[G]): Applicative[({type f[x] = (F[x], G[x])})#f] =
new Applicative[({type f[x] = (F[x], G[x])})#f] {
override def unit[A](a: => A): (F[A], G[A]) =
(Applicative.this.unit(a), G.unit(a))
override def map2[A, B, C](fa: (F[A], G[A]), fb: (F[B], G[B]))(f: (A, B) => C): (F[C], G[C]) =
(Applicative.this.map2(fa._1, fb._1)(f), G.map2(fa._2, fb._2)(f))
}
//12.9
def compose[G[_]](G: Applicative[G]): Applicative[({type f[x] = F[G[x]]})#f] =
new Applicative[({type f[x] = F[G[x]]})#f] {
override def unit[A](a: => A): F[G[A]] =
Applicative.this.unit(G.unit(a))
override def map2[A, B, C](fa: F[G[A]], fb: F[G[B]])(f: (A, B) => C): F[G[C]] =
Applicative.this.map2(fa, fb)((ga, gb) => G.map2(ga, gb)(f))
}
trait Traverse[F[_]] { self =>
def traverse[G[_] : Applicative, A, B](fa: F[A])(f: A => G[B]): G[F[B]] =
???
def sequence[G[_] : Applicative, A](fga: F[G[A]]): G[F[A]]
case class Id[A](value: A)
implicit val id = new Applicative[Id] {
override def unit[A](a: => A): Id[A] = Id(a)
override def map2[A, B, C](fa: Id[A], fb: Id[B])(f: (A, B) => C): Id[C] = Id(f(fa.value, fb.value))
}
//12.14
def map[A, B](fa: F[A])(f: A => B): F[B] = traverse(fa)(a => Id(f(a))).value
def traverseS[S, A, B](fa: F[A])(f: A => State[S, B]): State[S, F[B]] =
traverse[({type f[x] = State[S, x]})#f, A, B](fa)(f)(stateMonad)
def mapAccum[S, A, B](fa: F[A], s: S)(f: (A, S) => (B, S)): (F[B], S) =
traverseS(fa)((a: A) => for {
s1 <- State.get[S]
(b, s2) = f(a, s1)
_ <- State.set(s2)
} yield b).run(s)
def toList[A](fa: F[A]): List[A] =
mapAccum(fa, List[A]())((a, as) => ((), a :: as))._2.reverse
def zipWithIndex[A](fa: F[A]): F[(A, Int)] = {
mapAccum(fa, 0)((a, i) => ((a, i), i + 1))._1
}
//12.16
def reverse[A](fa: F[A]): F[A] = {
mapAccum(fa, toList(fa).reverse)((_, s) => (s.head, s.tail))._1
}
//12.17
def foldLeft[A, B](fa: F[A], z: B)(op: (B, A) => B): B =
mapAccum(fa, z)((a, s) => ((), op(s, a)))._2
//12.18
def fuse[G[_], H[_], A, B](fa: F[A])(f: A => G[B], g: A => H[B])
(G: Applicative[G], H: Applicative[H]): (G[F[B]], H[F[B]]) = {
traverse[({type f[x] = (G[x], H[x])})#f, A, B](fa)(a => (f(a), g(a)))(G product H)
}
//12.19
def compose[Z[_]](implicit Z: Traverse[Z]): Traverse[({type f[x] = F[Z[x]]})#f] =
new Traverse[({type f[x] = F[Z[x]]})#f] {
override def traverse[G[_] : Applicative, A, B](fa: F[Z[A]])(f: A => G[B]): G[F[Z[B]]] =
self.traverse(fa)((ga: Z[A]) => Z.traverse(ga)(f))
override def sequence[G[_] : Applicative, A](fga: F[Z[G[A]]]): G[F[Z[A]]] = ???
}
//12.20 skip
}
def stateMonad[S] = new Applicative[({type f[x] = State[S, x]})#f] {
def unit[A](a: => A): State[S, A] = State(s => (a, s))
def map2[A, B, C](sta: State[S, A], stb: State[S, B])(f: (A, B) => C): State[S, C] =
sta.map2(stb)(f)
}
//12.13
val listTraverse = new Traverse[List] {
override def sequence[G[_] : Applicative, A](fga: List[G[A]]): G[List[A]] = {
val ag = implicitly[Applicative[G]]
fga.foldLeft(ag.unit(List[A]()))((acc, ga) => ag.map2(ga, acc)(_ :: _))
}
}
val optionTraverse = new Traverse[Option] {
override def sequence[G[_] : Applicative, A](fga: Option[G[A]]): G[Option[A]] = {
fga match {
case Some(ga) => implicitly[Applicative[G]].map(ga)(Some(_))
case None => implicitly[Applicative[G]].unit(None)
}
}
}
case class Tree[+A](head: A, tail: List[Tree[A]])
val treeTraverse = new Traverse[Tree] {
override def sequence[G[_] : Applicative, A](fga: Tree[G[A]]): G[Tree[A]] = {
val ag = implicitly[Applicative[G]]
val head: G[A] = fga.head
val tail: G[List[Tree[A]]] = listTraverse.sequence(fga.tail.map(sequence(_)))
ag.map2(head, tail)(Tree(_, _))
}
}
//12.2
trait Applicative2[F[_]] extends Functor[F] {
def apply[A, B](fab: F[A => B])(fa: F[A]): F[B] =
map2(fab, fa)((a2b, a) => a2b(a))
def unit[A](a: => A): F[A]
def map[A, B](fa: F[A])(f: A => B): F[B] =
apply(unit(f))(fa)
def map2[A, B, C](fa: F[A], fb: F[B])(f: (A, B) => C): F[C] =
map(apply(map(fa)(a => (b: B) => (a, b)))(fb))(f.tupled)
//12.3
def map3[A, B, C, D](fa: F[A], fb: F[B], fc: F[C])(f: (A, B, C) => D): F[D] =
apply(apply(map(fa)(f.curried))(fb))(fc)
def map4[A, B, C, D, E](fa: F[A], fb: F[B], fc: F[C], fd: F[D])(f: (A, B, C, D) => E): F[E] =
apply(apply(apply(map(fa)(f.curried))(fb))(fc))(fd)
}
}
object ApplicativeApp extends App {
//12.15
case class Iteration[A](a: A, f: A => A, n: Int) {
def foldMap[B](g: A => B)(M: fp10.Monoid[B]): B = {
def iterate(n: Int, b: B, c: A): B =
if (n <= 0) b else iterate(n - 1, g(c), f(a))
iterate(n, M.zero, a)
}
}
def goodStrings(elements: List[String], len: Int): List[String] = {
if (len == 0) {
List()
} else {
goodStrings(elements, len - 1)
}
}
println("==========")
println(goodStrings(List("a", "b", "c"), 2))
//println((0 to 25).sum)
//12.4 zip streams of incoming list to a stream of list of values of corresponding streams
def sequence[A](a: List[Stream[A]]): Stream[List[A]] = ???
//12.5
object EitherM {
def eitherMonad[E]: fp11.Monad[({type f[x] = Either[E, x]})#f] = new fp11.Monad[({type f[x] = Either[E, x]})#f] {
def unit[A](a: => A): Either[E, A] =
Right(a)
def flatMap[A, B](e: Either[E, A])(f: A => Either[E, B]): Either[E, B] =
e match {
case Left(value) => Left(value)
case Right(value) => f(value)
}
}
}
sealed trait Validation[+E, +A]
case class Failure[E](head: E, tail: Vector[E] = Vector())
extends Validation[E, Nothing]
case class Success[A](a: A) extends Validation[Nothing, A]
//12.6
object ValidationM {
def validationApplicative[E]: fp12.Applicative[({type f[x] = Validation[E, x]})#f] =
new fp12.Applicative[({type f[x] = Validation[E, x]})#f] {
def unit[A](a: => A): Validation[E, A] =
Success(a)
override def map2[A, B, C](va: Validation[E, A], vb: Validation[E, B])(f: (A, B) => C): Validation[E, C] =
(va, vb) match {
case (Success(a), Success(b)) => Success(f(a, b))
case (Success(_), Failure(h, t)) => Failure(h, t)
case (Failure(h, t), Success(_)) => Failure(h, t)
case (Failure(h1, t1), Failure(h2, t2)) => Failure(h1, (t1 ++ t2) :+ h2)
}
}
}
def assoc[A, B, C](p: (A, (B, C))): ((A, B), C) =
p match {
case (a, (b, c)) => ((a, b), c)
}
//12.7
/*
monadic:
associative
x.flatMap(f).flatMap(g) == x.flatMap(a => f(a).flatMap(g))
identity:
flatMap(x)(unit) == x
flatMap(unit(y))(f) == f(y)
def map2[A,B,C](fa: F[A], fb: F[B])(f: (A, B) => C): F[C] = flatMap(fa)(a => map(fb)(b => f(a,b)))
applicative:
//left right identity
map(v)(id) == v map(map(v)(g))(f) == map(v)(f compose g)
map2(unit(()), fa)((_,a) => a) == fa
flatMap(unit(())(u => map(fa)((_,a) => a))
(u => map(fa)((_,a) => a))(())
fa
map2(fa, unit(()))((a,_) => a) == fa
op(a, op(b, c)) == op(op(a, b), c)
compose(f, op(g, h)) == compose(compose(f, g), h)
//associativity
product(product(fa,fb),fc) == map(product(fa, product(fb,fc)))(assoc)
//associativity
map2(a,b)(productF(f,g)) == product(map(a)(f), map(b)(g))
*/
//12.10
/*
several days or even a few weeks to think about
life is too short
*/
}
}
|
kharole/fpinscala
|
answers/src/main/scala/fpinscala/monoids/fp10.scala
|
package fpinscala.monoids
import fp10._
import fpinscala.parallelism.Nonblocking.Par
import fpinscala.testing.Gen.listOfN
import fpinscala.testing.Prop.forAll
import fpinscala.testing.{Gen, Prop}
object fp10 {
trait Monoid[A] {
def op(a1: A, a2: A): A
def zero: A
}
//10.1
val intAddition: Monoid[Int] = new Monoid[Int] {
override def op(a1: Int, a2: Int) = a1 + a2
override def zero = 0
}
val stringConcatenation: Monoid[String] = new Monoid[String] {
override def op(a1: String, a2: String) = a1 + a2
override def zero = ""
}
val intMultiplication: Monoid[Int] = new Monoid[Int] {
override def op(a1: Int, a2: Int) = a1 * a2
override def zero = 1
}
val booleanOr: Monoid[Boolean] = new Monoid[Boolean] {
override def op(a1: Boolean, a2: Boolean) = a1 || a2
override def zero = false
}
val booleanAnd: Monoid[Boolean] = new Monoid[Boolean] {
override def op(a1: Boolean, a2: Boolean) = a1 && a2
override def zero = true
}
//10.2
def optionMonoid[A]: Monoid[Option[A]] = new Monoid[Option[A]] {
override def op(a1: Option[A], a2: Option[A]): Option[A] = (a1, a2) match {
case (None, None) => None
case (Some(aa1), None) => Some(aa1)
case (None, Some(aa2)) => Some(aa2)
case (Some(aa1), Some(_)) => Some(aa1)
}
override def zero = None
}
//10.3
def endoMonoid[A]: Monoid[A => A] = new Monoid[A => A] {
override def op(a1: A => A, a2: A => A): A => A = a1.andThen(a2)
override def zero: A => A = identity
}
//10.4
def monoidLaws[A](m: Monoid[A], gen: Gen[A]): Prop =
forAll(gen)(a => m.op(a, m.zero) == a) &&
forAll(listOfN(3, gen)) { case x :: y :: z :: Nil => m.op(m.op(x, y), z) == m.op(x, m.op(y, z)) }
//10.5
def foldMap[A, B](as: List[A], m: Monoid[B])(f: A => B): B = as.foldRight(m.zero)((a, s) => m.op(s, f(a)))
//10.6
def foldRight[A, B](as: List[A], z: B)(ff: (A, B) => B): B = {
val f = (a: A) => (b: B) => ff(a, b)
val mf: B => B = foldMap(as, endoMonoid[B])(f)
mf(z)
}
//10.7
def foldMapV[A, B](v: IndexedSeq[A], m: Monoid[B])(f: A => B): B = v.size match {
case 0 =>
m.zero
case 1 =>
f(v.head)
case _ =>
val (v1, v2) = v.splitAt(v.size / 2)
val b1: B = foldMapV(v1, m)(f)
val b2: B = foldMapV(v2, m)(f)
m.op(b1, b2)
}
//10.8
import fpinscala.parallelism.Nonblocking.Par.toParOps
import fpinscala.parallelism.Nonblocking._
def par[A](m: Monoid[A]): Monoid[Par[A]] = new Monoid[Par[A]] {
override def op(pa1: Par[A], pa2: Par[A]): Par[A] = Par.map2(pa1, pa2)(m.op)
override def zero: Par[A] = Par.unit(m.zero)
}
def parFoldMap[A, B](as: IndexedSeq[A], m: Monoid[B])(f: A => B): Par[B] =
Par.parMap(as)(f).flatMap { bs =>
foldMapV(bs, par(m))(b => Par.lazyUnit(b))
}
//10.9
sealed trait Segment
case object ZeroSegment extends Segment
case class OrderedSegment(left: Int, right: Int) extends Segment
case object UnorderedSegment extends Segment
val segmentMerge: Monoid[Segment] = new Monoid[Segment] {
override def op(s1: Segment, s2: Segment): Segment = (s1, s2) match {
case (_, UnorderedSegment) => UnorderedSegment
case (UnorderedSegment, _) => UnorderedSegment
case (ZeroSegment, s) => s
case (s, ZeroSegment) => s
case (OrderedSegment(l1, r1), OrderedSegment(l2, r2)) if r1 <= l2 => OrderedSegment(l1, r2)
case (OrderedSegment(_, r1), OrderedSegment(l2, _)) if r1 > l2 => UnorderedSegment
case _ => throw new IllegalStateException
}
override def zero: Segment = ZeroSegment
}
object WC {
def apply(chars: String): WC = {
val a = chars.split("\\s+")
a.size match {
case 1 | 2 => Stub(chars)
case _ => Part(a(0), a.size - 2, a(a.size - 1))
}
}
}
sealed trait WC {
def count: Int = this match {
case Stub(chars) =>
chars.split("\\s+").size
case Part(lStub, words, rStub) =>
val l = if (lStub.isEmpty) 0 else 1
val r = if (rStub.isEmpty) 0 else 1
l + words + r
}
}
case class Stub(chars: String) extends WC
case class Part(lStub: String, words: Int, rStub: String) extends WC {
def simplifyRight: Part = {
val a = rStub.split("\\s+")
a.size match {
case 1 => this
case 2 => Part(lStub, words + 1, a(1))
case _ => throw new IllegalStateException()
}
}
def simplifyLeft: Part = {
val a = lStub.split("\\s+")
a.size match {
case 1 => this
case 2 => Part(a(0), words + 1, rStub)
case _ => throw new IllegalStateException()
}
}
}
//10.10
val wcMonoid: Monoid[WC] = new Monoid[WC] {
override def op(wc1: WC, wc2: WC): WC = (wc1, wc2) match {
case (Stub(cs1), Stub(cs2)) => WC(cs1 + cs2)
case (Part(ls1, w1, rs1), Stub(c2)) => Part(ls1, w1, rs1 + c2).simplifyRight
case (Stub(c1), Part(ls2, w2, rs2)) => Part(c1 + ls2, w2, rs2).simplifyLeft
case (Part(ls1, w1, ""), Part("", w2, rs2)) => Part(ls1, w1 + w2, rs2)
case (Part(ls1, w1, _), Part(_, w2, rs2)) => Part(ls1, w1 + w2 + 1, rs2)
}
override def zero: WC = Stub("")
}
//10.11
def wordCount(s: String): Int = {
val wcs = rwc(s)
val wc = foldMapV(wcs, wcMonoid)(identity)
wc.count
}
def rwc(s: String): Vector[WC] = {
if (s.size > 3) {
val (s1, s2) = s.splitAt(s.size / 2)
rwc(s1) ++ rwc(s2)
} else {
Vector(WC(s))
}
}
trait Foldable[F[_]] {
def foldRight[A, B](as: F[A])(z: B)(f: (A, B) => B): B
def foldLeft[A, B](as: F[A])(z: B)(f: (B, A) => B): B
def foldMap[A, B](as: F[A])(f: A => B)(mb: Monoid[B]): B
def concatenate[A](as: F[A])(m: Monoid[A]): A = foldLeft(as)(m.zero)(m.op)
//10.15
def toList[A](as: F[A]): List[A] = foldLeft(as)(List[A]())((acc, a) => a :: acc)
}
//10.12
val foldableList = new Foldable[List] {
override def foldLeft[A, B](as: List[A])(z: B)(f: (B, A) => B): B = as match {
case head :: tail => f(foldLeft(tail)(z)(f), head)
case Nil => z
}
override def foldRight[A, B](as: List[A])(z: B)(f: (A, B) => B): B = as match {
case head :: tail => f(head, foldRight(tail)(z)(f))
case Nil => z
}
override def foldMap[A, B](as: List[A])(f: A => B)(mb: Monoid[B]): B =
foldLeft(as)(mb.zero)((b, a) => mb.op(f(a), b))
}
val indexedSeqFoldable = new Foldable[IndexedSeq] {
override def foldLeft[A, B](as: IndexedSeq[A])(z: B)(f: (B, A) => B): B = {
def foldLeftFrom[A, B](as: IndexedSeq[A], idx: Int)(z: B)(f: (B, A) => B): B =
if (idx < as.length)
foldLeftFrom(as, idx + 1)(f(z, as(idx)))(f)
else
z
foldLeftFrom(as, 0)(z)(f)
}
override def foldRight[A, B](as: IndexedSeq[A])(z: B)(f: (A, B) => B): B = {
def foldRightFrom[A, B](as: IndexedSeq[A], idx: Int)(z: B)(f: (A, B) => B): B =
if (idx > 0)
foldRightFrom(as, idx - 1)(f(as(idx), z))(f)
else
z
foldRightFrom(as, as.length)(z)(f)
}
override def foldMap[A, B](as: IndexedSeq[A])(f: A => B)(mb: Monoid[B]): B =
foldLeft(as)(mb.zero)((b, a) => mb.op(f(a), b))
}
val foldableStream = new Foldable[Stream] {
override def foldLeft[A, B](as: Stream[A])(z: B)(f: (B, A) => B): B = as match {
case cons: Stream.Cons[A] => foldLeft(cons.tail)(f(z, cons.head))(f)
case Stream.Empty => z
}
override def foldRight[A, B](as: Stream[A])(z: B)(f: (A, B) => B): B = as match {
case cons: Stream.Cons[A] => f(cons.head, foldRight(cons.tail)(z)(f))
case Stream.Empty => z
}
override def foldMap[A, B](as: Stream[A])(f: A => B)(mb: Monoid[B]): B =
foldLeft(as)(mb.zero)((b, a) => mb.op(f(a), b))
}
sealed trait Tree[+A]
case class Leaf[A](value: A) extends Tree[A]
case class Branch[A](left: Tree[A], right: Tree[A]) extends Tree[A]
//10.13
val foldableTree = new Foldable[Tree] {
override def foldLeft[A, B](t: Tree[A])(z: B)(f: (B, A) => B): B = t match {
case Leaf(value) => f(z, value)
case Branch(left, right) => {
val lz = foldLeft(left)(z)(f)
foldLeft(right)(lz)(f)
}
}
override def foldRight[A, B](t: Tree[A])(z: B)(f: (A, B) => B): B = t match {
case Leaf(value) => f(value, z)
case Branch(left, right) => {
val rz = foldRight(right)(z)(f)
foldRight(left)(rz)(f)
}
}
override def foldMap[A, B](as: Tree[A])(f: A => B)(mb: Monoid[B]): B =
foldLeft(as)(mb.zero)((b, a) => mb.op(f(a), b))
}
//10.14
val foldableOption = new Foldable[Option] {
override def foldRight[A, B](as: Option[A])(z: B)(f: (A, B) => B): B = as match {
case Some(value) => f(value, z)
case None => z
}
override def foldLeft[A, B](as: Option[A])(z: B)(f: (B, A) => B): B = as match {
case Some(value) => f(z, value)
case None => z
}
override def foldMap[A, B](as: Option[A])(f: A => B)(mb: Monoid[B]): B =
foldLeft(as)(mb.zero)((b, a) => mb.op(f(a), b))
}
//10.17
def productMonoid[A, B](A: Monoid[A], B: Monoid[B]): Monoid[(A, B)] = new Monoid[(A, B)] {
override def zero: (A, B) = (A.zero, B.zero)
override def op(a1: (A, B), a2: (A, B)): (A, B) = (A.op(a1._1, a2._1), B.op(a1._2, a2._2))
}
def functionMonoid[A, B](B: Monoid[B]): Monoid[A => B] = new Monoid[A => B] {
override def zero: A => B = _ => B.zero
override def op(a1: A => B, a2: A => B): A => B = (a => B.op(a1(a), a2(a)))
}
def mapMergeMonoid[K, V](V: Monoid[V]): Monoid[Map[K, V]] = new Monoid[Map[K, V]] {
def zero = Map[K, V]()
def op(a: Map[K, V], b: Map[K, V]) =
(a.keySet ++ b.keySet).foldLeft(zero) { (acc, k) =>
acc.updated(k, V.op(a.getOrElse(k, V.zero),
b.getOrElse(k, V.zero)))
}
}
def bagMonoid[A](): Monoid[Map[A, Int]] = new Monoid[Map[A, Int]] {
def zero = Map[A, Int]()
def op(a: Map[A, Int], b: Map[A, Int]) =
(a.keySet ++ b.keySet).foldLeft(zero) { (acc, k) =>
acc.updated(k, a.getOrElse(k, 0) + b.getOrElse(k, 0))
}
}
//10.18
def bag[A](as: IndexedSeq[A]): Map[A, Int] = indexedSeqFoldable.concatenate(as.map(a => Map(a -> 1)))(bagMonoid())
def bag2[A](as: IndexedSeq[A]): Map[A, Int] =
foldMapV(as, mapMergeMonoid[A, Int](intAddition))((a: A) => Map(a -> 1))
}
object MonoidsApp extends App {
val ml = monoidLaws(intAddition, Gen.choose(-1000, 1000))
Prop.run(ml)
println(fp10.foldRight(List(1, 2, 3), "")((i, s) => s + i))
println(fp10.foldMapV(IndexedSeq("lorem", "ipsum", "dolor", "sit"), fp10.stringConcatenation)(identity))
val pool = java.util.concurrent.Executors.newFixedThreadPool(4)
val zz: Par[String] = fp10.parFoldMap(IndexedSeq("lorem", "ipsum", "dolor", "sit"), fp10.stringConcatenation)(identity)
println(Par.run(pool)(zz))
//fp10.foldMapV(IndexedSeq(), fp10.segmentMerge)()
println(fp10.foldMapV(IndexedSeq(1, 2, 5, 100), fp10.segmentMerge)(i => OrderedSegment(i, i)))
println(fp10.foldMapV(IndexedSeq(2, 1, 5, 100), fp10.segmentMerge)(i => OrderedSegment(i, i)))
println(fp10.foldMapV(IndexedSeq(), fp10.segmentMerge)(i => OrderedSegment(i, i)))
pool.shutdown();
println(fp10.wcMonoid.op(Stub("lor"), Stub("em")))
println(fp10.wcMonoid.op(Stub("lor"), Stub("em ip")))
println(fp10.wcMonoid.op(Stub("lor"), Stub("em ipsum do")))
println(fp10.wcMonoid.op(Part("lorem", 1, ""), Part("dolor", 1, "amet")))
println(fp10.wcMonoid.op(Part("lorem", 1, "do"), Stub("lor sit")))
println(fp10.wcMonoid.op(Stub("lor"), Part("em", 1, "do")))
println(fp10.wcMonoid.op(Stub("lorem ip"), Part("sum", 1, "si")))
println(fp10.wordCount("lorem ipsum dolor sit amet "))
}
|
kharole/fpinscala
|
answers/src/main/scala/fpinscala/parsing/fp9.scala
|
import scala.util.matching.Regex
object fp9 {
trait Parsers[ParseError, Parser[+ _]] {
self =>
def run[A](p: Parser[A])(input: String): Either[ParseError, A]
def or[A](s1: Parser[A], s2: Parser[A]): Parser[A]
def simple: Parser[String] = ???
def trimmed: Parser[String] = ???
def string(s: String): Parser[String]
implicit def char(c: Char): Parser[Char] = ???
implicit def operators[A](p: Parser[A]) = ParserOps[A](p)
implicit def asStringParser[A](a: A)(implicit f: A => Parser[String]):
ParserOps[String] = ParserOps(f(a))
import scala.util.matching.Regex
implicit def regex(r: Regex): Parser[String]
case class ParserOps[A](p: Parser[A]) {
def |[B >: A](p2: Parser[B]): Parser[B] = self.or(p, p2)
def or[B >: A](p2: => Parser[B]): Parser[B] = self.or(p, p2)
def **[B >: A](p2: => Parser[B]): Parser[(A, B)] = self.product(p, p2)
def map[B](f: A => B): Parser[B] = self.map(p)(f)
def many: Parser[List[A]] = self.many(p)
def slice: Parser[String] = self.slice(p)
def flatMap[B](f: A => Parser[B]): Parser[B] = self.flatMap(p)(f)
}
def succeed[A](a: A): Parser[A] = string("") map (_ => a)
def slice[A](p: Parser[A]): Parser[String]
def get1[A, B](p: Parser[(A, B)]): Parser[A] = p.map(_._1)
//9.3
def many[A](p: Parser[A]): Parser[List[A]] =
map2(p, many(p))(_ :: _) or succeed(List())
//9.1
def map2[A, B, C](p: Parser[A], p2: => Parser[B])(f: (A, B) => C): Parser[C] = {
val pr: Parser[(A, B)] = product(p, p2)
map(pr)(f.tupled)
}
def many1[A](p: Parser[A]): Parser[List[A]] =
map2(p, many(p))((a, as) => a :: as)
//9.4
def listOfN[A](n: Int, p: Parser[A]): Parser[List[A]] =
if (n <= 0)
succeed(List())
else
map2(p, listOfN(n - 1, p))(_ :: _)
//9.5
def lazily[A](p: => Parser[A]): Parser[A] = p
def many1_lazy[A](p: Parser[A]): Parser[List[A]] =
map2(p, lazily(many(p)))((a, as) => a :: as)
import fpinscala.testing._
import fpinscala.testing.Prop.forAll
object Laws {
def equal[A](p1: Parser[A], p2: Parser[A])(in: Gen[String]): Prop =
forAll(in)(s => run(p1)(s) == run(p2)(s))
def mapLaw[A](p: Parser[A])(in: Gen[String]): Prop =
equal(p, p.map(a => a))(in)
def stringLaw(in: Gen[String]): Prop =
forAll(in)(s => run(string(s))(s) == Right(s))
//9.2
def productDefLaw[A, B](p1: Parser[A], p2: Parser[B])(in: Gen[(String, String)]): Prop =
forAll(in)(sp => {
val (s1, s2) = sp
val yy = for {
r1 <- run(p1)(s1)
r2 <- run(p2)(s2)
} yield ((r1, r2))
val zz = run(product(p1, p2))(s1 + s2)
yy == zz
})
def productAssocLaw[A, B, C](p1: Parser[A], p2: Parser[B], p3: Parser[C])(in: Gen[String]): Prop =
forAll(in)(s => run(product(product(p1, p2), p3))(s) == run(product(p1, product(p2, p3)))(s))
}
def flatMap[A, B](p: Parser[A])(f: A => Parser[B]): Parser[B]
//9.6
def nAChars: Parser[Int] = {
for {
n <- regex("[0-9]*".r).map(_.toInt)
_ <- listOfN(n, char('a'))
} yield n
}
//9.7
def product[A, B](p: Parser[A], p2: => Parser[B]): Parser[(A, B)] =
p.flatMap(a => p2.map(b => (a, b)))
def map2_2[A, B, C](p: Parser[A], p2: => Parser[B])(f: (A, B) => C): Parser[C] =
p.flatMap(a => p2.map(b => f(a, b)))
//9.8
def map[A, B](a: Parser[A])(f: A => B): Parser[B] =
a.flatMap(aa => succeed(f(aa)))
//9.11
def furthest[A](p: Parser[A]): Parser[A] = ???
def latest[A](p: Parser[A]): Parser[A] = ???
//9.10 - sucks
def label[A](msg: String)(p: Parser[A]): Parser[A]
def attempt[A](p: Parser[A]): Parser[A]
def scope[A](e: String)(p: Parser[A]): Parser[A]
}
//9.9
trait JSON
object JSON {
case object JNull extends JSON
case class JNumber(get: Double) extends JSON
case class JString(get: String) extends JSON
case class JBool(get: Boolean) extends JSON
case class JArray(get: IndexedSeq[JSON]) extends JSON
case class JObject(get: Map[String, JSON]) extends JSON
//trait Parser[JSON] {}
def jsonParser[Err, Parser[+ _]](P: Parsers[Err, Parser]): Parser[JSON] = {
import P._
//import JSON._
val spaces: Parser[String] = char(' ').many.slice
val jpNull: Parser[JSON] = string("null").map(_ => JNull)
val jpNumber: Parser[JSON] = regex("[0-9]*".r).map(d => JNumber(d.toInt))
val jpString: Parser[JSON] = simple.map(s => JString(s))
val jpBool: Parser[JSON] = regex("true|false".r).map(b => JBool(b.toBoolean))
val jpArray: Parser[JSON] = (jsonParser(P) ** char(',')).map(_._1).many.map(js => JArray(js.toIndexedSeq))
val jpObject: Parser[JSON] = ???
jpNull | jpNumber | jpString | jpBool | jpArray | jpObject
}
}
//9.18
trait ParseError2
case class ParseErrorSingle2(stack: List[(Location, String)] = List()) extends ParseError2
case class ParseErrorCombo() extends ParseError2
case class ParseError(stack: List[(Location, String)] = List()) {
def push(loc: Location, msg: String): ParseError =
copy(stack = (loc, msg) :: stack)
def label[A](s: String): ParseError =
ParseError(latestLoc.map((_, s)).toList)
def latest: Option[(Location, String)] =
stack.lastOption
def latestLoc: Option[Location] =
latest map (_._1)
//9.16
override def toString =
if (stack.isEmpty) "no error message"
else {
val collapsed = collapseStack(stack)
val context =
collapsed.lastOption.map("\n\n" + _._1.currentLine).getOrElse("") +
collapsed.lastOption.map("\n" + _._1.columnCaret).getOrElse("")
collapsed.map { case (loc, msg) => loc.line.toString + "." + loc.col + " " + msg }.mkString("\n") +
context
}
def collapseStack(s: List[(Location, String)]): List[(Location, String)] =
s.groupBy(_._1).
mapValues(_.map(_._2).mkString("; ")).
toList.sortBy(_._1.offset)
def formatLoc(l: Location): String = l.line + "." + l.col
}
//9.17
case class Location(input: String, offset: Int = 0, isSliced: Boolean = false) {
lazy val line = input.slice(0, offset + 1).count(_ == '\n') + 1
lazy val col = input.slice(0, offset + 1).lastIndexOf('\n') match {
case -1 => offset + 1
case lineStart => offset - lineStart
}
def toError(msg: String): ParseError =
ParseError(List((this, msg)))
def advanceBy(n: Int) = copy(offset = offset + n)
/* Returns the line corresponding to this location */
def currentLine: String =
if (input.length > 1) input.lines.drop(line - 1).next
else ""
def columnCaret = (" " * (col - 1)) + "^"
}
trait Result[+A] {
def addCommit(isCommitted: Boolean): Result[A] = this match {
case Failure(e, c) => Failure(e, c || isCommitted)
case _ => this
}
def advanceSuccess(n: Int): Result[A] = this match {
case Success(a, m) => Success(a, n + m)
case _ => this
}
def uncommit: Result[A] = this match {
case Failure(e, true) => Failure(e, false)
case _ => this
}
def mapError(f: ParseError => ParseError): Result[A] = this match {
case Failure(e, c) => Failure(f(e), c)
case _ => this
}
}
case class Success[+A](get: A, charsConsumed: Int) extends Result[A]
case class Failure(get: ParseError, isCommitted: Boolean) extends Result[Nothing]
type MyParser2[+A] = Location => Result[A]
//9.13
object MyParser2 extends Parsers[String, MyParser2] {
//9.15
override def run[A](p: MyParser2[A])(input: String): Either[String, A] = p(Location(input)) match {
case Success(a, _) => Right(a)
case Failure(e, _) => Left(e.toString)
}
override def or[A](x: MyParser2[A], y: MyParser2[A]): MyParser2[A] =
s => x(s) match {
case Failure(_, false) => y(s)
case r => r
}
override def string(s: String): MyParser2[String] =
(loc: Location) =>
if (loc.input.startsWith(s))
Success(s, s.length)
else
Failure(ParseError(), false)
override def succeed[A](a: A): MyParser2[A] =
(loc: Location) =>
Success(a, 0)
override implicit def regex(r: Regex): MyParser2[String] =
(loc: Location) =>
r.findFirstIn(loc.input) match {
case Some(value) => Success(value, value.length)
case None => Failure(ParseError(), false)
}
override def slice[A](p: MyParser2[A]): MyParser2[String] =
(loc: Location) =>
Success(loc.input.substring(0, loc.offset), loc.offset)
//9.14
override def scope[A](e: String)(p: MyParser2[A]): MyParser2[A] = {
s => p(s).mapError(_.push(s, e))
}
override def label[A](msg: String)(p: MyParser2[A]): MyParser2[A] =
s => p(s).mapError(_.label(msg))
override def flatMap[A, B](f: MyParser2[A])(g: A => MyParser2[B]): MyParser2[B] =
s => f(s) match {
case Success(a, n) => g(a)(s.advanceBy(n))
.addCommit(n != 0)
.advanceSuccess(n)
case e@Failure(_, _) => e
}
override def attempt[A](p: MyParser2[A]): MyParser2[A] = {
s => p(s).uncommit
}
}
//9.12
class MyParser[+A](val f: String => List[(A, String, String)]) {
def run(s: String): List[(A, String, String)] = f(s)
}
object MyParser extends Parsers[String, MyParser] {
override def run[A](p: MyParser[A])(input: String): Either[String, A] = p.run(input) match {
case x :: Nil => Right(x._1)
case _ => Left("Error")
}
override def string(s: String): MyParser[String] = {
val f = (x: String) => if (x.startsWith(s)) List((s, x.substring(s.length), s)) else Nil
new MyParser[String](f)
}
override def regex(r: Regex): MyParser[String] = {
val f = (x: String) => r.findFirstIn(x).map(m => (m, x.replaceFirst(m, ""), m)).toList
new MyParser[String](f)
}
override def flatMap[A, B](p: MyParser[A])(f: A => MyParser[B]): MyParser[B] = {
val ff = (x: String) => p.f(x).flatMap(t => f(t._1).f(t._2).map(tt => (tt._1, tt._2, t._3 + tt._3)))
new MyParser[B](ff)
}
override def slice[A](p: MyParser[A]): MyParser[String] = {
val ff = (x: String) => p.f(x).map(t => (t._3, t._2, t._3))
new MyParser[String](ff)
}
override def or[A](s1: MyParser[A], s2: MyParser[A]): MyParser[A] = {
val ff = (x: String) => s1.f(x) ++ s2.f(x)
new MyParser[A](ff)
}
//error handling
override def label[A](msg: String)(p: MyParser[A]): MyParser[A] = ???
override def attempt[A](p: MyParser[A]): MyParser[A] = ???
override def scope[A](e: String)(p: MyParser[A]): MyParser[A] = ???
}
}
|
rajthilakmca/megam_play
|
app/models/json/tosca/PolicySerialization.scala
|
<reponame>rajthilakmca/megam_play
/*
** Copyright [2013-2014] [Megam Systems]
**
** 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 models.json.tosca
import scalaz._
import scalaz.NonEmptyList._
import scalaz.Validation
import scalaz.Validation._
import Scalaz._
import net.liftweb.json._
import net.liftweb.json.scalaz.JsonScalaz._
import java.util.Date
import java.nio.charset.Charset
import controllers.funnel.FunnelErrors._
import controllers.Constants._
import controllers.funnel.SerializationBase
import models.tosca.{ Policy, MembersList }
/**
* @author rajthilak
*
*/
class PolicySerialization(charset: Charset = UTF8Charset) extends SerializationBase[Policy] {
protected val NameKey = "name"
protected val PtypeKey = "ptype"
protected val MembersKey = "members"
override implicit val writer = new JSONW[Policy] {
import MembersListSerialization.{ writer => MembersListWriter }
override def write(h: Policy): JValue = {
JObject(
JField(NameKey, toJSON(h.name)) ::
JField(PtypeKey, toJSON(h.ptype)) ::
JField(MembersKey, toJSON(h.members)(MembersListWriter)) ::
Nil)
}
}
override implicit val reader = new JSONR[Policy] {
import MembersListSerialization.{ reader => MembersListReader }
override def read(json: JValue): Result[Policy] = {
val nameField = field[String](NameKey)(json)
val ptypeField = field[String](PtypeKey)(json)
val membersField = field[MembersList](MembersKey)(json)(MembersListReader)
(nameField |@| ptypeField |@| membersField ) {
(name: String, ptype: String, members: MembersList) =>
new Policy(name, ptype, members)
}
}
}
}
|
rajthilakmca/megam_play
|
app/models/json/tosca/ContiniousIntegrationResultSerialization.scala
|
<reponame>rajthilakmca/megam_play
/*
** Copyright [2012-2013] [Megam Systems]
**
** 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 models.json.tosca
import scalaz._
import scalaz.NonEmptyList._
import scalaz.Validation
import scalaz.Validation._
import Scalaz._
import net.liftweb.json._
import net.liftweb.json.scalaz.JsonScalaz._
import java.util.Date
import java.nio.charset.Charset
import controllers.funnel.FunnelErrors._
import controllers.Constants._
import controllers.funnel.SerializationBase
import models.tosca.{ ContiniousIntegrationResult }
/**
* @author morpheyesh
*
*/
class ContiniousIntegrationResultSerialization(charset: Charset = UTF8Charset) extends SerializationBase[ContiniousIntegrationResult] {
protected val JSONClazKey = controllers.Constants.JSON_CLAZ
protected val ScmKey = "scm"
protected val EnableKey = "enable"
protected val TokenKey = "token"
protected val OwnerKey = "owner"
protected val ComponentIDKey = "component_id"
protected val AssemblyIDKey = "assembly_id"
protected val IdKey = "id"
protected val CreatedAtKey ="created_at"
override implicit val writer = new JSONW[ContiniousIntegrationResult] {
override def write(h: ContiniousIntegrationResult): JValue = {
JObject(
JField(EnableKey, toJSON(h.enable)) ::
JField(ScmKey, toJSON(h.scm)) ::
JField(TokenKey, toJSON(h.token)) ::
JField(OwnerKey, toJSON(h.owner)) ::
JField(ComponentIDKey, toJSON(h.component_id)) ::
JField(AssemblyIDKey, toJSON(h.assembly_id)) ::
JField(IdKey, toJSON(h.id)) ::
JField(CreatedAtKey, toJSON(h.created_at)) ::
Nil)
}
}
override implicit val reader = new JSONR[ContiniousIntegrationResult] {
override def read(json: JValue): Result[ContiniousIntegrationResult] = {
val idField = field[String](IdKey)(json)
val enableField = field[String](EnableKey)(json)
val scmField = field[String](ScmKey)(json)
val tokenField = field[String](TokenKey)(json)
val ownerField = field[String](OwnerKey)(json)
val componentIDField = field[String](ComponentIDKey)(json)
val assemblyIDField = field[String](AssemblyIDKey)(json)
val createdAtField = field[String](CreatedAtKey)(json)
(idField |@| enableField |@| scmField |@| tokenField |@| ownerField |@| componentIDField |@| assemblyIDField |@| createdAtField) {
(id: String, enable: String, scm: String, token: String, owner: String, component_id: String, assembly_id: String, created_at: String) =>
new ContiniousIntegrationResult(id, enable, scm, token, owner, component_id, assembly_id, created_at)
}
}
}
}
|
rajthilakmca/megam_play
|
app/models/tosca/Assembly.scala
|
/*
** Copyright [2013-2014] [Megam Systems]
**
** 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 models.tosca
import scalaz._
import Scalaz._
import scalaz.effect.IO
import scalaz.EitherT._
import scalaz.Validation
//import scalaz.Validation.FlatMap._
import scalaz.NonEmptyList._
import scalaz.syntax.SemigroupOps
import org.megam.util.Time
import scala.collection.mutable.ListBuffer
import controllers.stack._
import controllers.Constants._
import controllers.funnel.FunnelErrors._
import models.tosca._
import models._
import models.cache._
import models.riak._
import com.stackmob.scaliak._
import com.basho.riak.client.core.query.indexes.{ RiakIndexes, StringBinIndex, LongIntIndex }
import com.basho.riak.client.core.util.{ Constants => RiakConstants }
import org.megam.common.riak.{ GSRiak, GunnySack }
import org.megam.common.uid.UID
import net.liftweb.json._
import net.liftweb.json.scalaz.JsonScalaz._
import java.nio.charset.Charset
/**
* @author rajthilak
*
*/
case class AssemblyResult(id: String, name: String, components: models.tosca.ComponentLinks, policies: models.tosca.PoliciesList, inputs: String, operations: String, outputs: models.tosca.OutputsList, status: String, created_at: String) {
def toJValue: JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.tosca.AssemblyResultSerialization
val preser = new AssemblyResultSerialization()
toJSON(this)(preser.writer)
}
def toJson(prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue))
} else {
compactRender(toJValue)
}
}
object AssemblyResult {
def fromJValue(jValue: JValue)(implicit charset: Charset = UTF8Charset): Result[AssemblyResult] = {
import net.liftweb.json.scalaz.JsonScalaz.fromJSON
import models.json.tosca.AssemblyResultSerialization
val preser = new AssemblyResultSerialization()
fromJSON(jValue)(preser.reader)
}
def fromJson(json: String): Result[AssemblyResult] = (Validation.fromTryCatch {
parse(json)
} leftMap { t: Throwable =>
UncategorizedError(t.getClass.getCanonicalName, t.getMessage, List())
}).toValidationNel.flatMap { j: JValue => fromJValue(j) }
}
case class Policy(name: String, ptype: String, members: models.tosca.MembersList) {
val json = "{\"name\":\"" + name + "\",\"ptype\":\"" + ptype + "\",\"members\":" + MembersList.toJson(members, true) + "}"
def toJValue: JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
val preser = new models.json.tosca.PolicySerialization()
toJSON(this)(preser.writer)
}
def toJson(prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue))
} else {
compactRender(toJValue)
}
}
object Policy {
def empty: Policy = new Policy(new String(), new String(), MembersList.empty)
def fromJValue(jValue: JValue)(implicit charset: Charset = UTF8Charset): Result[Policy] = {
import net.liftweb.json.scalaz.JsonScalaz.fromJSON
val preser = new models.json.tosca.PolicySerialization()
fromJSON(jValue)(preser.reader)
}
def fromJson(json: String): Result[Policy] = (Validation.fromTryCatch[net.liftweb.json.JValue] {
play.api.Logger.debug(("%-20s -->[%s]").format("---json------------------->", json))
parse(json)
} leftMap { t: Throwable =>
UncategorizedError(t.getClass.getCanonicalName, t.getMessage, List())
}).toValidationNel.flatMap { j: JValue => fromJValue(j) }
}
case class Output(key: String, value: String) {
val json = "{\"key\":\"" + key + "\",\"value\":\"" + value + "\"}"
def toJValue: JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
val preser = new models.json.tosca.OutputSerialization()
toJSON(this)(preser.writer)
}
def toJson(prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue))
} else {
compactRender(toJValue)
}
}
object Output {
def empty: Output = new Output(new String(), new String())
def fromJValue(jValue: JValue)(implicit charset: Charset = UTF8Charset): Result[Output] = {
import net.liftweb.json.scalaz.JsonScalaz.fromJSON
val preser = new models.json.tosca.OutputSerialization()
fromJSON(jValue)(preser.reader)
}
def fromJson(json: String): Result[Output] = (Validation.fromTryCatch[net.liftweb.json.JValue] {
play.api.Logger.debug(("%-20s -->[%s]").format("---json------------------->", json))
parse(json)
} leftMap { t: Throwable =>
UncategorizedError(t.getClass.getCanonicalName, t.getMessage, List())
}).toValidationNel.flatMap { j: JValue => fromJValue(j) }
}
case class Assembly(name: String, components: models.tosca.ComponentsList, policies: models.tosca.PoliciesList, inputs: String, operations: String, outputs: models.tosca.OutputsList, status: String) {
val json = "{\"name\":\"" + name + "\",\"components\":" + ComponentsList.toJson(components, true) + ",\"policies\":" + PoliciesList.toJson(policies, true) +
",\"inputs\":\"" + inputs + "\",\"operations\":\"" + operations + "\",\"outputs\":" + OutputsList.toJson(outputs, true) + ",\"status\":\"" + status + "\"}"
def toJValue: JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
val preser = new models.json.tosca.AssemblySerialization()
toJSON(this)(preser.writer)
}
def toJson(prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue))
} else {
compactRender(toJValue)
}
}
case class AssemblyUpdateInput(id: String, name: String, components: models.tosca.ComponentLinks, policies: models.tosca.PoliciesList, inputs: String, operations: String, outputs: models.tosca.OutputsList, status: String, created_at: String) {
val json = "{\"id\":\"" + id + "\",\"name\":\"" + name + "\",\"components\":" + ComponentLinks.toJson(components, true) + ",\"policies\":" + PoliciesList.toJson(policies, true) +
",\"inputs\":\"" + inputs + "\",\"operations\":\"" + operations + "\",\"outputs\":" + OutputsList.toJson(outputs, true) + ",\"status\":\"" + status + "\",\"created_at\":\"" + created_at + "\"}"
}
object Assembly {
implicit val formats = DefaultFormats
private val riak = GWRiak("assembly")
val metadataKey = "ASSEMBLY"
val metadataVal = "Assembly Creation"
val bindex = "assembly"
def empty: Assembly = new Assembly(new String(), ComponentsList.empty, PoliciesList.empty, new String, new String(), OutputsList.empty, new String())
def fromJValue(jValue: JValue)(implicit charset: Charset = UTF8Charset): Result[Assembly] = {
import net.liftweb.json.scalaz.JsonScalaz.fromJSON
val preser = new models.json.tosca.AssemblySerialization()
fromJSON(jValue)(preser.reader)
}
def fromJson(json: String): Result[Assembly] = (Validation.fromTryCatch {
play.api.Logger.debug(("%-20s -->[%s]").format("---json------------------->", json))
parse(json)
} leftMap { t: Throwable =>
UncategorizedError(t.getClass.getCanonicalName, t.getMessage, List())
}).toValidationNel.flatMap { j: JValue => fromJValue(j) }
def findByNodeName(assemblyID: Option[List[String]]): ValidationNel[Throwable, AssemblyResults] = {
play.api.Logger.debug(("%-20s -->[%s]").format("models.Assembly", "findByNodeName:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("nodeNameList", assemblyID))
(assemblyID map {
_.map { asm_id =>
play.api.Logger.debug(("%-20s -->[%s]").format("Assembly ID", asm_id))
(riak.fetch(asm_id) leftMap { t: NonEmptyList[Throwable] =>
new ServiceUnavailableError(asm_id, (t.list.map(m => m.getMessage)).mkString("\n"))
}).toValidationNel.flatMap { xso: Option[GunnySack] =>
xso match {
case Some(xs) => {
//JsonScalaz.Error doesn't descend from java.lang.Error or Throwable. Screwy.
(AssemblyResult.fromJson(xs.value) leftMap
{ t: NonEmptyList[net.liftweb.json.scalaz.JsonScalaz.Error] =>
JSONParsingError(t)
}).toValidationNel.flatMap { j: AssemblyResult =>
play.api.Logger.debug(("%-20s -->[%s]").format("assemblies result", j))
Validation.success[Throwable, AssemblyResults](nels(j.some)).toValidationNel //screwy kishore, every element in a list ?
}
}
case None => {
Validation.failure[Throwable, AssemblyResults](new ResourceItemNotFound(asm_id, "")).toValidationNel
}
}
}
} // -> VNel -> fold by using an accumulator or successNel of empty. +++ => VNel1 + VNel2
} map {
_.foldRight((AssemblyResults.empty).successNel[Throwable])(_ +++ _)
}).head //return the folded element in the head.
}
private def updateGunnySack(email: String, input: String): ValidationNel[Throwable, Option[GunnySack]] = {
play.api.Logger.debug(("%-20s -->[%s]").format("tosca.Assembly Update", "mkGunnySack:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("email", email))
play.api.Logger.debug(("%-20s -->[%s]").format("json", input))
val ripNel: ValidationNel[Throwable, AssemblyUpdateInput] = (Validation.fromTryCatch {
parse(input).extract[AssemblyUpdateInput]
} leftMap { t: Throwable => new MalformedBodyError(input, t.getMessage) }).toValidationNel //capture failure
for {
rip <- ripNel
aor <- (Accounts.findByEmail(email) leftMap { t: NonEmptyList[Throwable] => t })
} yield {
val bvalue = Set(aor.get.id)
val json = AssemblyResult(rip.id, rip.name, rip.components, rip.policies, rip.inputs, rip.operations, rip.outputs, rip.status, rip.created_at).toJson(false)
new GunnySack((rip.id), json, RiakConstants.CTYPE_TEXT_UTF8, None,
Map(metadataKey -> metadataVal), Map((bindex, bvalue))).some
}
}
def update(email: String, input: String): ValidationNel[Throwable, Option[Tuple2[Map[String, String], String]]] = {
play.api.Logger.debug(("%-20s -->[%s]").format("models.Assembly", "update:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("json", input))
val ripNel: ValidationNel[Throwable, AssemblyUpdateInput] = (Validation.fromTryCatch {
parse(input).extract[AssemblyUpdateInput]
} leftMap { t: Throwable => new MalformedBodyError(input, t.getMessage) }).toValidationNel //capture failure
for {
rip <- ripNel
gs <- (updateGunnySack(email, input) leftMap { err: NonEmptyList[Throwable] => err })
maybeGS <- (riak.store(gs.get) leftMap { t: NonEmptyList[Throwable] => t })
com <- (Component.findByNodeName(List(rip.components(0)).some) leftMap { t: NonEmptyList[Throwable] => t })
} yield {
val nrip = parse(gs.get.value).extract[AssemblyResult]
maybeGS match {
case Some(thatGS) =>
Tuple2(Map[String, String](("Id" -> nrip.id), ("Action" -> "bind policy"), ("Args" -> "Nah")), nrip.name).some
case None => {
play.api.Logger.warn(("%-20s -->[%s]").format("Assembly.updated successfully", "Scaliak returned => None. Thats OK."))
Tuple2(Map[String, String](("Id" -> nrip.id), ("Action" -> "bind policy"), ("Args" -> "Nah")), nrip.name).some
}
}
}
}
}
object AssembliesList {
implicit val formats = DefaultFormats
implicit def AssembliesListsSemigroup: Semigroup[AssembliesLists] = Semigroup.instance((f1, f2) => f1.append(f2))
val emptyRR = List(Assembly.empty)
def toJValue(nres: AssembliesList): JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.tosca.AssembliesListSerialization.{ writer => AssembliesListWriter }
toJSON(nres)(AssembliesListWriter)
}
def fromJValue(jValue: JValue)(implicit charset: Charset = UTF8Charset): Result[AssembliesList] = {
import net.liftweb.json.scalaz.JsonScalaz.fromJSON
import models.json.tosca.AssembliesListSerialization.{ reader => AssembliesListReader }
fromJSON(jValue)(AssembliesListReader)
}
def toJson(nres: AssembliesList, prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue(nres)))
} else {
compactRender(toJValue(nres))
}
def apply(assemblyList: List[Assembly]): AssembliesList = { println(assemblyList); assemblyList }
def empty: List[Assembly] = emptyRR
private val riak = GWRiak("assembly")
val metadataKey = "ASSEMBLY"
val metadataVal = "Assembly Creation"
val bindex = "assembly"
def createLinks(email: String, input: AssembliesList): ValidationNel[Throwable, AssembliesLists] = {
play.api.Logger.debug(("%-20s -->[%s]").format("tosca.AssembliesList", "create:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("email", email))
play.api.Logger.debug(("%-20s -->[%s]").format("yaml", input))
val res = (input map {
asminp =>
play.api.Logger.debug(("%-20s -->[%s]").format("assembly", asminp))
(create(email, asminp))
}).foldRight((AssembliesLists.empty).successNel[Throwable])(_ +++ _)
play.api.Logger.debug(("%-20s -->[%s]").format("models.tosca.Assembly", res))
res.getOrElse(new ResourceItemNotFound(email, "nodes = ah. ouh. ror some reason.").failureNel[AssembliesLists])
res
}
/*
* create new market place item with the 'name' of the item provide as input.
* A index name assemblies name will point to the "csars" bucket
*/
def create(email: String, input: Assembly): ValidationNel[Throwable, AssembliesLists] = {
play.api.Logger.debug(("%-20s -->[%s]").format("tosca.AssembliesList", "create:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("email", email))
play.api.Logger.debug(("%-20s -->[%s]").format("yaml", input))
for {
ogsi <- mkGunnySack(email, input) leftMap { err: NonEmptyList[Throwable] => err }
nrip <- AssemblyResult.fromJson(ogsi.get.value) leftMap { t: NonEmptyList[net.liftweb.json.scalaz.JsonScalaz.Error] => println("osgi\n" + ogsi.get.value); play.api.Logger.debug(JSONParsingError(t).toString); nels(JSONParsingError(t)) }
ogsr <- riak.store(ogsi.get) leftMap { t: NonEmptyList[Throwable] => play.api.Logger.debug("--------> ooo"); t }
} yield {
play.api.Logger.debug(("%-20s -->[%s],riak returned: %s").format("Assembly.created successfully", email, ogsr))
ogsr match {
case Some(thatGS) => {
nels(AssemblyResult(thatGS.key, nrip.name, nrip.components, nrip.policies, nrip.inputs, nrip.operations, nrip.outputs, nrip.status, Time.now.toString()).some)
}
case None => {
play.api.Logger.warn(("%-20s -->[%s]").format("Node.created successfully", "Scaliak returned => None. Thats OK."))
nels(AssemblyResult(ogsi.get.key, nrip.name, nrip.components, nrip.policies, nrip.inputs, nrip.operations, nrip.outputs, nrip.status, Time.now.toString()).some)
}
}
}
}
private def mkGunnySack(email: String, rip: Assembly): ValidationNel[Throwable, Option[GunnySack]] = {
play.api.Logger.debug(("%-20s -->[%s]").format("tosca.Assembly", "mkGunnySack:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("email", email))
play.api.Logger.debug(("%-20s -->[%s]").format("json", rip))
var outlist = rip.outputs
for {
aor <- (Accounts.findByEmail(email) leftMap { t: NonEmptyList[Throwable] => t })
uir <- (UID(MConfig.snowflakeHost, MConfig.snowflakePort, "asm").get leftMap { ut: NonEmptyList[Throwable] => ut })
com <- (ComponentsList.createLinks(email, rip.components, (uir.get._1 + uir.get._2)) leftMap { t: NonEmptyList[Throwable] => t })
} yield {
val bvalue = Set(aor.get.id)
var components_links = new ListBuffer[String]()
for (component <- com) {
component match {
case Some(value) => components_links += value.id
case None => components_links += ""
}
}
if (rip.components(0).tosca_type == "tosca.web.docker") {
for {
predef <- (models.PredefClouds.create(email, new PredefCloudInput(rip.name, new PredefCloudSpec("docker", uir.get._1 + uir.get._2, "", "", ""), new PredefCloudAccess("", "", "fedora", "", "", "", "")).json) leftMap { t: NonEmptyList[Throwable] => t })
} yield {
outlist :::= List(Output("container", predef.get.name))
}
}
val json = AssemblyResult(uir.get._1 + uir.get._2, rip.name, components_links.toList, rip.policies, rip.inputs, rip.operations, outlist, rip.status, Time.now.toString).toJson(false)
new GunnySack((uir.get._1 + uir.get._2), json, RiakConstants.CTYPE_TEXT_UTF8, None,
Map(metadataKey -> metadataVal), Map((bindex, bvalue))).some
}
}
}
|
rajthilakmca/megam_play
|
test/tosca/CSARLinksSpec.scala
|
<reponame>rajthilakmca/megam_play
/*
** Copyright [2013-2014] [Megam Systems]
**
** 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.
*/
/**
* @author rajthilak
*
*/
package test.tosca
import scalaz._
import scalaz.syntax.SemigroupOps
import scalaz.NonEmptyList._
import scalaz.Validation._
import org.specs2.mutable._
import org.specs2.Specification
import java.net.URL
import org.specs2.matcher.MatchResult
import org.specs2.execute.{ Result => SpecsResult }
import com.stackmob.newman.response.{ HttpResponse, HttpResponseCode }
import com.stackmob.newman._
import com.stackmob.newman.dsl._
import controllers.stack.HeaderConstants._
import models.tosca.{ CSARInput }
import test.{Context}
class CSARLinksSpec extends Specification {
def is =
"CSARLinksSpec".title ^ end ^
"""
CSARLinksSpec is the implementation that calls the megam_play API server with the /csars url to create csars
""" ^ end ^
"The Client Should" ^
"Correctly do GET requests with a valid userid and api key" ! Get.succeeds ^
end
case object Get extends Context {
protected override def urlSuffix: String = "csars/CSI1147542768063741952"
protected def headersOpt: Option[Map[String, String]] = None
private val get = GET(url)(httpClient)
.addHeaders(headers)
def succeeds = {
val resp = execute(get)
resp.code must beTheSameResponseCodeAs(HttpResponseCode.Ok)
}
}
}
|
rajthilakmca/megam_play
|
test/tosca/AssembliesSpec.scala
|
<gh_stars>0
/*
** Copyright [2013-2014] [Megam Systems]
**
** 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 test.tosca
import org.specs2.mutable._
import org.specs2.Specification
import java.net.URL
import org.specs2.matcher.MatchResult
import org.specs2.execute.{ Result => SpecsResult }
import com.stackmob.newman.response.{ HttpResponse, HttpResponseCode }
import com.stackmob.newman._
import com.stackmob.newman.dsl._
import models.tosca._
import models.tosca.Assemblies
import test.{ Context }
/**
* @author ram
*
*/
class AssembliesSpec extends Specification {
def is =
"AssembliesSpec".title ^ end ^ """
AssembliesSpec is the implementation that calls the megam_play API server with the /assemblies url
""" ^ end ^
"The Client Should" ^
"Correctly do POST assemblies with a valid userid and api key" ! Post.succeeds ^
// "Correctly do GET requests with an valid Assemblies ID" ! findById.succeeds ^
//"Correctly do LIST requests with a valid userid and api key" ! List.succeeds ^
end
/**
* Change the body content in method bodyToStick
*/
case object Post extends Context {
protected override def urlSuffix: String = "assemblies/content"
protected override def bodyToStick: Option[String] = {
// val inputs = new AssembliesInputs("9c8281e6.637d8", "tab", "Sheet 2")
val contentToEncode = "{ \"name\":\"Sheet 1\", " +
"\"assemblies\":[ " +
"{ " +
"\"name\":\"PaulineHarper\"," +
"\"components\":[" +
"{" +
"\"name\":\"GussieMathis\"," +
"\"tosca_type\":\"tosca.web.riak\"," +
"\"requirements\":{" +
"\"host\":\"aws516887611449540608\"," +
"\"dummy\":\"\"" +
"}," +
"\"inputs\":{" +
"\"domain\":\"megam.co\"," +
"\"port\":\"\"," +
"\"username\":\"\"," +
"\"password\":\"\"," +
"\"version\":\"2.0.0\"," +
"\"source\":\"\"," +
"\"design_inputs\":{" +
"\"id\":\"46fc26f2.b903d8\"," +
"\"x\":645," +
"\"y\":184," +
"\"z\":\"adae6e10.52519\"," +
"\"wires\":[" +
"\"e0e3651f.1f1c98\"" +
"]" +
"}," +
"\"service_inputs\":{" +
"\"dbname\":\"\"," +
"\"dbpassword\":\"\"" +
"}," +
"\"ci\":{" +
"\"scm\":\"github\"," +
"\"enable\":\"true\"," +
"\"token\":\"token\"," +
"\"owner\":\"owner\"" +
"}}," +
"\"external_management_resource\":\"\"," +
"\"artifacts\":{" +
"\"artifact_type\":\"tosca type\"," +
"\"content\":\"\"," +
"\"artifact_requirements\":\"\"" +
"}," +
"\"related_components\":\"VernonDennis.megam.co/MasonHernandez\"," +
"\"operations\":{" +
"\"operation_type\":\"\"," +
"\"target_resource\":\"\"" +
"}," +
"\"others\":[{\"otherkey\":\"ci\",\"othervalue\":\"github\"}, {\"otherkey\":\"ci\",\"othervalue\":\"github\"}]" +
"}" +
"]," +
"\"policies\":[" +
"{" +
"\"name\":\"bind policy\"," +
"\"ptype\":\"colocated\"," +
"\"members\":[" +
"\"46fc26f2.b903d8\"" +
"]" +
"}" +
"]," +
"\"inputs\":\"\"," +
"\"operations\":\"\"," +
"\"status\":\"Launching\"" +
"}," +
"{" +
"\"name\":\"VernonDennis\"," +
"\"components\":[" +
"{" +
"\"name\":\"AddieOrtega\"," +
"\"tosca_type\":\"tosca.web.java\"," +
"\"requirements\":{" +
"\"host\":\"aws516887611449540608\"," +
"\"dummy\":\"\"" +
"}," +
"\"inputs\":{" +
"\"domain\":\"megam.co\"," +
"\"port\":\"\"," +
"\"username\":\"\"," +
"\"password\":\"\"," +
"\"version\":\"\"," +
"\"source\":\"dfhfgjh\"," +
"\"design_inputs\":{" +
"\"id\":\"e0e3651f.1f1c98\"," +
"\"x\":428," +
"\"y\":134," +
"\"z\":\"adae6e10.52519\"," +
"\"wires\":[" +
"\"46fc26f2.b903d8\"" +
"]" +
"}," +
"\"service_inputs\":{" +
"\"dbname\":\"\"," +
"\"dbpassword\":\"\"" +
"}," +
"\"ci\":{" +
"\"scm\":\"github\"," +
"\"enable\":\"true\"," +
"\"token\":\"token\"," +
"\"owner\":\"owner\"" +
"}}," +
"\"external_management_resource\":\"\"," +
"\"artifacts\":{" +
"\"artifact_type\":\"tosca type\"," +
"\"content\":\"\"," +
"\"artifact_requirements\":\"\"" +
"}," +
"\"related_components\":\"PaulineHarper.megam.co/GussieMathis\"," +
"\"operations\":{" +
"\"operation_type\":\"\"," +
"\"target_resource\":\"\"" +
"}," +
"\"others\":[]," +
"}," +
"{" +
"\"name\":\"MasonHernandez\"," +
"\"tosca_type\":\"tosca.web.akka\"," +
"\"requirements\":{" +
"\"host\":\"aws516887611449540608\"," +
"\"dummy\":\"\"" +
"}," +
"\"inputs\":{" +
"\"domain\":\"megam.co\"," +
"\"port\":\"\"," +
"\"username\":\"\"," +
"\"password\":\"\"," +
"\"version\":\"\"," +
"\"source\":\"dfghfh\"," +
"\"design_inputs\":{" +
"\"id\":\"3ecdffaf.c132\"," +
"\"x\":450," +
"\"y\":297," +
"\"z\":\"adae6e10.52519\"," +
"\"wires\":[" +
"\"46fc26f2.b903d8\"" +
"]" +
"}," +
"\"service_inputs\":{" +
"\"dbname\":\"\"," +
"\"dbpassword\":\"\"" +
"}," +
"\"ci\":{" +
"\"scm\":\"github\"," +
"\"enable\":\"true\"," +
"\"token\":\"token\"," +
"\"owner\":\"owner\"" +
"}}," +
"\"external_management_resource\":\"\"," +
"\"artifacts\":{" +
"\"artifact_type\":\"tosca type\"," +
"\"content\":\"\"," +
"\"artifact_requirements\":\"\"" +
"}," +
"\"related_components\":\"PaulineHarper.megam.co/GussieMathis\"," +
"\"operations\":{" +
"\"operation_type\":\"\"," +
"\"target_resource\":\"\"" +
"}," +
"\"others\":[]," +
"}" +
"]," +
"\"policies\":[" +
"{" +
"\"name\":\"bind policy\"," +
"\"ptype\":\"colocated\"," +
"\"members\":[" +
"\"e0e3651f.1f1c98\"," +
"\"3ecdffaf.c132\"" +
"]" +
"}" +
"]," +
"\"inputs\":\"\"," +
"\"operations\":\"\"," +
"\"status\":\"Launching\"" +
"}" +
"]," +
"\"inputs\":{" +
"\"id\":\"adae6e10.52519\"," +
"\"assemblies_type\":\"tab\"," +
"\"label\":\"Sheet 1\"," +
"\"cloudsettings\":[" +
"{" +
"\"id\":\"53ef867c.ac1078\"," +
"\"cstype\":\"cloudsettings\"," +
"\"cloudsettings\":\"aws516887611449540608\"," +
"\"x\":186," +
"\"y\":215," +
"\"z\":\"adae6e10.52519\"," +
"\"wires\":[" +
"\"e0e3651f.1f1c98\"," +
"\"3ecdffaf.c132\"," +
"\"46fc26f2.b903d8\"" +
"]" +
"}" +
"]" +
"}" +
"}"
Some(new String(contentToEncode))
}
protected override def headersOpt: Option[Map[String, String]] = None
private val post = POST(url)(httpClient)
.addHeaders(headers)
.addBody(body)
def succeeds: SpecsResult = {
val resp = execute(post)
resp.code must beTheSameResponseCodeAs(HttpResponseCode.Created)
}
}
case object List extends Context {
protected override def urlSuffix: String = "assemblies"
protected def headersOpt: Option[Map[String, String]] = None
private val get = GET(url)(httpClient)
.addHeaders(headers)
def succeeds = {
val resp = execute(get)
resp.code must beTheSameResponseCodeAs(HttpResponseCode.Ok)
}
}
case object findById extends Context {
protected override def urlSuffix: String = "assemblies/AMS520198742872162304"
protected def headersOpt: Option[Map[String, String]] = None
private val get = GET(url)(httpClient)
.addHeaders(headers)
def succeeds = {
val resp = execute(get)
resp.code must beTheSameResponseCodeAs(HttpResponseCode.Ok)
}
}
}
|
rajthilakmca/megam_play
|
app/controllers/funnel/FunnelResponse.scala
|
/*
** Copyright [2013-2014] [Megam Systems]
**
** 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 controllers.funnel
import scalaz._
import Scalaz._
import scalaz.effect.IO
import scalaz.EitherT._
import scalaz.Validation
//import scalaz.Validation.FlatMap._
import scalaz.NonEmptyList._
import net.liftweb.json._
import net.liftweb.json.scalaz.JsonScalaz._
import java.nio.charset.Charset
import controllers.Constants._
import controllers.funnel.FunnelErrors._
import org.megam.common.jsonscalaz._
import play.api.http.Status._
/**
* @author ram
*
*/
case class FunnelResponse(code: Int, msg: String, more: String, json_claz: String,
msg_type: String = "error", links: String = tailMsg) {
def toJValue: JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import controllers.funnel.FunnelResponseSerialization
val funser = new FunnelResponseSerialization()
toJSON(this)(funser.writer)
}
def toJson(prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue))
} else {
compactRender(toJValue)
}
}
object FunnelResponse {
def apply(code: Int, message: String, json_claz: String): FunnelResponse = new FunnelResponse(code, message, new String(), json_claz, "info")
def apply(message: String, json_claz: String): FunnelResponse = FunnelResponse(OK, message, json_claz)
def fromJValue(jValue: JValue)(implicit charset: Charset = UTF8Charset): Result[FunnelResponse] = {
import net.liftweb.json.scalaz.JsonScalaz.fromJSON
import controllers.funnel.FunnelResponseSerialization
val funser = new FunnelResponseSerialization()
fromJSON(jValue)(funser.reader)
}
def fromJson(json: String): Result[FunnelResponse] = (Validation.fromTryCatch[net.liftweb.json.JValue] {
parse(json)
} leftMap { t: Throwable =>
UncategorizedError(t.getClass.getCanonicalName, t.getMessage, List())
}).toValidationNel.flatMap { j: JValue => fromJValue(j) }
}
|
rajthilakmca/megam_play
|
app/Global.scala
|
<gh_stars>0
/*
** Copyright [2013-2014] [Megam Systems]
**
** 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.
*/
/**
* @author ram
*
*/
import play.api._
import play.api.http.Status._
import play.api.http.HeaderNames._
import play.api.mvc._
import play.api.mvc.Results._
import play.filters.gzip.{ GzipFilter }
import controllers.stack.HeaderConstants._
import scala.concurrent.Future
import controllers._
import java.io._
/**
* We do bunch of things in Global, a gzip response is sent back to the client when the
* header has "Content-length" > 5000bytes
*/
object Global extends WithFilters(new GzipFilter(shouldGzip = (request, response) =>
response.headers.get(CONTENT_TYPE).exists(_.startsWith(application_gzip)))) with GlobalSettings {
override def onStart(app: Application) {
play.api.Logger.info("megamgateway - started ---------------------------------------------------------")
val megamprimeddir = new File(Constants.MEGAM_PRIMED_DIR)
megamprimeddir.mkdirs()
val megamprimedfile = new File(Constants.MEGAM_PRIMED_FILE)
megamprimedfile.exists() match {
case true => play.api.Logger.info(">> Found megamprimed file, skip priming.")
case false =>
play.api.Logger.info(">> priming: performing priming.")
models.PlatformAppPrimer.acc_prep
play.api.Logger.info(">> priming: account..")
models.PlatformAppPrimer.mkp_prep
play.api.Logger.info(">> priming: marketplace..")
models.PlatformAppPrimer.org_prep
play.api.Logger.info(">> priming: org..")
models.PlatformAppPrimer.dmn_prep
play.api.Logger.info(">> priming: complete.")
megamprimedfile.createNewFile();
}
}
override def onStop(app: Application) {
play.api.Logger.info("megamgateway - going down---------------------------------------------------------")
}
override def onError(request: RequestHeader, ex: Throwable): Future[play.api.mvc.Result] = {
Future.successful(InternalServerError(
views.html.errorPage(ex)))
}
override def onHandlerNotFound(request: RequestHeader): Future[play.api.mvc.Result] = {
Future.successful(NotFound(
views.html.errorPage(new Throwable(NOT_FOUND + ":" + request.path + " NOT_FOUND"))))
}
}
|
rajthilakmca/megam_play
|
app/models/tosca/CSARLinks.scala
|
<filename>app/models/tosca/CSARLinks.scala
/*
** Copyright [2013-2014] [Megam Systems]
**
** 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 models.tosca
import scalaz._
import Scalaz._
import scalaz.effect.IO
import scalaz.EitherT._
import scalaz.Validation
//import scalaz.Validation.FlatMap._
import scalaz.NonEmptyList._
import scalaz.syntax.SemigroupOps
import scalaz.NonEmptyList._
import org.megam.util.Time
import controllers.stack._
import controllers.Constants._
import controllers.funnel.FunnelErrors._
import controllers.Constants._
import models._
import models.riak._
import com.stackmob.scaliak._
import com.basho.riak.client.core.query.indexes.{ RiakIndexes, StringBinIndex, LongIntIndex }
import com.basho.riak.client.core.util.{ Constants => RiakConstants }
import org.megam.common.riak.{ GSRiak, GunnySack }
import org.megam.common.uid.UID
import net.liftweb.json._
import net.liftweb.json.scalaz.JsonScalaz._
import java.nio.charset.Charset
import scala.collection.JavaConversions._
import models.cache._
import org.yaml.snakeyaml.Yaml
/**
* @author rajthilak
*
*/
case class CSARLinkInput(kachha: String) {
val TOSCA_DESCRIPTION = "description"
lazy val kacchaMango: Validation[Throwable, Map[String, String]] = (Validation.fromTryCatch[Map[String, String]] {
play.api.Logger.debug(("%-20s -->[%s]").format("tosca.CSARLinks", "kacchaMango:Entry"))
mapAsScalaMap[String, String](new Yaml().load(kachha).asInstanceOf[java.util.Map[String, String]]).toMap
} leftMap { t: Throwable => t
})
lazy val desc: ValidationNel[Throwable, Option[String]] = (kacchaMango.leftMap { err: Throwable =>
err
}).toValidationNel.flatMap { chunk: Map[String, String] => Validation.success[Throwable, Option[String]](chunk.get(TOSCA_DESCRIPTION)).toValidationNel }
}
case class CSARLinkResult(id: String, desc: String)
object CSARLinks {
implicit val formats = DefaultFormats
private val riak = GWRiak("csarlinks")
implicit def CSARsSemigroup: Semigroup[CSARLinkResults] = Semigroup.instance((f1, f2) => f1.append(f2))
val metadataKey = "csarlinkkey"
val metadataVal = "csarlinkkeys Creation"
val bindex = "csarlink"
/**
* A private method which chains computation to make GunnySack when provided with an input yaml, email.
* If there is an error during parsing, a MalformedBodyError is sent back.
* After that flatMap on its success and the account id information is looked up.
* If the account id is looked up successfully, then yield the GunnySack object.
*/
private def mkGunnySack(email: String, input: String): ValidationNel[Throwable, (String, Option[GunnySack])] = {
play.api.Logger.debug(("%-20s -->[%s]").format("tosca.CSARLinks", "mkGunnySack:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("email", email))
play.api.Logger.debug(("%-20s -->[%s]").format("yaml", input))
val csarInput: ValidationNel[Throwable, Option[String]] = CSARLinkInput(input).desc
for {
pdc <- csarInput
//TO-DO: Does the leftMap make sense ? To check during function testing, by removing it.
aor <- (Accounts.findByEmail(email) leftMap { t: NonEmptyList[Throwable] => t }) //captures failure on the left side, success on right ie the component before the (<-)
uir <- (UID(MConfig.snowflakeHost, MConfig.snowflakePort, "csi").get leftMap { ut: NonEmptyList[Throwable] => ut })
} yield {
//TO-DO: do we need a match for None on aor, and uir (confirm it during function testing).
val bvalue = Set(aor.get.id)
(pdc.get, (new GunnySack(uir.get._1 + uir.get._2, input, RiakConstants.CTYPE_TEXT_UTF8, None,
Map(metadataKey -> metadataVal), Map((bindex, bvalue)))).some)
}
}
/*
* create new Node with the 'name' of the node provide as input.
* A index name accountID will point to the "accounts" bucket
*/
def create(email: String, input: String): ValidationNel[Throwable, CSARLinkResult] = {
play.api.Logger.debug(("%-20s -->[%s]").format("tosca.CSARLinks", "create:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("email", email))
play.api.Logger.debug(("%-20s -->[%s]").format("yaml", input))
(mkGunnySack(email, input) leftMap { err: NonEmptyList[Throwable] =>
new ServiceUnavailableError(input, (err.list.map(m => m.getMessage)).mkString("\n"))
}).toValidationNel.flatMap { gs: (String, Option[GunnySack]) =>
(riak.store(gs._2.get) leftMap { t: NonEmptyList[Throwable] => t }).
flatMap { maybeGS: Option[GunnySack] =>
maybeGS match {
case Some(thatGS) => CSARLinkResult(thatGS.key, thatGS.value).successNel[Throwable]
case None => {
play.api.Logger.debug(("%-20s -->[%s]").format("desc", gs._1 + "," + gs._2.get))
play.api.Logger.warn(("%-20s -->[%s]").format("CSARLink.created success", "Scaliak returned => None. Thats OK."))
CSARLinkResult(gs._2.get.key, gs._1).successNel[Throwable]
}
}
}
}
}
def findByName(csarLinksNameList: Option[List[String]]): ValidationNel[Throwable, CSARLinkResults] = {
play.api.Logger.debug(("%-20s -->[%s]").format("tosca.CSARLinks", "findByName:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("CSARLinksList", csarLinksNameList))
(csarLinksNameList map {
_.map { csarLinkName =>
play.api.Logger.debug("models.tosca.CSARLinks findByName: CSARLinks:" + csarLinkName)
(riak.fetch(csarLinkName) leftMap { t: NonEmptyList[Throwable] =>
new ServiceUnavailableError(csarLinkName, (t.list.map(m => m.getMessage)).mkString("\n"))
}).toValidationNel.flatMap { xso: Option[GunnySack] =>
xso match {
case Some(xs) => {
(Validation.fromTryCatch[models.tosca.CSARLinkResult] {
CSARLinkResult(csarLinkName, xs.value)
} leftMap { t: Throwable =>
new ResourceItemNotFound(csarLinkName, t.getMessage)
}).toValidationNel.flatMap { j: CSARLinkResult =>
Validation.success[Throwable, CSARLinkResults](nels(j.some)).toValidationNel //screwy kishore, every element in a list ?
}
}
case None => Validation.failure[Throwable, CSARLinkResults](new ResourceItemNotFound(csarLinkName, "")).toValidationNel
}
}
} // -> VNel -> fold by using an accumulator or successNel of empty. +++ => VNel1 + VNel2
} map {
_.foldRight((CSARLinkResults.empty).successNel[Throwable])(_ +++ _)
}).head //return the folded element in the head.
}
/*
* An IO wrapped finder using an email. Upon fetching the account_id for an email,
* the csarlinknames are listed on the index (account.id) in bucket `CSARLinks`.
* Using a "csarlinkname" as key, return a list of ValidationNel[List[CSARLinkResult]]
* Takes an email, and returns a Future[ValidationNel, List[Option[CSARLinkResult]]]
*/
def findByEmail(email: String): ValidationNel[Throwable, CSARLinkResults] = {
play.api.Logger.debug(("%-20s -->[%s]").format("tosca.CSARLinks", "findByNodeName:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("email", email))
val res = eitherT[IO, NonEmptyList[Throwable], ValidationNel[Throwable, CSARLinkResults]] {
(((for {
aor <- (Accounts.findByEmail(email) leftMap { t: NonEmptyList[Throwable] => t }) //captures failure on the left side, success on right ie the component before the (<-)
} yield {
val bindex = ""
val bvalue = Set("")
new GunnySack("csarlink", aor.get.id, RiakConstants.CTYPE_TEXT_UTF8,
None, Map(metadataKey -> metadataVal), Map((bindex, bvalue))).some
}) leftMap { t: NonEmptyList[Throwable] => t } flatMap {
gs: Option[GunnySack] => riak.fetchIndexByValue(gs.get)
} map { nm: List[String] =>
(if (!nm.isEmpty) findByName(nm.some) else
new ResourceItemNotFound(email, "CSARLinks = nothing found.").failureNel[CSARLinkResults])
}).disjunction).pure[IO]
}.run.map(_.validation).unsafePerformIO
res.getOrElse(new ResourceItemNotFound(email, "CSARLinks = nothing found.").failureNel[CSARLinkResults])
}
}
|
rajthilakmca/megam_play
|
app/models/json/tosca/ComponentResultSerialization.scala
|
/*
** Copyright [2013-2014] [Megam Systems]
**
** 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 models.json.tosca
import scalaz._
import scalaz.NonEmptyList._
import scalaz.Validation
import scalaz.Validation._
import Scalaz._
import net.liftweb.json._
import net.liftweb.json.scalaz.JsonScalaz._
import java.util.Date
import java.nio.charset.Charset
import controllers.funnel.FunnelErrors._
import controllers.Constants._
import controllers.funnel.SerializationBase
import models.tosca.{ ComponentResult, ComponentsList, ComponentInputsResult, ComponentOperations, Artifacts, ComponentRequirements, ComponentOthers }
/**
* @author rajthilak
*
*/
class ComponentResultSerialization(charset: Charset = UTF8Charset) extends SerializationBase[ComponentResult] {
protected val JSONClazKey = controllers.Constants.JSON_CLAZ
protected val IdKey = "id"
protected val NameKey = "name"
protected val ToscaTypeKey = "tosca_type"
protected val RequirementsKey = "requirements"
protected val InputsKey = "inputs"
protected val ExternalManagementResourceKey = "external_management_resource"
protected val ArtifactsKey = "artifacts"
protected val RelatedComponentsKey ="related_components"
protected val OperationsKey = "operations"
protected val OthersKey = "others"
protected val CreatedAtKey ="created_at"
override implicit val writer = new JSONW[ComponentResult] {
import ComponentRequirementsSerialization.{ writer => ComponentRequirementsWriter }
import models.json.tosca.ComponentInputsResultSerialization.{ writer => ComponentInputsResultWriter }
import models.json.tosca.ArtifactsSerialization.{ writer => ArtifactsWriter }
import models.json.tosca.ComponentOperationsSerialization.{ writer => ComponentOperationsWriter }
import models.json.tosca.ComponentOthersSerialization.{ writer => ComponentOthersWriter }
override def write(h: ComponentResult): JValue = {
JObject(
JField(IdKey, toJSON(h.id)) ::
JField(JSONClazKey, toJSON("Megam::Components")) ::
JField(NameKey, toJSON(h.name)) ::
JField(ToscaTypeKey, toJSON(h.tosca_type)) ::
JField(RequirementsKey, toJSON(h.requirements)(ComponentRequirementsWriter)) ::
JField(InputsKey, toJSON(h.inputs)(ComponentInputsResultWriter)) ::
JField(ExternalManagementResourceKey, toJSON(h.external_management_resource)) ::
JField(ArtifactsKey, toJSON(h.artifacts)(ArtifactsWriter)) ::
JField(RelatedComponentsKey, toJSON(h.related_components)) ::
JField(OperationsKey, toJSON(h.operations)(ComponentOperationsWriter)) ::
JField(OthersKey, toJSON(h.others)(ComponentOthersWriter)) ::
JField(CreatedAtKey, toJSON(h.created_at)) :: Nil)
}
}
override implicit val reader = new JSONR[ComponentResult] {
import models.json.tosca.ComponentInputsResultSerialization.{ reader => ComponentInputsResultReader}
import models.json.tosca.ArtifactsSerialization.{ reader => ArtifactsReader }
import models.json.tosca.ComponentOperationsSerialization.{ reader => ComponentOperationsReader }
import models.json.tosca.ComponentOthersSerialization.{ reader => ComponentOthersReader }
import ComponentRequirementsSerialization.{ reader => ComponentRequirementsReader }
override def read(json: JValue): Result[ComponentResult] = {
val idField = field[String](IdKey)(json)
val nameField = field[String](NameKey)(json)
val toscaTypeField = field[String](ToscaTypeKey)(json)
val requirementsField = field[ComponentRequirements](RequirementsKey)(json)(ComponentRequirementsReader)
val inputsField = field[ComponentInputsResult](InputsKey)(json)(ComponentInputsResultReader)
val externalManagementResourceField = field[String](ExternalManagementResourceKey)(json)
val artifactsField = field[Artifacts](ArtifactsKey)(json)(ArtifactsReader)
val relatedComponentsField = field[String](RelatedComponentsKey)(json)
val operationsField = field[ComponentOperations](OperationsKey)(json)(ComponentOperationsReader)
val othersField = field[ComponentOthers](OthersKey)(json)(ComponentOthersReader)
val createdAtField = field[String](CreatedAtKey)(json)
(idField |@| nameField |@| toscaTypeField |@| requirementsField |@| inputsField |@| externalManagementResourceField |@| artifactsField |@| relatedComponentsField |@| operationsField |@| othersField |@| createdAtField) {
(id: String, name: String, tosca_type: String, requirements: ComponentRequirements, inputs: ComponentInputsResult, external_management_resource: String, artifacts: Artifacts, related_components: String, operations: ComponentOperations, others: ComponentOthers, created_at: String) =>
new ComponentResult(id, name, tosca_type, requirements, inputs, external_management_resource, artifacts, related_components, operations, others, created_at)
}
}
}
}
|
rajthilakmca/megam_play
|
app/models/tosca/Organizations.scala
|
/*
** Copyright [2012-2014] [Megam Systems]
**
** 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 models.tosca
import scalaz._
import scalaz.syntax.SemigroupOps
import scalaz.NonEmptyList._
import scalaz.Validation._
import scalaz.effect.IO
import scalaz.EitherT._
import org.megam.util.Time
import Scalaz._
import controllers.stack._
import controllers.Constants._
import controllers.funnel.FunnelErrors._
import models.tosca._
import models.cache._
import models.riak._
import com.stackmob.scaliak._
import com.basho.riak.client.core.query.indexes.{ RiakIndexes, StringBinIndex, LongIntIndex }
import com.basho.riak.client.core.util.{ Constants => RiakConstants }
import org.megam.common.riak.{ GSRiak, GunnySack }
import org.megam.common.uid.UID
import net.liftweb.json._
import net.liftweb.json.scalaz.JsonScalaz._
import java.nio.charset.Charset
/**
* @author morpheyesh
*
*/
case class OrganizationsInput(name: String) {
val json = "{\"name\":\"" + name + "\"}"
}
case class OrganizationsResult(id: String, accounts_id: String, name: String, created_at: String) {
def toJValue: JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.tosca.OrganizationsResultSerialization
val preser = new OrganizationsResultSerialization()
toJSON(this)(preser.writer) //where does this JSON from?
}
def toJson(prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue))
} else {
compactRender(toJValue)
}
}
object OrganizationsResult {
def fromJValue(jValue: JValue)(implicit charset: Charset = UTF8Charset): Result[OrganizationsResult] = {
import net.liftweb.json.scalaz.JsonScalaz.fromJSON
import models.json.tosca.OrganizationsResultSerialization
val preser = new OrganizationsResultSerialization()
fromJSON(jValue)(preser.reader)
}
def fromJson(json: String): Result[OrganizationsResult] = (Validation.fromTryCatch {
parse(json)
} leftMap { t: Throwable =>
UncategorizedError(t.getClass.getCanonicalName, t.getMessage, List())
}).toValidationNel.flatMap { j: JValue => fromJValue(j) }
}
object Organizations {
implicit val formats = DefaultFormats
private val riak = GWRiak("organizations")
implicit def OrganizationsResultsSemigroup: Semigroup[OrganizationsResults] = Semigroup.instance((f1, f2) => f1.append(f2))
val metadataKey = "Organizations"
val metadataVal = "Organizations Creation"
val bindex = "organization"
/**
* A private method which chains computation to make GunnySack when provided with an input json, email.
* parses the json, and converts it to organizationsinput, if there is an error during parsing, a MalformedBodyError is sent back.
* After that flatMap on its success and the account id information is looked up.
* If the account id is looked up successfully, then yield the GunnySack object.
*/
private def mkGunnySack(email: String, input: String): ValidationNel[Throwable, Option[GunnySack]] = {
play.api.Logger.debug(("%-20s -->[%s]").format("models.tosca.Organizations", "mkGunnySack:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("email", email))
play.api.Logger.debug(("%-20s -->[%s]").format("json", input))
val organizationsInput: ValidationNel[Throwable, OrganizationsInput] = (Validation.fromTryCatch {
parse(input).extract[OrganizationsInput]
} leftMap { t: Throwable => new MalformedBodyError(input, t.getMessage) }).toValidationNel //capture failure
for {
org <- organizationsInput
aor <- (models.Accounts.findByEmail(email) leftMap { t: NonEmptyList[Throwable] => t })
uir <- (UID(MConfig.snowflakeHost, MConfig.snowflakePort, "org").get leftMap { ut: NonEmptyList[Throwable] => ut })
} yield {
val bvalue = Set(aor.get.id)
val json = new OrganizationsResult(uir.get._1 + uir.get._2, aor.get.id, org.name, Time.now.toString).toJson(false)
new GunnySack(org.name, json, RiakConstants.CTYPE_TEXT_UTF8, None,
Map(metadataKey -> metadataVal), Map((bindex, bvalue))).some
}
}
/*
* create new organization item with the 'name' of the item provide as input.
* A index name organization name will point to the "organization bucket" bucket.
*/
def create(email: String, input: String): ValidationNel[Throwable, Option[OrganizationsResult]] = {
play.api.Logger.debug(("%-20s -->[%s]").format("models.Organizations", "create:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("email", email))
play.api.Logger.debug(("%-20s -->[%s]").format("json", input))
(mkGunnySack(email, input) leftMap { err: NonEmptyList[Throwable] =>
new ServiceUnavailableError(input, (err.list.map(m => m.getMessage)).mkString("\n"))
}).toValidationNel.flatMap { gs: Option[GunnySack] =>
(riak.store(gs.get) leftMap { t: NonEmptyList[Throwable] => t }).
flatMap { maybeGS: Option[GunnySack] =>
maybeGS match {
case Some(thatGS) => (parse(thatGS.value).extract[OrganizationsResult].some).successNel[Throwable]
case None => {
play.api.Logger.warn(("%-20s -->[%s]").format("Organizations.created success", "Scaliak returned => None. Thats OK."))
(parse(gs.get.value).extract[OrganizationsResult].some).successNel[Throwable];
}
}
}
}
}
def findByName(organizationsList: Option[List[String]]): ValidationNel[Throwable, OrganizationsResults] = {
play.api.Logger.debug(("%-20s -->[%s]").format("models.Organizations", "findByName:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("nodeNameList", organizationsList))
(organizationsList map {
_.map { organizationsName =>
play.api.Logger.debug(("%-20s -->[%s]").format("organizationsName", organizationsName))
(riak.fetch(organizationsName) leftMap { t: NonEmptyList[Throwable] =>
new ServiceUnavailableError(organizationsName, (t.list.map(m => m.getMessage)).mkString("\n"))
}).toValidationNel.flatMap { xso: Option[GunnySack] =>
xso match {
case Some(xs) => {
//JsonScalaz.Error doesn't descend from java.lang.Error or Throwable. Screwy.
(OrganizationsResult.fromJson(xs.value) leftMap
{ t: NonEmptyList[net.liftweb.json.scalaz.JsonScalaz.Error] =>
JSONParsingError(t)
}).toValidationNel.flatMap { j: OrganizationsResult =>
play.api.Logger.debug(("%-20s -->[%s]").format("organizationsresult", j))
Validation.success[Throwable, OrganizationsResults](nels(j.some)).toValidationNel //screwy kishore, every element in a list ?
}
}
case None => {
Validation.failure[Throwable, OrganizationsResults](new ResourceItemNotFound(organizationsName, "")).toValidationNel
}
}
}
} // -> VNel -> fold by using an accumulator or successNel of empty. +++ => VNel1 + VNel2
} map {
_.foldRight((OrganizationsResults.empty).successNel[Throwable])(_ +++ _)
}).head //return the folded element in the head.
}
def findByEmail(email: String): ValidationNel[Throwable, OrganizationsResults] = {
play.api.Logger.debug(("%-20s -->[%s]").format("models.Organizations", "findByEmail:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("email", email))
val res = eitherT[IO, NonEmptyList[Throwable], ValidationNel[Throwable, OrganizationsResults]] {
(((for {
aor <- (models.Accounts.findByEmail(email) leftMap { t: NonEmptyList[Throwable] => t }) //captures failure on the left side, success on right ie the component before the (<-)
} yield {
val bindex = ""
val bvalue = Set("")
play.api.Logger.debug(("%-20s -->[%s]").format(" Organizations result", aor.get))
new GunnySack("organization", aor.get.id, RiakConstants.CTYPE_TEXT_UTF8,
None, Map(metadataKey -> metadataVal), Map((bindex, bvalue))).some
}) leftMap { t: NonEmptyList[Throwable] => t } flatMap {
gs: Option[GunnySack] => riak.fetchIndexByValue(gs.get)
} map { nm: List[String] =>
(if (!nm.isEmpty) findByName(nm.some) else
new ResourceItemNotFound(email, "organizations = nothing found.").failureNel[OrganizationsResults])
}).disjunction).pure[IO]
}.run.map(_.validation).unsafePerformIO
res.getOrElse(new ResourceItemNotFound(email, "organizations = nothing found.").failureNel[OrganizationsResults])
}
}
|
rajthilakmca/megam_play
|
app/models/CloudToolSettings.scala
|
/*
** Copyright [2013-2014] [Megam Systems]
**
** 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 models
import scalaz._
import Scalaz._
import scalaz.effect.IO
import scalaz.EitherT._
import scalaz.Validation
//import scalaz.Validation.FlatMap._
import scalaz.NonEmptyList._
import scalaz.syntax.SemigroupOps
import org.megam.util.Time
import controllers.stack._
import controllers.Constants._
import controllers.funnel.FunnelErrors._
import models._
import models.riak._
import com.stackmob.scaliak._
import com.basho.riak.client.core.query.indexes.{RiakIndexes, StringBinIndex, LongIntIndex }
import com.basho.riak.client.core.util.{ Constants => RiakConstants }
import org.megam.common.riak.{ GSRiak, GunnySack }
import org.megam.common.uid.UID
import net.liftweb.json._
import net.liftweb.json.scalaz.JsonScalaz._
import java.nio.charset.Charset
/**
* @author rajthilak
*
*/
case class CloudToolSettingInput(cloud_type: String, repo_name: String, repo: String, vault_location: String, conf_location: String) {
val json = "{\"cloud_type\":\"" + cloud_type + "\",\"repo_name\":\"" + repo_name + "\",\"repo\":\"" + repo + "\",\"vault_location\":\"" + vault_location + "\",\"conf_location\":\"" + conf_location + "\"}"
}
case class CloudToolSettingResult(id: String, accounts_id: String, cloud_type: String, repo_name: String, repo: String, vault_location: String, conf_location: String, created_at: String) {
def toJValue: JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.CloudToolSettingResultSerialization
val preser = new CloudToolSettingResultSerialization()
toJSON(this)(preser.writer)
}
def toJson(prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue))
} else {
compactRender(toJValue)
}
}
object CloudToolSettingResult {
def fromJValue(jValue: JValue)(implicit charset: Charset = UTF8Charset): Result[CloudToolSettingResult] = {
import net.liftweb.json.scalaz.JsonScalaz.fromJSON
import models.json.CloudToolSettingResultSerialization
val preser = new CloudToolSettingResultSerialization()
fromJSON(jValue)(preser.reader)
}
def fromJson(json: String): Result[CloudToolSettingResult] = (Validation.fromTryCatch[net.liftweb.json.JValue] {
parse(json)
} leftMap { t: Throwable =>
UncategorizedError(t.getClass.getCanonicalName, t.getMessage, List())
}).toValidationNel.flatMap { j: JValue => fromJValue(j) }
}
object CloudToolSettings {
implicit val formats = DefaultFormats
private val riak = GWRiak( "CloudToolSettings")
implicit def CloudToolSettingResultsSemigroup: Semigroup[CloudToolSettingResults] = Semigroup.instance((f1, f2) => f1.append(f2))
val metadataKey = "CloudToolSetting"
val metadataVal = "CloudToolSetting Creation"
val bindex = "CloudToolSetting"
/**
* A private method which chains computation to make GunnySack when provided with an input json, email.
* parses the json, and converts it to CloudToolSetting input, if there is an error during parsing, a MalformedBodyError is sent back.
* After that flatMap on its success and the account id information is looked up.
* If the account id is looked up successfully, then yield the GunnySack object.
*/
private def mkGunnySack(email: String, input: String): ValidationNel[Throwable, Option[GunnySack]] = {
play.api.Logger.debug(("%-20s -->[%s]").format("models.CloudToolSettings", "mkGunnySack:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("email", email))
play.api.Logger.debug(("%-20s -->[%s]").format("json", input))
val CloudToolSettingInput: ValidationNel[Throwable, CloudToolSettingInput] = (Validation.fromTryCatch[models.CloudToolSettingInput] {
parse(input).extract[CloudToolSettingInput]
} leftMap { t: Throwable => new MalformedBodyError(input, t.getMessage) }).toValidationNel //capture failure
for {
pdc <- CloudToolSettingInput
//TO-DO: Does the leftMap make sense ? To check during function testing, by removing it.
aor <- (Accounts.findByEmail(email) leftMap { t: NonEmptyList[Throwable] => t }) //captures failure on the left side, success on right ie the component before the (<-)
uir <- (UID(MConfig.snowflakeHost, MConfig.snowflakePort, "cts").get leftMap { ut: NonEmptyList[Throwable] => ut })
} yield {
//TO-DO: do we need a match for None on aor, and uir (confirm it during function testing).
val bvalue = Set(aor.get.id)
val json = new CloudToolSettingResult(uir.get._1 + uir.get._2, aor.get.id, pdc.cloud_type, pdc.repo_name, pdc.repo, pdc.vault_location, pdc.conf_location, Time.now.toString).toJson(false)
new GunnySack(uir.get._1 + uir.get._2, json, RiakConstants.CTYPE_TEXT_UTF8, None,
Map(metadataKey -> metadataVal), Map((bindex, bvalue))).some
}
}
/*
* create new Node with the 'name' of the node provide as input.
* A index name CloudToolSettingID will point to the "CloudToolSettings" bucket
*/
def create(email: String, input: String): ValidationNel[Throwable, Option[Tuple3[String, String, String]]] = {
play.api.Logger.debug(("%-20s -->[%s]").format("models.CloudToolSettings", "create:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("email", email))
play.api.Logger.debug(("%-20s -->[%s]").format("json", input))
(mkGunnySack(email, input) leftMap { err: NonEmptyList[Throwable] =>
new ServiceUnavailableError(input, (err.list.map(m => m.getMessage)).mkString("\n"))
}).toValidationNel.flatMap { gs: Option[GunnySack] =>
val req_result = parse(gs.get.value).extract[CloudToolSettingResult]
(riak.store(gs.get) leftMap { t: NonEmptyList[Throwable] => t }).
flatMap { maybeGS: Option[GunnySack] =>
maybeGS match {
case Some(thatGS) => Tuple3(thatGS.key, req_result.vault_location, req_result.repo).some.successNel[Throwable]
case None => {
play.api.Logger.warn(("%-20s -->[%s]").format("CloudToolSettings.created success", "Scaliak returned => None. Thats OK."))
(gs.get.key, req_result.vault_location, req_result.repo).some.successNel[Throwable];
}
}
}
}
}
def findByName(cloudtoolsettingList: Option[List[String]]): ValidationNel[Throwable, CloudToolSettingResults] = {
play.api.Logger.debug(("%-20s -->[%s]").format("models.CloudToolSettings", "findByNodeName:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("CloudToolSettingsList", cloudtoolsettingList))
(cloudtoolsettingList map {
_.map { CloudToolSettingName =>
play.api.Logger.debug("models.CloudToolSetting findByName: CloudToolSettings:" + CloudToolSettingName)
(riak.fetch(CloudToolSettingName) leftMap { t: NonEmptyList[Throwable] =>
new ServiceUnavailableError(CloudToolSettingName, (t.list.map(m => m.getMessage)).mkString("\n"))
}).toValidationNel.flatMap { xso: Option[GunnySack] =>
xso match {
case Some(xs) => {
(Validation.fromTryCatch[models.CloudToolSettingResult] {
parse(xs.value).extract[CloudToolSettingResult]
} leftMap { t: Throwable =>
new ResourceItemNotFound(CloudToolSettingName, t.getMessage)
}).toValidationNel.flatMap { j: CloudToolSettingResult =>
Validation.success[Throwable, CloudToolSettingResults](nels(j.some)).toValidationNel //screwy kishore, every element in a list ?
}
}
case None => Validation.failure[Throwable, CloudToolSettingResults](new ResourceItemNotFound(CloudToolSettingName, "")).toValidationNel
}
}
} // -> VNel -> fold by using an accumulator or successNel of empty. +++ => VNel1 + VNel2
} map {
_.foldRight((CloudToolSettingResults.empty).successNel[Throwable])(_ +++ _)
}).head //return the folded element in the head.
}
/*
* An IO wrapped finder using an email. Upon fetching the account_id for an email,
* the nodenames are listed on the index (account.id) in bucket `Nodes`.
* Using a "nodename" as key, return a list of ValidationNel[List[NodeResult]]
* Takes an email, and returns a Future[ValidationNel, List[Option[NodeResult]]]
*/
def findByEmail(email: String): ValidationNel[Throwable, CloudToolSettingResults] = {
play.api.Logger.debug(("%-20s -->[%s]").format("models.CloudToolSettings", "findByNodeName:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("email", email))
val res = eitherT[IO, NonEmptyList[Throwable], ValidationNel[Throwable, CloudToolSettingResults]] {
(((for {
aor <- (Accounts.findByEmail(email) leftMap { t: NonEmptyList[Throwable] => t }) //captures failure on the left side, success on right ie the component before the (<-)
} yield {
val bindex = ""
val bvalue = Set("")
new GunnySack("CloudToolSetting", aor.get.id, RiakConstants.CTYPE_TEXT_UTF8,
None, Map(metadataKey -> metadataVal), Map((bindex, bvalue))).some
}) leftMap { t: NonEmptyList[Throwable] => t } flatMap {
gs: Option[GunnySack] => riak.fetchIndexByValue(gs.get)
} map { nm: List[String] =>
(if (!nm.isEmpty) findByName(nm.some) else
new ResourceItemNotFound(email, "CloudToolSettings = nothing found.").failureNel[CloudToolSettingResults])
}).disjunction).pure[IO]
}.run.map(_.validation).unsafePerformIO
res.getOrElse(new ResourceItemNotFound(email, "CloudToolSettings = nothing found.").failureNel[CloudToolSettingResults])
}
}
|
rajthilakmca/megam_play
|
app/models/json/AppRequestResultSerialization.scala
|
/*
** Copyright [2012-2013] [Megam Systems]
**
** 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 models.json
import scalaz._
import scalaz.NonEmptyList._
import scalaz.Validation
import scalaz.Validation._
import Scalaz._
import net.liftweb.json._
import net.liftweb.json.scalaz.JsonScalaz._
import java.util.Date
import java.nio.charset.Charset
import controllers.funnel.FunnelErrors._
import controllers.Constants._
import controllers.funnel.SerializationBase
import models.{AppRequestResult}
/**
* @author rajthilak
*
*/
class AppRequestResultSerialization(charset: Charset = UTF8Charset) extends SerializationBase[AppRequestResult] {
protected val JSONClazKey = controllers.Constants.JSON_CLAZ
protected val IdKey = "id"
protected val AppIDKey = "app_id"
protected val AppNameKey = "app_name"
protected val ActionKey = "action"
protected val CreatedAtKey ="created_at"
override implicit val writer = new JSONW[AppRequestResult] {
override def write(h: AppRequestResult): JValue = {
JObject(
JField(IdKey, toJSON(h.id)) ::
JField(AppIDKey, toJSON(h.app_id)) ::
JField(AppNameKey, toJSON(h.app_name)) ::
JField(JSONClazKey, toJSON("Megam::AppRequest")) ::
JField(ActionKey, toJSON(h.action)) ::
JField(CreatedAtKey, toJSON(h.created_at)) :: Nil)
}
}
override implicit val reader = new JSONR[AppRequestResult] {
override def read(json: JValue): Result[AppRequestResult] = {
val idField = field[String](IdKey)(json)
val appIdField = field[String](AppIDKey)(json)
val appNameField = field[String](AppNameKey)(json)
val actionField = field[String](ActionKey)(json)
val createdAtField = field[String](CreatedAtKey)(json)
(idField |@| appIdField |@| appNameField |@| actionField |@| createdAtField) {
(id: String, app_id: String, app_name: String, action: String, created_at: String) =>
new AppRequestResult(id, app_id, app_name, action, created_at)
}
}
}
}
|
rajthilakmca/megam_play
|
test/tosca/CSARsSpec.scala
|
<reponame>rajthilakmca/megam_play<filename>test/tosca/CSARsSpec.scala
/*
** Copyright [2013-2014] [Megam Systems]
**
** 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.
*/
/**
* @author rajthilak
*
*/
package test.tosca
import scalaz._
import scalaz.syntax.SemigroupOps
import scalaz.NonEmptyList._
import scalaz.Validation._
import org.specs2.mutable._
import org.specs2.Specification
import java.net.URL
import org.specs2.matcher.MatchResult
import org.specs2.execute.{ Result => SpecsResult }
import com.stackmob.newman.response.{ HttpResponse, HttpResponseCode }
import com.stackmob.newman._
import com.stackmob.newman.dsl._
import controllers.stack.HeaderConstants._
import models.tosca.{ CSARInput }
import test.{Context}
class CSARsSpec extends Specification {
def is =
"CSARsSpec".title ^ end ^
"""
CSARsSpec is the implementation that calls the megam_play API server with the /csars url to create csars
""" ^ end ^
"The Client Should" ^
// "Correctly do POST requests" ! Post.succeeds ^
"Correctly do PUSH requests" ! Push.succeeds ^
// "Correctly do LIST requests with a valid userid and api key" ! List.succeeds ^
// "Correctly do GET requests with a valid userid and api key" ! Get.succeeds ^
// "Correctly do POST requests with an invalid body" ! PostInvalidBody.succeeds ^
end
//post the headers and their body for specifing url
case object Post extends Context {
protected override def urlSuffix: String = "csars/content"
protected override def bodyToStick: Option[String] = {
val contentToEncode = scala.io.Source.fromFile("./test/tosca/appgroup.csar").mkString
Some(contentToEncode)
}
protected override def headersOpt: Option[Map[String, String]] = None
private val post = POST(url)(httpClient)
.addHeaders(headers)
.addBody(body)
def succeeds: SpecsResult = {
val resp = execute(post)
resp.code must beTheSameResponseCodeAs(HttpResponseCode.Created)
}
}
case object Push extends Context {
protected override def urlSuffix: String = "csars/push/CSR1147833510380306432"
protected override def headersOpt: Option[Map[String, String]] = None
private val get = GET(url)(httpClient)
.addHeaders(headers)
def succeeds: SpecsResult = {
val resp = execute(get)
resp.code must beTheSameResponseCodeAs(HttpResponseCode.Created)
}
}
case object List extends Context {
protected override def urlSuffix: String = "csars"
protected def headersOpt: Option[Map[String, String]] = None
private val get = GET(url)(httpClient)
.addHeaders(headers)
def succeeds = {
val resp = execute(get)
resp.code must beTheSameResponseCodeAs(HttpResponseCode.Ok)
}
}
case object Get extends Context {
protected override def urlSuffix: String = "csars/CSI1147543125976285184"
protected def headersOpt: Option[Map[String, String]] = None
private val get = GET(url)(httpClient)
.addHeaders(headers)
def succeeds = {
val resp = execute(get)
resp.code must beTheSameResponseCodeAs(HttpResponseCode.Ok)
}
}
/**
* test case for invalidBody
*/
case object PostInvalidBody extends Context {
protected override def urlSuffix: String = "csars/content"
protected override def bodyToStick: Option[String] = {
val contentToEncode = scala.io.Source.fromFile("./test/tosca/appplusdb_bad.csar").mkString
Some(new String(contentToEncode))
}
protected override def headersOpt: Option[Map[String, String]] = None
private val post = POST(url)(httpClient)
.addHeaders(headers)
.addBody(body)
def succeeds: SpecsResult = {
val resp = execute(post)
resp.code must beTheSameResponseCodeAs(HttpResponseCode.ServiceUnavailable)
}
}
}
|
rajthilakmca/megam_play
|
app/models/tosca/CSARs.scala
|
<filename>app/models/tosca/CSARs.scala
/*
** Copyright [2013-2014] [Megam Systems]
**
** 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 models.tosca
import scalaz._
import Scalaz._
import scalaz.effect.IO
import scalaz.EitherT._
import scalaz.Validation
//import scalaz.Validation.FlatMap._
import scalaz.NonEmptyList._
import scalaz.syntax.SemigroupOps
import org.megam.util.Time
import controllers.stack._
import controllers.Constants._
import controllers.funnel.FunnelErrors._
import models._
import models.cache._
import models.riak._
import com.stackmob.scaliak._
import com.basho.riak.client.core.query.indexes.{ RiakIndexes, StringBinIndex, LongIntIndex }
import com.basho.riak.client.core.util.{ Constants => RiakConstants }
import org.megam.common.riak.{ GSRiak, GunnySack }
import org.megam.common.uid.UID
import net.liftweb.json._
import net.liftweb.json.scalaz.JsonScalaz._
import java.nio.charset.Charset
import org.megam.common.amqp.response._
/**
* @author rajthilak
*
*/
case class CSARInput(doc: String)
case class CSARResult(id: String, desc: String, link: String, created_at: String) {
def toJValue: JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.tosca.CSARResultSerialization
val preser = new CSARResultSerialization()
toJSON(this)(preser.writer)
}
def toJson(prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue))
} else {
compactRender(toJValue)
}
}
object CSARResult {
def fromJValue(jValue: JValue)(implicit charset: Charset = UTF8Charset): Result[CSARResult] = {
import net.liftweb.json.scalaz.JsonScalaz.fromJSON
import models.json.tosca.CSARResultSerialization
val preser = new CSARResultSerialization()
fromJSON(jValue)(preser.reader)
}
def fromJson(json: String): Result[CSARResult] = (Validation.fromTryCatch[net.liftweb.json.JValue] {
parse(json)
} leftMap { t: Throwable =>
UncategorizedError(t.getClass.getCanonicalName, t.getMessage, List())
}).toValidationNel.flatMap { j: JValue => fromJValue(j) }
val empty = CSARResult("", "", "", "")
}
object CSARs {
implicit val formats = DefaultFormats
private val riak = GWRiak("csars")
implicit def CSARsSemigroup: Semigroup[CSARResults] = Semigroup.instance((f1, f2) => f1.append(f2))
val metadataKey = "CSAR"
val metadataVal = "CSARs Creation"
val bindex = "csar"
/**
* A private method which chains computation to make GunnySack when provided with an input json, email.
* parses the json, and converts it to nodeinput, if there is an error during parsing, a MalformedBodyError is sent back.
* After that flatMap on its success and the account id information is looked up.
* If the account id is looked up successfully, then yield the GunnySack object.
*/
private def mkGunnySack(email: String, input: String): ValidationNel[Throwable, Option[GunnySack]] = {
play.api.Logger.debug(("%-20s -->[%s]").format("tosca.CSARs", "mkGunnySack:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("email", email))
play.api.Logger.debug(("%-20s -->[%s]").format("json", input))
for {
aor <- (Accounts.findByEmail(email) leftMap { t: NonEmptyList[Throwable] => t })
csir <- (CSARLinks.create(email, input) leftMap { err: NonEmptyList[Throwable] => err })
uir <- (UID(MConfig.snowflakeHost, MConfig.snowflakePort, "csr").get leftMap { ut: NonEmptyList[Throwable] => ut })
} yield {
val csar_res = new CSARResult(uir.get._1 + uir.get._2, csir.desc, csir.id, Time.now.toString)
val bvalue = Set(aor.get.id)
play.api.Logger.debug(("%-20s -->[%s]").format("tosca.CSARs", "mkGunnysack" + bvalue))
new GunnySack(csar_res.id, csar_res.toJson(false), RiakConstants.CTYPE_TEXT_UTF8, None,
Map(metadataKey -> metadataVal), Map((bindex, bvalue))).some
}
}
/*
* create new market place item with the 'name' of the item provide as input.
* A index name csar name will point to the "csars" bucket
*/
def create(email: String, input: String): ValidationNel[Throwable, Option[CSARResult]] = {
play.api.Logger.debug(("%-20s -->[%s]").format("tosca.CSARs", "create:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("email", email))
(mkGunnySack(email, input) leftMap { err: NonEmptyList[Throwable] =>
new ServiceUnavailableError(input, (err.list.map(m => m.getMessage)).mkString("\n"))
}).toValidationNel.flatMap { gs: Option[GunnySack] =>
(riak.store(gs.get) leftMap { t: NonEmptyList[Throwable] => t }).
flatMap { maybeGS: Option[GunnySack] =>
maybeGS match {
case Some(thatGS) => (parse(thatGS.value).extract[CSARResult].some).successNel[Throwable]
case None => {
play.api.Logger.warn(("%-20s -->[%s]").format("CSAR.created success", "Scaliak returned => None. Thats OK."))
(parse(gs.get.value).extract[CSARResult].some).successNel[Throwable]
}
}
}
}
}
def getCSAR(input: String): ValidationNel[Throwable, CSARResults] = {
for {
csir <- (CSARs.findByName(List(input).some) leftMap { err: NonEmptyList[Throwable] => err })
} yield {
csir
}
}
def getCsarLink(input: CSARResults): ValidationNel[Throwable, CSARLinkResults] = {
(input map {
_.map { csars =>
InMemory[ValidationNel[Throwable, CSARLinkResults]]({
csar =>
{
play.api.Logger.debug("tosca.CSARs findLinksByName: csars:" + csars)
CSARLinks.findByName(List(csars.link).some)
}
}).get(csars.link).eval(InMemoryCache[ValidationNel[Throwable, CSARLinkResults]]())
}
} map {
_.foldRight((CSARLinkResults.empty).successNel[Throwable])(_ +++ _)
}).head //return the folded element in the head.
}
def getYaml(input: CSARLinkResults): ValidationNel[Throwable, String] = {
(input map {
_.map { links =>
InMemory[ValidationNel[Throwable, String]]({
csar =>
{
play.api.Logger.debug("tosca.CSARs findLinksByName: csars:" + links)
CSARJson.toJson(links.desc)
}
}).get(links.desc).eval(InMemoryCache[ValidationNel[Throwable, String]]())
}
} map {
_.foldRight(("").successNel[Throwable])(_ +++ _)
}).head //return the folded element in the head.
}
def push(email: String, input: String): ValidationNel[Throwable, AMQPResponse] = {
for {
csar <- (CSARs.getCSAR(input) leftMap { err: NonEmptyList[Throwable] => err })
csir <- (getCsarLink(csar) leftMap { err: NonEmptyList[Throwable] => err })
json <- (getYaml(csir) leftMap { err: NonEmptyList[Throwable] => err })
asm <- (Assemblies.create(email, json) leftMap { err: NonEmptyList[Throwable] => err })
request <- (models.Requests.createforNewNode("{\"node_id\": \"" + asm.get.id + "\",\"node_name\": \"" + asm.get.name + "\",\"req_type\": \"create\"}") leftMap { err: NonEmptyList[Throwable] => err })
amqp <- (CloudStandUpPublish(request.get._2, request.get._1).dop leftMap { err: NonEmptyList[Throwable] => err })
} yield {
play.api.Logger.debug("tosca.CSARs Pushed: csars:" + json)
amqp
}
}
def findLinksByName(csarslinksNameList: Option[List[String]]): ValidationNel[Throwable, CSARLinkResults] = {
play.api.Logger.debug(("%-20s -->[%s]").format("tosca.CSARs", "findLinksByNodeName:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("csarlinksList", csarslinksNameList))
(csarslinksNameList map {
_.map { csarslinksName =>
InMemory[ValidationNel[Throwable, CSARLinkResults]]({
clinkname: String =>
{
play.api.Logger.debug("tosca.CSARs findLinksByName: csars:" + csarslinksName)
CSARLinks.findByName(List(clinkname).some)
}
}).get(csarslinksName).eval(InMemoryCache[ValidationNel[Throwable, CSARLinkResults]]())
}
} map {
_.foldRight((CSARLinkResults.empty).successNel[Throwable])(_ +++ _)
}).head //return the folded element in the head.
}
def findByName(csarsNameList: Option[List[String]]): ValidationNel[Throwable, CSARResults] = {
play.api.Logger.debug(("%-20s -->[%s]").format("tosca.CSARs", "findByNodeName:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("csarList", csarsNameList))
(csarsNameList map {
_.map { csarsName =>
InMemory[ValidationNel[Throwable, CSARResults]]({
cname: String =>
{
play.api.Logger.debug("tosca.CSARs findByName: csars:" + csarsName)
(riak.fetch(csarsName) leftMap { t: NonEmptyList[Throwable] =>
new ServiceUnavailableError(csarsName, (t.list.map(m => m.getMessage)).mkString("\n"))
}).toValidationNel.flatMap { xso: Option[GunnySack] =>
xso match {
case Some(xs) => {
(Validation.fromTryCatch[models.tosca.CSARResult] {
parse(xs.value).extract[CSARResult]
} leftMap { t: Throwable =>
new ResourceItemNotFound(csarsName, t.getMessage)
}).toValidationNel.flatMap { j: CSARResult =>
Validation.success[Throwable, CSARResults](nels(j.some)).toValidationNel //screwy kishore, every element in a list ?
}
}
case None => Validation.failure[Throwable, CSARResults](new ResourceItemNotFound(csarsName, "")).toValidationNel
}
}
}
}).get(csarsName).eval(InMemoryCache[ValidationNel[Throwable, CSARResults]]())
}
} map {
_.foldRight((CSARResults.empty).successNel[Throwable])(_ +++ _)
}).head //return the folded element in the head.
}
/*
* An IO wrapped finder using an email. Upon fetching the account_id for an email,
* the csarnames are listed on the index (account.id) in bucket `CSARs`.
* Using a "csarname" as key, return a list of ValidationNel[List[CSARResult]]
* Takes an email, and returns a Future[ValidationNel, List[Option[CSARResult]]]
*/
def findByEmail(email: String): ValidationNel[Throwable, CSARResults] = {
play.api.Logger.debug(("%-20s -->[%s]").format("tosca.CSARs", "findByEmail:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("email", email))
val res = eitherT[IO, NonEmptyList[Throwable], ValidationNel[Throwable, CSARResults]] {
(((for {
aor <- (Accounts.findByEmail(email) leftMap { t: NonEmptyList[Throwable] => t }) //captures failure on the left side, success on right ie the component before the (<-)
} yield {
val bindex = ""
val bvalue = Set("")
play.api.Logger.debug(("%-20s -->[%s]").format("tosca.CSARs", "findByEmail" + aor.get.id))
new GunnySack("csar", aor.get.id, RiakConstants.CTYPE_TEXT_UTF8,
None, Map(metadataKey -> metadataVal), Map((bindex, bvalue))).some
}) leftMap { t: NonEmptyList[Throwable] => t } flatMap {
gs: Option[GunnySack] => riak.fetchIndexByValue(gs.get)
} map { nm: List[String] =>
(if (!nm.isEmpty) findByName(nm.some) else
new ResourceItemNotFound(email, "CSAR = nothing found.").failureNel[CSARResults])
}).disjunction).pure[IO]
}.run.map(_.validation).unsafePerformIO
res.getOrElse(new ResourceItemNotFound(email, "CSAR = nothing found.").failureNel[CSARResults])
}
implicit val sedimentCSARsResults = new Sedimenter[ValidationNel[Throwable, CSARResults]] {
def sediment(maybeASediment: ValidationNel[Throwable, CSARResults]): Boolean = {
val notSed = maybeASediment.isSuccess
play.api.Logger.debug("%-20s -->[%s]".format("|^/^|-->CSR:sediment:", notSed))
notSed
}
}
implicit val sedimentStrings = new Sedimenter[ValidationNel[Throwable, String]] {
def sediment(maybeASediment: ValidationNel[Throwable, String]): Boolean = {
val notSed = maybeASediment.isSuccess
play.api.Logger.debug("%-20s -->[%s]".format("|^/^|-->CSR:sediment:", notSed))
notSed
}
}
implicit val sedimentCSARLinksResults = new Sedimenter[ValidationNel[Throwable, CSARLinkResults]] {
def sediment(maybeASediment: ValidationNel[Throwable, CSARLinkResults]): Boolean = {
val notSed = maybeASediment.isSuccess
play.api.Logger.debug("%-20s -->[%s]".format("|^/^|-->CSRLK:sediment:", notSed))
notSed
}
}
}
|
rajthilakmca/megam_play
|
test/PredefCloudsSpec.scala
|
<filename>test/PredefCloudsSpec.scala
/*
** Copyright [2013-2014] [Megam Systems]
**
** 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.
*/
/**
* @author rajthilak
*
*/
package test
import org.specs2.mutable._
import org.specs2.Specification
import java.net.URL
import controllers.Constants._
import org.specs2.matcher.MatchResult
import org.specs2.execute.{ Result => SpecsResult }
import com.stackmob.newman.response.{ HttpResponse, HttpResponseCode }
import com.stackmob.newman._
import com.stackmob.newman.dsl._
import controllers.stack.HeaderConstants._
import models.{ PredefCloudInput, PredefCloudSpec, PredefCloudAccess }
class PredefCloudsSpec extends Specification {
def is =
"PredefsCloudSpec".title ^ end ^
"""
PredefCloudsSpec is the implementation that calls the megam_play API server with the /predefcloud url to create predefclouds
""" ^ end ^
"The Client Should" ^
"Correctly do POST requests" ! Post0.succeeds ^
// "Correctly do POST requests" ! Post1.succeeds ^
// "Correctly do LIST requests with a valid userid and api key" ! List.succeeds ^
// "Correctly do GET requests with a valid userid and api key" ! Get.succeeds ^
// "Correctly do POST requests with an invalid key" ! PostInvalidUrl.succeeds ^
//"Correctly do POST requests with an invalid body" ! PostInvalidBody.succeeds ^
// "Correctly do GET requests with a invalid apikey" ! GetInvalidApi.succeeds ^
// "Correctly do GET requests with a invalid email" ! GetInvalidEmail.succeeds ^
end
//post the headers and their body for specifing url
case object Post0 extends Context {
protected override def urlSuffix: String = "predefclouds/content"
protected override def bodyToStick: Option[String] = {
val contentToEncode = new PredefCloudInput("clouddefault",
new PredefCloudSpec("google", "", "debian-7-wheezy-v20131120", "f1-micro", ""),
new PredefCloudAccess("", "cloudkeys/" + MEGAM_ADMIN_EMAIL + "/id_rsa.pub", "ubuntu", "https://s3-ap-southeast-1.amazonaws.com/cloudkeys/" + MEGAM_ADMIN_EMAIL + "/gdefault", "", "europe-west1-a", "")).json
Some(contentToEncode)
}
protected override def headersOpt: Option[Map[String, String]] = None
private val post = POST(url)(httpClient)
.addHeaders(headers)
.addBody(body)
def succeeds: SpecsResult = {
val resp = execute(post)
resp.code must beTheSameResponseCodeAs(HttpResponseCode.Created)
}
}
//post the headers and their body for specifing url (insert one more record)
case object Post1 extends Context {
protected override def urlSuffix: String = "predefclouds/content"
protected override def bodyToStick: Option[String] = {
val contentToEncode = new PredefCloudInput("ec2_play", new PredefCloudSpec("fooz-type", "fooz-group", "fooz-image", "fooz-flvr", ""),
new PredefCloudAccess("fooz-ssh", "fooz-identity-file", "fooz-sshuser", "https://s3-ap-southeast-1.amazonaws.com/cloudkeys/megam@mypaas.io/default", "fooz-identity-file", "", "region")).json
Some(contentToEncode)
}
protected override def headersOpt: Option[Map[String, String]] = None
private val post = POST(url)(httpClient)
.addHeaders(headers)
.addBody(body)
def succeeds: SpecsResult = {
val resp = execute(post)
resp.code must beTheSameResponseCodeAs(HttpResponseCode.Created)
}
}
case object List extends Context {
protected override def urlSuffix: String = "predefclouds"
protected def headersOpt: Option[Map[String, String]] = None
private val get = GET(url)(httpClient)
.addHeaders(headers)
def succeeds = {
val resp = execute(get)
resp.code must beTheSameResponseCodeAs(HttpResponseCode.Ok)
}
}
case object Get extends Context {
protected override def urlSuffix: String = "predefclouds/clouddefault510348255477891072"
protected def headersOpt: Option[Map[String, String]] = None
private val get = GET(url)(httpClient)
.addHeaders(headers)
def succeeds = {
val resp = execute(get)
resp.code must beTheSameResponseCodeAs(HttpResponseCode.Ok)
}
}
/**
* test case for invalidUrl
*/
case object PostInvalidUrl extends Context {
protected override def urlSuffix: String = "predefclouds/contentinvalidurl"
protected override def bodyToStick: Option[String] = {
val contentToEncode = "{\"email\":\"<EMAIL>\", \"api_key\":\"IamAtlas{74}NobodyCanSeeME#075488\", \"authority\":\"user\" }"
Some(new String(contentToEncode))
}
protected override def headersOpt: Option[Map[String, String]] = None
private val post = POST(url)(httpClient)
.addHeaders(headers)
.addBody(body)
def succeeds: SpecsResult = {
val resp = execute(post)
resp.code must beTheSameResponseCodeAs(HttpResponseCode.NotFound)
}
}
/**
* test case for invalidBody
*/
case object PostInvalidBody extends Context {
protected override def urlSuffix: String = "predefclouds/content"
protected override def bodyToStick: Option[String] = {
val contentToEncode = "{\"collapsedmail\":\"<EMAIL>\", \"inval_api_key\":\"IamAtlas{74}NobodyCanSeeME#075488\", \"authority\":\"user\" }"
Some(new String(contentToEncode))
}
protected override def headersOpt: Option[Map[String, String]] = None
private val post = POST(url)(httpClient)
.addHeaders(headers)
.addBody(body)
def succeeds: SpecsResult = {
val resp = execute(post)
resp.code must beTheSameResponseCodeAs(HttpResponseCode.ServiceUnavailable)
}
}
case object GetInvalidApi extends Context {
protected override def urlSuffix: String = "predefclouds/ec2_rails"
protected override def headersOpt: Option[Map[String, String]] = Some(Map(Content_Type -> application_json,
X_Megam_EMAIL -> "<EMAIL>", X_Megam_APIKEY -> "i@a)23_mC-han^00g57#ed8a+p%i",
X_Megam_DATE -> currentDate, Accept -> application_vnd_megam_json))
private val get = GET(url)(httpClient)
.addHeaders(headers)
def succeeds = {
val resp = execute(get)
resp.code must beTheSameResponseCodeAs(HttpResponseCode.Unauthorized)
}
}
case object GetInvalidEmail extends Context {
protected override def urlSuffix: String = "predefcouds/meg-rails"
protected override def headersOpt: Option[Map[String, String]] = Some(Map(Content_Type -> application_json,
X_Megam_EMAIL -> "<EMAIL>", X_Megam_APIKEY -> "IamAtlas{74}NobodyCanSeeME#07",
X_Megam_DATE -> currentDate, Accept -> application_vnd_megam_json))
private val get = GET(url)(httpClient)
.addHeaders(headers)
def succeeds = {
val resp = execute(get)
resp.code must beTheSameResponseCodeAs(HttpResponseCode.NotFound)
}
}
}
|
rajthilakmca/megam_play
|
app/controllers/stack/MConfig.scala
|
<reponame>rajthilakmca/megam_play
/*
** Copyright [2013-2014] [Megam Systems]
**
** 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 controllers.stack
/**
* @author ram
*
*/
/**
* play.api.Play.current to get the current configuration
* getString() method return the current configuration file value
*/
object MConfig {
val riakurl = play.api.Play.application(play.api.Play.current).configuration.getString("riak.url").get
val amqpuri = play.api.Play.application(play.api.Play.current).configuration.getString("amqp.url").get
val routing_key = play.api.Play.application(play.api.Play.current).configuration.getString("amqp.routing.key").get
val snowflakeHost = play.api.Play.application(play.api.Play.current).configuration.getString("sf.host").get
val snowflakePort: Int = play.api.Play.application(play.api.Play.current).configuration.getInt("sf.port").get
val cloudstandup_queue = play.api.Play.application(play.api.Play.current).configuration.getString("amqp.global.cloudstandup.queue").get
val cloudstandup_exchange = play.api.Play.application(play.api.Play.current).configuration.getString("amqp.global.cloudstandup.exchange").get
val riakstash_queue = play.api.Play.application(play.api.Play.current).configuration.getString("amqp.global.riakstash.queue").get
val riakstash_exchange = play.api.Play.application(play.api.Play.current).configuration.getString("amqp.global.riakstash.exchange").get
val postlaunched_queue = play.api.Play.application(play.api.Play.current).configuration.getString("amqp.global.postlaunched.queue").get
val postlaunched_exchange = play.api.Play.application(play.api.Play.current).configuration.getString("amqp.global.postlaunched.exchange").get
val cloudper_node_queue_prefix = play.api.Play.application(play.api.Play.current).configuration.getString("amqp.node.queue.prefix").get
val cloudper_node_exchage_prefix = play.api.Play.application(play.api.Play.current).configuration.getString("amqp.node.exchange.prefix").get
val cloudrecipe_queue = play.api.Play.application(play.api.Play.current).configuration.getString("amqp.global.cloudrecipe.queue").get
val cloudrecipe_exchange = play.api.Play.application(play.api.Play.current).configuration.getString("amqp.global.cloudrecipe.exchange").get
val ci_queue = play.api.Play.application(play.api.Play.current).configuration.getString("amqp.global.ci.queue").get
val ci_exchange = play.api.Play.application(play.api.Play.current).configuration.getString("amqp.global.ci.exchange").get
val event_queue = play.api.Play.application(play.api.Play.current).configuration.getString("amqp.global.event.queue").get
val event_exchange = play.api.Play.application(play.api.Play.current).configuration.getString("amqp.global.event.exchange").get
}
|
rajthilakmca/megam_play
|
app/controllers/funnel/package.scala
|
<gh_stars>0
/*
** Copyright [2013-2014] [Megam Systems]
**
** 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 controllers
import scalaz._
import Scalaz._
import scalaz.effect.IO
import scalaz.EitherT._
import scalaz.Validation
//import scalaz.Validation.FlatMap._
import scalaz.NonEmptyList._
import controllers.funnel.FunnelErrors._
import controllers.funnel.FunnelResponsesSerialization
import controllers.Constants._
import jp.t2v.lab.play2.stackc.{ RequestWithAttributes, RequestAttributeKey, StackableController }
import java.io.{ StringWriter, PrintWriter }
import net.liftweb.json._
import net.liftweb.json.scalaz.JsonScalaz._
import java.nio.charset.Charset
import play.api.http.Status._
/**
* @author ram
*
*/
package object funnel {
type FunneledHeader = Option[String]
type FunneledBody = Option[String]
type FunnelResponseList = NonEmptyList[FunnelResponse]
type FunnelResponses = Option[FunnelResponseList]
object FunnelResponses {
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJValue(fres: FunnelResponses): JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import controllers.funnel.FunnelResponsesSerialization.{ writer => FunResponsesWriter }
toJSON(fres)(FunResponsesWriter)
}
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJson(fres: FunnelResponses, prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue(fres)))
} else {
compactRender(toJValue(fres))
}
def toTuple2(fres: FunnelResponses): List[Tuple2[String,String]] = {
(fres.flatMap { fres_list: FunnelResponseList =>
(fres_list.map { fre => (fre.code.toString,fre.msg) }.list).some
}).getOrElse(List(("000", "Done")))
}
def apply(f: FunnelResponse): FunnelResponses = FunnelResponses(nels(f))
def apply(f: FunnelResponseList): FunnelResponses = f.some
def apply(f: List[FunnelResponse]): FunnelResponses = f.toNel
def empty: FunnelResponses = Option.empty[FunnelResponseList]
}
implicit def req2FunnelBuilder[A](req: RequestWithAttributes[A]): FunnelRequestBuilder[A] = new FunnelRequestBuilder[A](req)
/**
* Broadly erros are categorized into
* 1. Authentication errors 2. Malformed Inputs 3. Service Errors 4. Resource Errors 5. JSON errors
* JSON erros aren't traked yet
*/
implicit class RichThrowable(thrownExp: Throwable) {
def fold[T](
cannotAuthError: CannotAuthenticateError => T,
malformedBodyError: MalformedBodyError => T,
malformedHeaderError: MalformedHeaderError => T,
serviceUnavailableError: ServiceUnavailableError => T,
resourceNotFound: ResourceItemNotFound => T,
anyError: Throwable => T): T = thrownExp match {
case a @ CannotAuthenticateError(_, _, _) => cannotAuthError(a)
case m @ MalformedBodyError(_, _, _) => malformedBodyError(m)
case h @ MalformedHeaderError(_, _, _) => malformedHeaderError(h)
case c @ ServiceUnavailableError(_, _, _) => serviceUnavailableError(c)
case r @ ResourceItemNotFound(_, _, _) => resourceNotFound(r)
case t @ _ => anyError(t)
}
}
implicit def err2FunnelResponse(hpret: HttpReturningError) = new FunnelResponse(hpret.code.getOrElse(BAD_REQUEST), hpret.msg, hpret.more.getOrElse(new String("none")), "Megam::Error", hpret.severity)
implicit def err2FunnelResponses(hpret: HttpReturningError) = hpret.errNel.map { err: Throwable =>
err.fold(a => new FunnelResponse(hpret.mkCode(a).getOrElse(BAD_REQUEST), hpret.mkMsg(a), hpret.mkMore(a), "Megam::Error", hpret.severity),
m => new FunnelResponse(hpret.mkCode(m).getOrElse(BAD_REQUEST), hpret.mkMsg(m), hpret.mkMore(m), "Megam::Error", hpret.severity),
h => new FunnelResponse(hpret.mkCode(h).getOrElse(BAD_REQUEST), hpret.mkMsg(h), hpret.mkMore(h), "Megam::Error", hpret.severity),
c => new FunnelResponse(hpret.mkCode(c).getOrElse(BAD_REQUEST), hpret.mkMsg(c), hpret.mkMore(c), "Megam::Error", hpret.severity),
r => new FunnelResponse(hpret.mkCode(r).getOrElse(BAD_REQUEST), hpret.mkMsg(r), hpret.mkMore(r), "Megam::Error", hpret.severity),
t => new FunnelResponse(hpret.mkCode(t).getOrElse(BAD_REQUEST), hpret.mkMsg(t), hpret.mkMore(t), "Megam::Error", hpret.severity))
}.some
implicit def funnelResponses2Json(fres: FunnelResponses): String = FunnelResponses.toJson(fres, true)
}
|
rajthilakmca/megam_play
|
test/tosca/ContiniousIntegrationSpec.scala
|
/*
** Copyright [2012-2013] [Megam Systems]
**
** 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 test.tosca
import org.specs2.mutable._
import org.specs2.Specification
import java.net.URL
import org.specs2.matcher.MatchResult
import org.specs2.execute.{ Result => SpecsResult }
import com.stackmob.newman.response.{ HttpResponse, HttpResponseCode }
import com.stackmob.newman._
import com.stackmob.newman.dsl._
import models.tosca._
import models.tosca.Domains
import test.{Context}
/**
* @author rajthilak
*
*/
class ContiniousIntegrationSpec extends Specification {
def is =
"ContiniousIntegrationSpec".title ^ end ^ """
ContiniousIntegrationSpec is the implementation that calls the megam_play API server with the /cis url to create ContiniousIntegration
""" ^ end ^
"The Client Should" ^
"Correctly do POST requests with a valid ContiniousIntegration name" ! Post.succeeds ^
//"Correctly do POST requests with an invalid URL" ! PostInvalidUrl.succeeds ^
//"Correctly do POST requests with an invalid body" ! PostInvalidBody.succeeds ^
//"Correctly do GET requests with a valid domains name" ! Get.succeeds ^
end
case object Post extends Context {
protected override def urlSuffix: String = "cis/content"
protected override def bodyToStick: Option[String] = {
val contentToEncode = "{\"scm\":\"github\",\"component_id\":\"COM1185521959144914944\" }"
Some(new String(contentToEncode))
}
protected override def headersOpt: Option[Map[String, String]] = None
private val post = POST(url)(httpClient)
.addHeaders(headers)
.addBody(body)
def succeeds: SpecsResult = {
val resp = execute(post)
resp.code must beTheSameResponseCodeAs(HttpResponseCode.Created)
}
}
/**
* test case for invalidUrl
*/
case object PostInvalidUrl extends Context {
protected override def urlSuffix: String = "cis/contentinvalidurl"
protected override def bodyToStick: Option[String] = {
val contentToEncode = "{\"scm\":\"github\",\"component_id\":\"COM1185521959144914944\" }"
Some(new String(contentToEncode))
}
protected override def headersOpt: Option[Map[String, String]] = None
private val post = POST(url)(httpClient)
.addHeaders(headers)
.addBody(body)
def succeeds: SpecsResult = {
val resp = execute(post)
resp.code must beTheSameResponseCodeAs(HttpResponseCode.NotFound)
}
}
/**
* test case for invalidBody
*/
case object PostInvalidBody extends Context {
protected override def urlSuffix: String = "cis/content"
protected override def bodyToStick: Option[String] = {
val contentToEncode = "{\"name1\":\"megam.org\"}"
Some(new String(contentToEncode))
}
protected override def headersOpt: Option[Map[String, String]] = None
private val post = POST(url)(httpClient)
.addHeaders(headers)
.addBody(body)
def succeeds: SpecsResult = {
val resp = execute(post)
resp.code must beTheSameResponseCodeAs(HttpResponseCode.ServiceUnavailable)
}
}
}
|
rajthilakmca/megam_play
|
app/models/tosca/package.scala
|
/*
** Copyright [2013-2014] [Megam Systems]
**
** 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 models
import scalaz._
import Scalaz._
import scalaz.NonEmptyList
import scalaz.NonEmptyList._
import models.json.tosca._
import net.liftweb.json._
import net.liftweb.json.scalaz.JsonScalaz._
import java.nio.charset.Charset
import controllers.Constants._
/**
* @author ram
*
*/
package object tosca {
type CSARLinkResults = NonEmptyList[Option[CSARLinkResult]]
object CSARLinkResults {
val emptyPC = List(Option.empty[CSARLinkResult])
def apply(m: CSARLinkResult): CSARLinkResults = nels(m.some)
def empty: CSARLinkResults = nel(emptyPC.head, emptyPC.tail)
}
type CSARResults = NonEmptyList[Option[CSARResult]]
object CSARResults {
val emptyPC = List(Option.empty[CSARResult])
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJValue(prres: CSARResults): JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.tosca.CSARResultsSerialization.{ writer => CSARResultsWriter }
toJSON(prres)(CSARResultsWriter)
}
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJson(nres: CSARResults, prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue(nres)))
} else {
compactRender(toJValue(nres))
}
def apply(m: CSARResult): CSARResults = nels(m.some)
def empty: CSARResults = nel(emptyPC.head, emptyPC.tail)
}
type AssembliesList = List[Assembly]
type ComponentsList = List[Component]
type AssembliesLists = NonEmptyList[Option[AssemblyResult]]
object AssembliesLists {
val emptyNR = List(Option.empty[AssemblyResult])
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJValue(nres: AssembliesLists): JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.tosca.AssembliesListsSerialization.{ writer => AssembliesListsWriter }
toJSON(nres)(AssembliesListsWriter)
}
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJson(nres: AssembliesLists, prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue(nres)))
} else {
compactRender(toJValue(nres))
}
def apply(m: Option[AssemblyResult]) = nels(m)
def apply(m: AssemblyResult): AssembliesLists = AssembliesLists(m.some)
def empty: AssembliesLists = nel(emptyNR.head, emptyNR.tail)
}
type AssembliesResults = NonEmptyList[Option[AssembliesResult]]
object AssembliesResults {
val emptyNR = List(Option.empty[AssembliesResult])
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJValue(nres: AssembliesResults): JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.tosca.AssembliesResultsSerialization.{ writer => AssembliesResultsWriter }
toJSON(nres)(AssembliesResultsWriter)
}
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJson(nres: AssembliesResults, prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue(nres)))
} else {
compactRender(toJValue(nres))
}
def apply(m: Option[AssembliesResult]) = nels(m)
def apply(m: AssembliesResult): AssembliesResults = AssembliesResults(m.some)
def empty: AssembliesResults = nel(emptyNR.head, emptyNR.tail)
}
type AssemblyLinks = List[String]
object AssemblyLinks {
val emptyRR = List("")
def toJValue(nres: AssemblyLinks): JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.tosca.AssemblyLinksSerialization.{ writer => AssemblyLinksWriter }
toJSON(nres)(AssemblyLinksWriter)
}
def fromJValue(jValue: JValue)(implicit charset: Charset = UTF8Charset): Result[AssemblyLinks] = {
import net.liftweb.json.scalaz.JsonScalaz.fromJSON
import models.json.tosca.AssemblyLinksSerialization.{ reader => AssemblyLinksReader }
fromJSON(jValue)(AssemblyLinksReader)
}
def toJson(nres: AssemblyLinks, prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue(nres)))
} else {
compactRender(toJValue(nres))
}
def apply(plansList: List[String]): AssemblyLinks = plansList
def empty: List[String] = emptyRR
}
type AssemblyResults = NonEmptyList[Option[AssemblyResult]]
object AssemblyResults {
val emptyNR = List(Option.empty[AssemblyResult])
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJValue(nres: AssemblyResults): JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.tosca.AssemblyResultsSerialization.{ writer => AssemblyResultsWriter }
toJSON(nres)(AssemblyResultsWriter)
}
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJson(nres: AssemblyResults, prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue(nres)))
} else {
compactRender(toJValue(nres))
}
def apply(m: Option[AssemblyResult]) = nels(m)
def apply(m: AssemblyResult): AssemblyResults = AssemblyResults(m.some)
def empty: AssemblyResults = nel(emptyNR.head, emptyNR.tail)
}
type ComponentLinks = List[String]
object ComponentLinks {
val emptyRR = List("")
def toJValue(nres: ComponentLinks): JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.tosca.ComponentLinksSerialization.{ writer => ComponentLinksWriter }
toJSON(nres)(ComponentLinksWriter)
}
def fromJValue(jValue: JValue)(implicit charset: Charset = UTF8Charset): Result[ComponentLinks] = {
import net.liftweb.json.scalaz.JsonScalaz.fromJSON
import models.json.tosca.ComponentLinksSerialization.{ reader => ComponentLinksReader }
fromJSON(jValue)(ComponentLinksReader)
}
def toJson(nres: ComponentLinks, prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue(nres)))
} else {
compactRender(toJValue(nres))
}
def apply(plansList: List[String]): ComponentLinks = plansList
def empty: List[String] = emptyRR
}
type ComponentsResults = NonEmptyList[Option[ComponentResult]]
object ComponentsResults {
val emptyNR = List(Option.empty[ComponentResult])
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJValue(nres: ComponentsResults): JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.tosca.ComponentsResultsSerialization.{ writer => ComponentsResultsWriter }
toJSON(nres)(ComponentsResultsWriter)
}
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJson(nres: ComponentsResults, prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue(nres)))
} else {
compactRender(toJValue(nres))
}
def apply(m: Option[ComponentResult]) = nels(m)
def apply(m: ComponentResult): ComponentsResults = ComponentsResults(m.some)
def empty: ComponentsResults = nel(emptyNR.head, emptyNR.tail)
}
type ComponentDesignInputsWires = List[String]
object ComponentDesignInputsWires {
val emptyRR = List("")
def toJValue(nres: ComponentDesignInputsWires): JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.tosca.ComponentDesignInputsWiresSerialization.{ writer => ComponentDesignInputsWiresWriter }
toJSON(nres)(ComponentDesignInputsWiresWriter)
}
def fromJValue(jValue: JValue)(implicit charset: Charset = UTF8Charset): Result[ComponentLinks] = {
import net.liftweb.json.scalaz.JsonScalaz.fromJSON
import models.json.tosca.ComponentDesignInputsWiresSerialization.{ reader => ComponentDesignInputsWiresReader }
fromJSON(jValue)(ComponentDesignInputsWiresReader)
}
def toJson(nres: ComponentLinks, prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue(nres)))
} else {
compactRender(toJValue(nres))
}
def apply(plansList: List[String]): ComponentDesignInputsWires = plansList
def empty: List[String] = emptyRR
}
type OrganizationsResults = NonEmptyList[Option[OrganizationsResult]]
object OrganizationsResults {
val emptyPC = List(Option.empty[OrganizationsResult])
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJValue(prres: OrganizationsResults): JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.tosca.OrganizationsResultsSerialization.{ writer => OrganizationsResultsWriter }
toJSON(prres)(OrganizationsResultsWriter)
}
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJson(nres: OrganizationsResults, prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue(nres)))
} else {
compactRender(toJValue(nres))
}
def apply(m: OrganizationsResult): OrganizationsResults = nels(m.some)
def empty: OrganizationsResults = nel(emptyPC.head, emptyPC.tail)
}
type DomainsResults = NonEmptyList[Option[DomainsResult]]
object DomainsResults {
val emptyPC = List(Option.empty[DomainsResult])
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJValue(prres: DomainsResults): JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.tosca.DomainsResultsSerialization.{ writer => DomainsResultsWriter }
toJSON(prres)(DomainsResultsWriter)
}
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJson(nres: DomainsResults, prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue(nres)))
} else {
compactRender(toJValue(nres))
}
def apply(m: DomainsResult): DomainsResults = nels(m.some)
def empty: DomainsResults = nel(emptyPC.head, emptyPC.tail)
}
type CloudSettingsList = List[CloudSetting]
object CloudSettingsList {
val emptyRR = List(CloudSetting.empty)
def toJValue(nres: CloudSettingsList): JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.tosca.CloudSettingsListSerialization.{ writer => CloudSettingsListWriter }
toJSON(nres)(CloudSettingsListWriter)
}
def fromJValue(jValue: JValue)(implicit charset: Charset = UTF8Charset): Result[CloudSettingsList] = {
import net.liftweb.json.scalaz.JsonScalaz.fromJSON
import models.json.tosca.CloudSettingsListSerialization.{ reader => CloudSettingsListReader }
fromJSON(jValue)(CloudSettingsListReader)
}
def toJson(nres: CloudSettingsList, prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue(nres)))
} else {
compactRender(toJValue(nres))
}
def apply(csList: List[CloudSetting]): CloudSettingsList = { println(csList); csList }
def empty: List[CloudSetting] = emptyRR
}
type CSWiresList = List[String]
object CSWiresList {
val emptyRR = List("")
def toJValue(nres: CSWiresList): JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.tosca.CSWiresListSerialization.{ writer => CSWiresListWriter }
toJSON(nres)(CSWiresListWriter)
}
def fromJValue(jValue: JValue)(implicit charset: Charset = UTF8Charset): Result[CSWiresList] = {
import net.liftweb.json.scalaz.JsonScalaz.fromJSON
import models.json.tosca.CSWiresListSerialization.{ reader => CSWiresListReader }
fromJSON(jValue)(CSWiresListReader)
}
def toJson(nres: CSWiresList, prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue(nres)))
} else {
compactRender(toJValue(nres))
}
def apply(plansList: List[String]): CSWiresList = plansList
def empty: List[String] = emptyRR
}
type PoliciesList = List[Policy]
object PoliciesList {
val emptyRR = List(Policy.empty)
def toJValue(nres: PoliciesList): JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.tosca.PoliciesListSerialization.{ writer => PoliciesListWriter }
toJSON(nres)(PoliciesListWriter)
}
def fromJValue(jValue: JValue)(implicit charset: Charset = UTF8Charset): Result[PoliciesList] = {
import net.liftweb.json.scalaz.JsonScalaz.fromJSON
import models.json.tosca.PoliciesListSerialization.{ reader => PoliciesListReader }
fromJSON(jValue)(PoliciesListReader)
}
def toJson(nres: PoliciesList, prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue(nres)))
} else {
compactRender(toJValue(nres))
}
def apply(plansList: List[Policy]): PoliciesList = plansList
def empty: List[Policy] = emptyRR
}
type MembersList = List[String]
object MembersList {
val emptyRR = List("")
def toJValue(nres: MembersList): JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.tosca.MembersListSerialization.{ writer => MembersListWriter }
toJSON(nres)(MembersListWriter)
}
def fromJValue(jValue: JValue)(implicit charset: Charset = UTF8Charset): Result[MembersList] = {
import net.liftweb.json.scalaz.JsonScalaz.fromJSON
import models.json.tosca.MembersListSerialization.{ reader => MembersListReader }
fromJSON(jValue)(MembersListReader)
}
def toJson(nres: MembersList, prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue(nres)))
} else {
compactRender(toJValue(nres))
}
def apply(plansList: List[String]): MembersList = plansList
def empty: List[String] = emptyRR
}
type OutputsList = List[Output]
object OutputsList {
val emptyRR = List(Output.empty)
def toJValue(nres: OutputsList): JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.tosca.OutputsListSerialization.{ writer => OutputsListWriter }
toJSON(nres)(OutputsListWriter)
}
def fromJValue(jValue: JValue)(implicit charset: Charset = UTF8Charset): Result[OutputsList] = {
import net.liftweb.json.scalaz.JsonScalaz.fromJSON
import models.json.tosca.OutputsListSerialization.{ reader => OutputsListReader }
fromJSON(jValue)(OutputsListReader)
}
def toJson(nres: OutputsList, prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue(nres)))
} else {
compactRender(toJValue(nres))
}
def apply(plansList: List[Output]): OutputsList = plansList
def empty: List[Output] = emptyRR
}
type ComponentOthers = List[ComponentOther]
object ComponentOthers {
val emptyRR = List(ComponentOther.empty)
def toJValue(nres: ComponentOthers): JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.tosca.ComponentOthersSerialization.{ writer => ComponentOthersWriter }
toJSON(nres)(ComponentOthersWriter)
}
def fromJValue(jValue: JValue)(implicit charset: Charset = UTF8Charset): Result[ComponentOthers] = {
import net.liftweb.json.scalaz.JsonScalaz.fromJSON
import models.json.tosca.ComponentOthersSerialization.{ reader => ComponentOthersReader }
fromJSON(jValue)(ComponentOthersReader)
}
def toJson(nres: ComponentOthers, prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue(nres)))
} else {
compactRender(toJValue(nres))
}
def apply(plansList: List[ComponentOther]): ComponentOthers = plansList
def empty: List[ComponentOther] = emptyRR
}
type ContiniousIntegrationResults = NonEmptyList[Option[ContiniousIntegrationResult]]
object ContiniousIntegrationResults {
val emptyPC = List(Option.empty[ContiniousIntegrationResult])
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJValue(prres: ContiniousIntegrationResults): JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.tosca.ContiniousIntegrationResultsSerialization.{ writer => ContiniousIntegrationResultsWriter }
toJSON(prres)(ContiniousIntegrationResultsWriter)
}
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJson(nres: ContiniousIntegrationResults, prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue(nres)))
} else {
compactRender(toJValue(nres))
}
def apply(m: ContiniousIntegrationResult): ContiniousIntegrationResults = nels(m.some)
def empty: ContiniousIntegrationResults = nel(emptyPC.head, emptyPC.tail)
}
}
|
rajthilakmca/megam_play
|
test/tosca/ComponentsSpec.scala
|
<reponame>rajthilakmca/megam_play<filename>test/tosca/ComponentsSpec.scala
/*
** Copyright [2013-2014] [Megam Systems]
**
** 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 test.tosca
import org.specs2.mutable._
import org.specs2.Specification
import java.net.URL
import org.specs2.matcher.MatchResult
import org.specs2.execute.{ Result => SpecsResult }
import com.stackmob.newman.response.{ HttpResponse, HttpResponseCode }
import com.stackmob.newman._
import com.stackmob.newman.dsl._
import models.tosca._
import models.tosca.Component
import test.{ Context }
/**
* @author rajthilak
*
*/
class ComponentsSpec extends Specification {
def is =
"ComponentsSpec".title ^ end ^ """
AssemblySpec is the implementation that calls the megam_play API server with the /assembly url
""" ^ end ^
"The Client Should" ^
"Correctly do GET requests with an valid Assembly ID" ! findByIDApp.succeeds ^
"Correctly do POST requests with an valid Assembly ID" ! updateApp.succeeds ^
end
case object findByIDApp extends Context {
protected override def urlSuffix: String = "components/COM1133824040297955328"
protected def headersOpt: Option[Map[String, String]] = None
private val get = GET(url)(httpClient)
.addHeaders(headers)
def succeeds = {
val resp = execute(get)
resp.code must beTheSameResponseCodeAs(HttpResponseCode.Ok)
}
}
case object updateApp extends Context {
protected override def urlSuffix: String = "components/update"
protected override def bodyToStick: Option[String] = {
val contentToEncode = "{" +
"\"id\": \"COM1139245887592202240\"," +
"\"name\":\"NettieMoore\"," +
"\"tosca_type\":\"tosca.web.redis\"," +
"\"requirements\":{" +
"\"host\":\"clouddefault1139222212843274240\"," +
"\"dummy\":\"\"" +
"}," +
"\"inputs\":{" +
"\"domain\":\"megam.co\"," +
"\"port\":\"6379\"," +
"\"username\":\"\"," +
"\"password\":\"\"," +
"\"version\":\"\"," +
"\"source\":\"\"," +
"\"design_inputs\":{" +
"\"id\":\"39bb18e7.c644e8\"," +
"\"x\":\"802\"," +
"\"y\":\"331\"," +
"\"z\":\"3f43bde9.c0bc42\"," +
"\"wires\":[\"cae50d7.f351af\"]" +
"}," +
"\"service_inputs\":{" +
"\"dbname\":\"\"," +
"\"dbpassword\":\"\"" +
"}," +
"\"ci\":{" +
"\"scm\":\"github\"," +
"\"ci\":\"true\"" +
"}}," +
"\"external_management_resource\":\"\"," +
"\"artifacts\":{" +
"\"artifact_type\":\"\"," +
"\"content\":\"\"," +
"\"artifact_requirements\":\"\"" +
"}," +
"\"related_components\":\"AntonioMcCormick.megam.co/TimothyHenderson\"," +
"\"operations\":{" +
"\"operation_type\":\"\"," +
"\"target_resource\":\"\"" +
"}," +
"\"others\":[{\"otherkey\":\"ci\",\"othervalue\":\"github\"}]," +
"\"created_at\":\"2014-10-29 14:06:39 +0000\"" +
"}"
Some(new String(contentToEncode))
}
protected override def headersOpt: Option[Map[String, String]] = None
private val post = POST(url)(httpClient)
.addHeaders(headers)
.addBody(body)
def succeeds: SpecsResult = {
val resp = execute(post)
resp.code must beTheSameResponseCodeAs(HttpResponseCode.Created)
}
}
}
|
rajthilakmca/megam_play
|
app/models/MarketPlaceAddons.scala
|
/*
** Copyright [2013-2014] [Megam Systems]
**
** 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 models
import scalaz._
import Scalaz._
import scalaz.effect.IO
import scalaz.EitherT._
import scalaz.Validation
//import scalaz.Validation.FlatMap._
import scalaz.NonEmptyList._
import scalaz.syntax.SemigroupOps
import org.megam.util.Time
import controllers.stack._
import controllers.Constants._
import controllers.funnel.FunnelErrors._
import models._
import models.riak._
import com.stackmob.scaliak._
import com.basho.riak.client.core.query.indexes.{RiakIndexes, StringBinIndex, LongIntIndex }
import com.basho.riak.client.core.util.{ Constants => RiakConstants }
import org.megam.common.riak.{ GSRiak, GunnySack }
import org.megam.common.uid.UID
import net.liftweb.json._
import net.liftweb.json.scalaz.JsonScalaz._
import java.nio.charset.Charset
/**
* @author rajthilak
*
*/
case class MarketPlaceAddonsInput(node_id: String, node_name: String, marketplace_id: String, config: MarketPlaceAddonsConfig) {
val json = "{\"node_id\":\"" + node_id + "\",\"node_name\":\"" + node_name + "\",\"marketplace_id\":\"" + marketplace_id + "\",\"config\":" + config + "}"
}
case class MarketPlaceAddonsResult(id: String, node_id: String, node_name: String, marketplace_id: String, config_id: String, created_at: String) {
def toJValue: JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.MarketPlaceAddonsResultSerialization
val preser = new MarketPlaceAddonsResultSerialization()
toJSON(this)(preser.writer)
}
def toJson(prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue))
} else {
compactRender(toJValue)
}
}
object MarketPlaceAddonsResult {
def fromJValue(jValue: JValue)(implicit charset: Charset = UTF8Charset): Result[MarketPlaceAddonsResult] = {
import net.liftweb.json.scalaz.JsonScalaz.fromJSON
import models.json.MarketPlaceAddonsResultSerialization
val preser = new MarketPlaceAddonsResultSerialization()
fromJSON(jValue)(preser.reader)
}
def fromJson(json: String): Result[MarketPlaceAddonsResult] = (Validation.fromTryCatch[net.liftweb.json.JValue] {
parse(json)
} leftMap { t: Throwable =>
UncategorizedError(t.getClass.getCanonicalName, t.getMessage, List())
}).toValidationNel.flatMap { j: JValue => fromJValue(j) }
}
object MarketPlaceAddons {
implicit val formats = DefaultFormats
private val riak = GWRiak( "addons")
implicit def MarketPlaceAddonsResultsSemigroup: Semigroup[MarketPlaceAddonsResults] = Semigroup.instance((f1, f2) => f1.append(f2))
val metadataKey = "marketplaceaddons"
val metadataVal = "MarketPlaceAddons Creation"
val bindex = "marketplaceaddons"
/**
* A private method which chains computation to make GunnySack when provided with an input json, email.
* parses the json, and converts it to nodeinput, if there is an error during parsing, a MalformedBodyError is sent back.
* After that flatMap on its success and the account id information is looked up.
* If the account id is looked up successfully, then yield the GunnySack object.
*/
private def mkGunnySack(email: String, input: String): ValidationNel[Throwable, Option[GunnySack]] = {
play.api.Logger.debug(("%-20s -->[%s]").format("models.MarketPlaceAddons", "mkGunnySack:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("email", email))
play.api.Logger.debug(("%-20s -->[%s]").format("json", input))
val addonInput: ValidationNel[Throwable, MarketPlaceAddonsInput] = (Validation.fromTryCatch[models.MarketPlaceAddonsInput] {
parse(input).extract[MarketPlaceAddonsInput]
} leftMap { t: Throwable => new MalformedBodyError(input, t.getMessage) }).toValidationNel //capture failure
play.api.Logger.debug(("%-20s -->[%s]").format("json-------->", addonInput))
for {
pdc <- addonInput
con <- (MarketPlaceAddonsConfiguration.create("{\"node_id\":\"" + pdc.node_id + "\",\"node_name\":\"" + pdc.node_name + "\",\"config\":" + pdc.config.json + "}") leftMap { t: NonEmptyList[Throwable] => t })
//TO-DO: Does the leftMap make sense ? To check during function testing, by removing it.
uir <- (UID(MConfig.snowflakeHost, MConfig.snowflakePort, "aon").get leftMap { ut: NonEmptyList[Throwable] => ut })
} yield {
//TO-DO: do we need a match for None on aor, and uir (confirm it during function testing).
val bvalue = Set(pdc.node_id)
val con_value = con.getOrElse(throw new ServiceUnavailableError(pdc.node_name, "Addon configuration create failed (or) not found. Retry again."))
val json = new MarketPlaceAddonsResult(uir.get._1 + uir.get._2, pdc.node_id, pdc.node_name, pdc.marketplace_id, con_value.id, Time.now.toString).toJson(false)
new GunnySack(uir.get._1 + uir.get._2, json, RiakConstants.CTYPE_TEXT_UTF8, None,
Map(metadataKey -> metadataVal), Map((bindex, bvalue))).some
}
}
/*
* create new Node with the 'name' of the node provide as input.
* A index name accountID will point to the "accounts" bucket
*/
def create(email: String, input: String): ValidationNel[Throwable, Option[Tuple3[Map[String, String], String, String]]] = {
play.api.Logger.debug(("%-20s -->[%s]").format("models.MarketPlaceAddons", "create:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("email", email))
play.api.Logger.debug(("%-20s -->[%s]").format("json", input))
(mkGunnySack(email, input) leftMap { err: NonEmptyList[Throwable] =>
new ServiceUnavailableError(input, (err.list.map(m => m.getMessage)).mkString("\n"))
}).toValidationNel.flatMap { gs: Option[GunnySack] =>
(riak.store(gs.get) leftMap { t: NonEmptyList[Throwable] => t }).
flatMap { maybeGS: Option[GunnySack] =>
val req_input = parse(input).extract[MarketPlaceAddonsInput]
val req_result = parse(gs.get.value).extract[MarketPlaceAddonsResult]
maybeGS match {
case Some(thatGS) => {
if (req_input.config.disaster.tohosts.equals("")) {
Tuple3(Map[String, String](("Id" -> req_result.config_id), ("Action" -> "addon"), ("Args" -> "Nah")), req_result.node_name, null).some.successNel[Throwable]
} else {
Tuple3(Map[String, String](("Id" -> req_result.config_id), ("Action" -> "addon"), ("Args" -> "Nah")), req_result.node_name, req_input.config.disaster.tohosts).some.successNel[Throwable]
}
}
case None => {
play.api.Logger.warn(("%-20s -->[%s]").format("MarketPlaceAddons.created success", "Scaliak returned => None. Thats OK."))
//(parse(gs.get.value).extract[MarketPlaceAddonsResult].some).successNel[Throwable];
if (req_input.config.disaster.tohosts.equals("")) {
Tuple3(Map[String, String](("Id" -> req_result.config_id), ("Action" -> "addon"), ("Args" -> "Nah")), req_result.node_name, null).some.successNel[Throwable]
} else {
Tuple3(Map[String, String](("Id" -> req_result.config_id), ("Action" -> "addon"), ("Args" -> "Nah")), req_result.node_name, req_input.config.disaster.tohosts).some.successNel[Throwable]
}
}
}
}
}
}
/**
* List all the app defns for a list of appdefns id for a particular node.
*/
def findByAddonId(addonidList: Option[List[String]]): ValidationNel[Throwable, MarketPlaceAddonsResults] = {
play.api.Logger.debug(("%-20s -->[%s]").format("models.MarketPlaceAddons", "findByNodeName:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("nodeNameList", addonidList))
(addonidList map {
_.map { addonid =>
play.api.Logger.debug(("%-20s -->[%s]").format("Add on id", addonid))
(riak.fetch(addonid) leftMap { t: NonEmptyList[Throwable] =>
new ServiceUnavailableError(addonid, (t.list.map(m => m.getMessage)).mkString("\n"))
}).toValidationNel.flatMap { xso: Option[GunnySack] =>
xso match {
case Some(xs) => {
//JsonScalaz.Error doesn't descend from java.lang.Error or Throwable. Screwy.
(MarketPlaceAddonsResult.fromJson(xs.value) leftMap
{ t: NonEmptyList[net.liftweb.json.scalaz.JsonScalaz.Error] =>
JSONParsingError(t)
}).toValidationNel.flatMap { j: MarketPlaceAddonsResult =>
play.api.Logger.debug(("%-20s -->[%s]").format("MarketPlaceAddonsresult", j))
Validation.success[Throwable, MarketPlaceAddonsResults](nels(j.some)).toValidationNel //screwy kishore, every element in a list ?
}
}
case None => {
Validation.failure[Throwable, MarketPlaceAddonsResults](new ResourceItemNotFound(addonid, "")).toValidationNel
}
}
}
} // -> VNel -> fold by using an accumulator or successNel of empty. +++ => VNel1 + VNel2
} map {
_.foldRight((MarketPlaceAddonsResults.empty).successNel[Throwable])(_ +++ _)
}).head //return the folded element in the head.
}
/*def findByNodeName(nodeNameList: Option[List[String]]): ValidationNel[Throwable, MarketPlaceAddonsResults] = {
play.api.Logger.debug(("%-20s -->[%s]").format("models.MarketPlaceAddons", "findByNodeName:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("nodeNameList", nodeNameList))
val res = eitherT[IO, NonEmptyList[Throwable], ValidationNel[Throwable, MarketPlaceAddonsResults]] {
((((for {
nelnr <- (Nodes.findByNodeName(nodeNameList) leftMap { t: NonEmptyList[Throwable] => t })
} yield {
//this is ugly, since what we receive from Nodes always contains one None. We need to filter
//that. This is justa hack for now. It calls for much more elegant soln.
(nelnr.list filter (nelwop => nelwop.isDefined) map { nelnor: Option[NodeResult] =>
(if (nelnor.isDefined) { //we only want to use the Some, ignore None. Hence a pattern match wasn't used here.
val bindex = ""
val bvalue = Set("")
val metadataVal = "Nodes-name"
play.api.Logger.debug(("%-20s -->[%s]").format("models.MarketPlaceAddons", nelnor))
new GunnySack("marketplaceaddons", nelnor.get.id, RiakConstants.CTYPE_TEXT_UTF8,
None, Map(metadataKey -> metadataVal), Map((bindex, bvalue)))
}).asInstanceOf[GunnySack]
})
}) leftMap { t: NonEmptyList[Throwable] => t } flatMap (({ gs: List[GunnySack] =>
gs.map { ngso: GunnySack => riak.fetchIndexByValue(ngso) }
}) map {
_.foldRight((List[String]()).successNel[Throwable])(_ +++ _)
})) map { nm: List[String] =>
play.api.Logger.debug("------------->" + nm)
(if (!nm.isEmpty) findByAddonId(nm.some) else
new ResourceItemNotFound(nodeNameList.map(m => m.mkString("[", ",", "]")).get, "application MarketPlaceAddons = nothing found.").failureNel[MarketPlaceAddonsResults])
}).disjunction).pure[IO]
}.run.map(_.validation).unsafePerformIO
res.getOrElse(new ResourceItemNotFound(nodeNameList.map(m => m.mkString("[", ",", "]")).get, "application MarketPlaceAddons = nothing found.").failureNel[MarketPlaceAddonsResults])
}*/
/*
* An IO wrapped finder using an email. Upon fetching the node results for an email,
* the nodeids are listed in bucket `Requests`.
* Using a "requestid" as key, return a list of ValidationNel[List[RequestResult]]
* Takes an email, and returns a Future[ValidationNel, List[Option[RequestResult]]]
*/
/*def findByEmail(email: String): ValidationNel[Throwable, MarketPlaceAddonsResults] = {
play.api.Logger.debug(("%-20s -->[%s]").format("models.MarketPlaceAddons", "findByEmail:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("email", email))
val res = eitherT[IO, NonEmptyList[Throwable], ValidationNel[Throwable, MarketPlaceAddonsResults]] {
((((for {
nelnr <- (Nodes.findByEmail(email) leftMap { t: NonEmptyList[Throwable] => t }) //captures failure on the left side, success on right ie the component before the (<-)
} yield {
play.api.Logger.debug(("%-20s -->[%s]").format("models.MarketPlaceAddons", "fetched nodes by email"))
//this is ugly, since what we receive from Nodes always contains one None. We need to filter
//that. This is justa hack for now. It calls for much more elegant soln.
(nelnr.list filter (nelwop => nelwop.isDefined) map { nelnor: Option[NodeResult] =>
val bindex = ""
val bvalue = Set("")
val metadataVal = "Nodes-name"
play.api.Logger.debug(("%-20s -->[%s]").format("models.Definition", nelnor))
new GunnySack("nodeId", nelnor.get.id, RiakConstants.CTYPE_TEXT_UTF8,
None, Map(metadataKey -> metadataVal), Map((bindex, bvalue)))
})
}) leftMap { t: NonEmptyList[Throwable] => t } flatMap (({ gs: List[GunnySack] =>
gs.map { ngso: GunnySack => riak.fetchIndexByValue(ngso) }
}) map {
_.foldLeft((List[String]()).successNel[Throwable])(_ +++ _)
})) map { nm: List[String] =>
(if (!nm.isEmpty) findByAddonId(nm.some) else
new ResourceItemNotFound(email, "definitions = nothing found.").failureNel[MarketPlaceAddonsResults])
}).disjunction).pure[IO]
}.run.map(_.validation).unsafePerformIO
play.api.Logger.debug(("%-20s -->[%s]").format("models.MarketPlaceAddons", res))
res.getOrElse(new ResourceItemNotFound(email, "definitions = nothing found.").failureNel[MarketPlaceAddonsResults])
}*/
}
|
rajthilakmca/megam_play
|
app/models/AppRequests.scala
|
/*
** Copyright [2012-2013] [Megam Systems]
**
** 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 models
import scalaz._
import Scalaz._
import scalaz.effect.IO
import scalaz.EitherT._
import scalaz.Validation
//import scalaz.Validation.FlatMap._
import scalaz.NonEmptyList._
import com.stackmob.scaliak._
import org.megam.common.riak.{ GSRiak, GunnySack }
import org.megam.common.uid.UID
import org.megam.util.Time
import net.liftweb.json._
import net.liftweb.json.scalaz.JsonScalaz._
import java.nio.charset.Charset
import com.basho.riak.client.core.query.indexes.{RiakIndexes, StringBinIndex, LongIntIndex }
import com.basho.riak.client.core.util.{ Constants => RiakConstants }
import models.cache._
import models.riak._
import controllers.funnel.FunnelErrors._
import controllers.Constants._
import controllers.stack.MConfig
import java.nio.charset.Charset
/**
* @author rajthilak
* This would actually be a link to the Nodes bucket. which would allow us to use link-walking
*/
case class AppRequestInput(app_id: String, app_name: String, action: String) {
val json = "\"app_id\":\"" + app_id + "\",\"app_name\":\"" + app_name + "\",\"action\":\"" + action + "\""
}
case class AppRequestResult(id: String, app_id: String, app_name: String, action: String, created_at: String) {
val json = "{\"id\": \"" + id + "\",\"app_id\": \"" + app_id + "\",\"app_name\":\"" + app_name + "\",\"action\":\"" + action + "\",\"created_at\":\"" + created_at + "\"}"
def toJValue: JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.AppRequestResultSerialization
val nrsser = new AppRequestResultSerialization()
toJSON(this)(nrsser.writer)
}
def toJson(prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue))
} else {
compactRender(toJValue)
}
}
object AppRequestResult {
def apply = new AppRequestResult(new String(), new String(), new String(), new String(), new String())
def fromJValue(jValue: JValue)(implicit charset: Charset = UTF8Charset): Result[AppRequestResult] = {
import net.liftweb.json.scalaz.JsonScalaz.fromJSON
import models.json.AppRequestResultSerialization
val nrsser = new AppRequestResultSerialization()
fromJSON(jValue)(nrsser.reader)
}
def fromJson(json: String): Result[AppRequestResult] = (Validation.fromTryCatch {
parse(json)
} leftMap { t: Throwable =>
UncategorizedError(t.getClass.getCanonicalName, t.getMessage, List())
}).toValidationNel.flatMap { j: JValue => fromJValue(j) }
}
object AppRequests {
implicit val formats = DefaultFormats
private val riak = GWRiak( "appreqs")
// implicit def AppRequestResultsSemigroup: Semigroup[AppRequestResults] = Semigroup.instance((f1, f2) => f1.append(f2))
val metadataKey = "AppRequest"
val metadataVal = "AppRequest Creation"
val bindex = "appId"
/**
* A private method which chains computation to make GunnySack for existing node when provided with an input json, Option[node_name].
* parses the json, and converts it to requestinput, if there is an error during parsing, a MalformedBodyError is sent back.
* After that flatMap on its success and the GunnySack object is built.
* If the node_name is send by the Node model. It then yield the GunnySack object.
*/
private def mkGunnySack(input: String): ValidationNel[Throwable, Option[GunnySack]] = {
play.api.Logger.debug(("%-20s -->[%s]").format("models.AppRequests", "mkGunnySack:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("models.AppRequests:json", input))
//Does this failure get propagated ? I mean, the input json parse fails ? I don't think so.
//This is a potential bug.
val ripNel: ValidationNel[Throwable, AppRequestInput] = (Validation.fromTryCatch {
parse(input).extract[AppRequestInput]
} leftMap { t: Throwable => new MalformedBodyError(input, t.getMessage) }).toValidationNel //capture failure
play.api.Logger.debug(("%-20s -->[%s]").format("models.AppRequests:rip", ripNel))
for {
rip <- ripNel
uir <- (UID(MConfig.snowflakeHost, MConfig.snowflakePort, "apr").get leftMap { ut: NonEmptyList[Throwable] => ut })
} yield {
val bvalue = Set(rip.app_id)
val json = "{\"id\": \"" + (uir.get._1 + uir.get._2) + "\"," + rip.json + ",\"created_at\":\"" + Time.now.toString + "\"}"
new GunnySack((uir.get._1 + uir.get._2), json, RiakConstants.CTYPE_TEXT_UTF8, None,
Map(metadataKey -> metadataVal), Map((bindex, bvalue))).some
}
}
/*
* create new AppRequest with the 'Nodename' of the node provide as input.
* A index name appreqID will point to the "appreqs" bucket
*/
def create(input: String): ValidationNel[Throwable, Option[Tuple2[Map[String,String], String]]] = {
play.api.Logger.debug(("%-20s -->[%s]").format("models.AppRequests", "create:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("json", input))
(mkGunnySack(input) leftMap { err: NonEmptyList[Throwable] =>
err
}).flatMap { gs: Option[GunnySack] =>
(riak.store(gs.get) leftMap { t: NonEmptyList[Throwable] => t }).
flatMap { maybeGS: Option[GunnySack] =>
val req_result = parse(gs.get.value).extract[AppRequestResult]
play.api.Logger.debug(("%-20s -->[%s]%nwith%n----%n%s").format("AppRequest.created successfully", "input", input))
maybeGS match {
case Some(thatGS) => Tuple2(Map[String,String](("Id" -> gs.get.key), ("Action" -> req_result.action), ("Args" -> "Nah")), req_result.app_name).some.successNel[Throwable]
case None => {
play.api.Logger.warn(("%-20s -->[%s]").format("AppRequest.created success", "Scaliak returned => None. Thats OK."))
Tuple2(Map[String,String](("Id" -> gs.get.key), ("Action" -> req_result.action), ("Args" -> "Nah")), req_result.app_name).some.successNel[Throwable]
}
}
}
}
}
}
|
rajthilakmca/megam_play
|
app/models/json/tosca/ComponentSerialization.scala
|
/*
** Copyright [2013-2014] [Megam Systems]
**
** 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 models.json.tosca
import scalaz._
import scalaz.NonEmptyList._
import scalaz.Validation
import scalaz.Validation._
import Scalaz._
import net.liftweb.json._
import net.liftweb.json.scalaz.JsonScalaz._
import java.util.Date
import java.nio.charset.Charset
import controllers.funnel.FunnelErrors._
import controllers.Constants._
import controllers.funnel.SerializationBase
import models.tosca.{ Component, ComponentRequirements, Artifacts, ComponentInputs, ExResource, ComponentOperations, ComponentOthers }
/**
* @author rajthilak
*
*/
class ComponentSerialization(charset: Charset = UTF8Charset) extends SerializationBase[Component] {
//protected val JSONClazKey = controllers.Constants.JSON_CLAZ
protected val NameKey = "name"
protected val ToscaTypeKey = "tosca_type"
protected val RequirementsKey = "requirements"
protected val InputsKey = "inputs"
protected val ExternalManagementResourceKey = "external_management_resource"
protected val ArtifactsKey = "artifacts"
protected val RelatedComponentsKey = "related_components"
protected val OperationsKey = "operations"
protected val OthersKey = "others"
override implicit val writer = new JSONW[Component] {
import ComponentRequirementsSerialization.{ writer => ComponentRequirementsWriter }
import ComponentOperationsSerialization.{ writer => ComponentOperationsWriter }
import ComponentInputsSerialization.{ writer => ComponentInputsWriter }
import ComponentOthersSerialization.{ writer => ComponentOthersWriter }
// import ExResourceSerialization.{ writer => ExResourceWriter }
import ArtifactsSerialization.{ writer => ArtifactsWriter }
override def write(h: Component): JValue = {
JObject(
// JField(JSONClazKey, toJSON("Megam::Component")) ::
JField(NameKey, toJSON(h.name)) ::
JField(ToscaTypeKey, toJSON(h.tosca_type)) ::
JField(RequirementsKey, toJSON(h.requirements)(ComponentRequirementsWriter)) ::
// JField(RequirementsKey, toJSON(h.requirements)) ::
JField(InputsKey, toJSON(h.inputs)(ComponentInputsWriter)) ::
// JField(ExternalManagementResourceKey, toJSON(h.external_management_resource)(ExResourceWriter)) ::
JField(ExternalManagementResourceKey, toJSON(h.external_management_resource)) ::
JField(ArtifactsKey, toJSON(h.artifacts)(ArtifactsWriter)) ::
JField(RelatedComponentsKey, toJSON(h.related_components)) ::
JField(OperationsKey, toJSON(h.operations)(ComponentOperationsWriter)) ::
JField(OthersKey, toJSON(h.others)(ComponentOthersWriter)) :: Nil)
}
}
override implicit val reader = new JSONR[Component] {
import ComponentRequirementsSerialization.{ reader => ComponentRequirementsReader }
import ComponentOperationsSerialization.{ reader => ComponentOperationsReader }
import ComponentInputsSerialization.{ reader => ComponentInputsReader }
import ComponentOthersSerialization.{ reader => ComponentOthersReader }
// import ExResourceSerialization.{ reader => ExResourceReader }
import ArtifactsSerialization.{ reader => ArtifactsReader }
override def read(json: JValue): Result[Component] = {
val nameField = field[String](NameKey)(json)
val toscatypeField = field[String](ToscaTypeKey)(json)
val requirementsField = field[ComponentRequirements](RequirementsKey)(json)(ComponentRequirementsReader)
// val requirementsField = field[String](RequirementsKey)(json)
val inputsField = field[ComponentInputs](InputsKey)(json)(ComponentInputsReader)
// val externalmanagementresourceField = field[String](ExternalManagementResourceKey)(json)(ExResourceReader)
val externalmanagementresourceField = field[String](ExternalManagementResourceKey)(json)
val artifactsField = field[Artifacts](ArtifactsKey)(json)(ArtifactsReader)
val relatedcomponentsField = field[String](RelatedComponentsKey)(json)
val operationsField = field[ComponentOperations](OperationsKey)(json)(ComponentOperationsReader)
val othersField = field[ComponentOthers](OthersKey)(json)(ComponentOthersReader)
(nameField |@| toscatypeField |@| requirementsField |@| inputsField |@| externalmanagementresourceField |@| artifactsField |@| relatedcomponentsField |@| operationsField |@| othersField) {
// (name: String, tosca_type: String, requirements: ComponentRequirements, inputs: ComponentInputs, external_management_resource: ExResource, artifacts: Artifacts, related_components: String, operations: ComponentOperations) =>
(name: String, tosca_type: String, requirements: ComponentRequirements, inputs: ComponentInputs, external_management_resource: String, artifacts: Artifacts, related_components: String, operations: ComponentOperations, others: ComponentOthers) =>
new Component(name, tosca_type, requirements, inputs, external_management_resource, artifacts, related_components, operations, others)
}
}
}
}
|
rajthilakmca/megam_play
|
app/models/tosca/ContiniousIntegration.scala
|
<reponame>rajthilakmca/megam_play<filename>app/models/tosca/ContiniousIntegration.scala
/*
** Copyright [2012-2013] [Megam Systems]
**
** 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 models.tosca
import scalaz._
import scalaz.syntax.SemigroupOps
import scalaz.NonEmptyList._
import scalaz.Validation._
import scalaz.effect.IO
import scalaz.EitherT._
import org.megam.util.Time
import Scalaz._
import controllers.stack._
import controllers.Constants._
import controllers.funnel.FunnelErrors._
import models.tosca._
import models.cache._
import models.riak._
import com.stackmob.scaliak._
import com.basho.riak.client.core.query.indexes.{ RiakIndexes, StringBinIndex, LongIntIndex }
import com.basho.riak.client.core.util.{ Constants => RiakConstants }
import org.megam.common.riak.{ GSRiak, GunnySack }
import org.megam.common.uid.UID
import net.liftweb.json._
import net.liftweb.json.scalaz.JsonScalaz._
import java.nio.charset.Charset
/**
* @author rajthilak
*
*/
case class ContiniousIntegrationInput(enable: String, scm: String, token: String, owner: String, component_id: String, assembly_id: String) {
val json = "{\"enable\":\"" + enable + "\",\"scm\":\"" + scm + "\",\"token\":\"" + token + "\",\"owner\":\"" + owner + "\",\"component_id\":\"" + component_id + "\",\"assembly_id\":\"" + assembly_id + "\"}"
}
case class ContiniousIntegrationResult(id: String, enable: String, scm: String, token: String, owner: String, component_id: String, assembly_id: String, created_at: String) {
def toJValue: JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.tosca.ContiniousIntegrationResultSerialization
val preser = new ContiniousIntegrationResultSerialization()
toJSON(this)(preser.writer) //where does this JSON from?
}
def toJson(prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue))
} else {
compactRender(toJValue)
}
}
object ContiniousIntegrationResult {
def fromJValue(jValue: JValue)(implicit charset: Charset = UTF8Charset): Result[ContiniousIntegrationResult] = {
import net.liftweb.json.scalaz.JsonScalaz.fromJSON
import models.json.tosca.ContiniousIntegrationResultSerialization
val preser = new ContiniousIntegrationResultSerialization()
fromJSON(jValue)(preser.reader)
}
def fromJson(json: String): Result[ContiniousIntegrationResult] = (Validation.fromTryCatch {
parse(json)
} leftMap { t: Throwable =>
UncategorizedError(t.getClass.getCanonicalName, t.getMessage, List())
}).toValidationNel.flatMap { j: JValue => fromJValue(j) }
}
object ContiniousIntegration {
implicit val formats = DefaultFormats
private val riak = GWRiak("cig")
implicit def ContiniousIntegrationResultsSemigroup: Semigroup[ContiniousIntegrationResults] = Semigroup.instance((f1, f2) => f1.append(f2))
//implicit def DomainsProcessedResultsSemigroup: Semigroup[NodeProcessedResults] = Semigroup.instance((f3, f4) => f3.append(f4))
val metadataKey = "ContiniousIntegration"
val metadataVal = "ContiniousIntegration Creation"
val bindex = "cig"
/**
* A private method which chains computation to make GunnySack when provided with an input json, email.
* parses the json, and converts it to domainsinput, if there is an error during parsing, a MalformedBodyError is sent back.
* After that flatMap on its success and the account id information is looked up.
* If the account id is looked up successfully, then yield the GunnySack object.
*/
private def mkGunnySack(email: String, input: String): ValidationNel[Throwable, Option[GunnySack]] = {
play.api.Logger.debug(("%-20s -->[%s]").format("models.tosca.ContiniousIntegration", "mkGunnySack:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("email", email))
play.api.Logger.debug(("%-20s -->[%s]").format("json", input))
val cigInput: ValidationNel[Throwable, ContiniousIntegrationInput] = (Validation.fromTryCatch {
parse(input).extract[ContiniousIntegrationInput]
} leftMap { t: Throwable => new MalformedBodyError(input, t.getMessage) }).toValidationNel //capture failure
for {
cig <- cigInput
uir <- (UID(MConfig.snowflakeHost, MConfig.snowflakePort, "cig").get leftMap { ut: NonEmptyList[Throwable] => ut })
} yield {
val bvalue = Set(cig.scm)
val json = new ContiniousIntegrationResult(uir.get._1 + uir.get._2, cig.enable, cig.scm, cig.token, cig.owner, cig.component_id, cig.assembly_id, Time.now.toString).toJson(false)
new GunnySack((uir.get._1 + uir.get._2), json, RiakConstants.CTYPE_TEXT_UTF8, None,
Map(metadataKey -> metadataVal), Map((bindex, bvalue))).some
}
}
/*
* create new organization item with the 'name' of the item provide as input.
* A index name organization name will point to the "organization bucket" bucket.
*/
def create(email: String, input: String): ValidationNel[Throwable, Option[Tuple2[String, String]]] = {
play.api.Logger.debug(("%-20s -->[%s]").format("models.ContiniousIntegration", "create:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("email", email))
play.api.Logger.debug(("%-20s -->[%s]").format("json", input))
(mkGunnySack(email, input) leftMap { err: NonEmptyList[Throwable] =>
new ServiceUnavailableError(input, (err.list.map(m => m.getMessage)).mkString("\n"))
}).toValidationNel.flatMap { gs: Option[GunnySack] =>
(riak.store(gs.get) leftMap { t: NonEmptyList[Throwable] => t }).
flatMap { maybeGS: Option[GunnySack] =>
maybeGS match {
case Some(thatGS) => Tuple2(thatGS.key, "").some.successNel[Throwable]
case None => {
play.api.Logger.warn(("%-20s -->[%s]").format("ContiniousIntegration.created success", "Scaliak returned => None. Thats OK."))
(gs.get.key, "").some.successNel[Throwable];
}
}
}
}
}
/* def findByName(domainsList: Option[List[String]]): ValidationNel[Throwable, DomainsResults] = {
play.api.Logger.debug(("%-20s -->[%s]").format("models.Domains", "findByName:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("domainsList", domainsList))
(domainsList map {
_.map { domainsName =>
play.api.Logger.debug(("%-20s -->[%s]").format("domainsName", domainsName))
(riak.fetch(domainsName) leftMap { t: NonEmptyList[Throwable] =>
new ServiceUnavailableError(domainsName, (t.list.map(m => m.getMessage)).mkString("\n"))
}).toValidationNel.flatMap { xso: Option[GunnySack] =>
xso match {
case Some(xs) => {
//JsonScalaz.Error doesn't descend from java.lang.Error or Throwable. Screwy.
(DomainsResult.fromJson(xs.value) leftMap
{ t: NonEmptyList[net.liftweb.json.scalaz.JsonScalaz.Error] =>
JSONParsingError(t)
}).toValidationNel.flatMap { j: DomainsResult =>
play.api.Logger.debug(("%-20s -->[%s]").format("domainsresult", j))
Validation.success[Throwable, DomainsResults](nels(j.some)).toValidationNel //screwy kishore, every element in a list ?
}
}
case None => {
Validation.failure[Throwable, DomainsResults](new ResourceItemNotFound(domainsName, "")).toValidationNel
}
}
}
} // -> VNel -> fold by using an accumulator or successNel of empty. +++ => VNel1 + VNel2
} map {
_.foldRight((DomainsResults.empty).successNel[Throwable])(_ +++ _)
}).head //return the folded element in the head.
}
*/
}
|
rajthilakmca/megam_play
|
app/models/json/tosca/CISerialization.scala
|
<reponame>rajthilakmca/megam_play<filename>app/models/json/tosca/CISerialization.scala<gh_stars>0
/*
** Copyright [2013-2014] [Megam Systems]
**
** 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 models.json.tosca
import scalaz._
import scalaz.NonEmptyList._
import scalaz.Validation
import scalaz.Validation._
import Scalaz._
import net.liftweb.json._
import net.liftweb.json.scalaz.JsonScalaz._
import java.util.Date
import java.nio.charset.Charset
import controllers.funnel.FunnelErrors._
import controllers.Constants._
import controllers.funnel.SerializationBase
import models.tosca.{ CI }
/**
* @author rajthilak
*
*/
object CISerialization extends SerializationBase[CI] {
protected val SCMKey = "scm"
protected val EnableKey = "enable"
protected val TokenKey = "token"
protected val OwnerKey = "owner"
override implicit val writer = new JSONW[CI] {
override def write(h: CI): JValue = {
JObject(
JField(SCMKey, toJSON(h.scm)) ::
JField(EnableKey, toJSON(h.enable)) ::
JField(TokenKey, toJSON(h.token)) ::
JField(OwnerKey, toJSON(h.owner)) ::
Nil)
}
}
override implicit val reader = new JSONR[CI] {
override def read(json: JValue): Result[CI] = {
val scmField = field[String](SCMKey)(json)
val enableField = field[String](EnableKey)(json)
val tokenField = field[String](TokenKey)(json)
val ownerField = field[String](OwnerKey)(json)
(scmField |@| enableField |@| tokenField |@| ownerField ) {
(scm: String, enable: String, token: String, owner: String) =>
new CI(scm, enable, token, owner)
}
}
}
}
|
rajthilakmca/megam_play
|
app/models/package.scala
|
<reponame>rajthilakmca/megam_play<gh_stars>0
/*
** Copyright [2013-2014] [Megam Systems]
**
** 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.
*/
import scalaz._
import Scalaz._
import scalaz.effect.IO
import scalaz.EitherT._
import scalaz.Validation
//import scalaz.Validation.FlatMap._
import scalaz.NonEmptyList._
import models.json._
import net.liftweb.json._
import net.liftweb.json.scalaz.JsonScalaz._
import java.nio.charset.Charset
import controllers.Constants._
/**
* @author rajthilak
*
*/
package object models {
type PredefResults = NonEmptyList[Option[PredefResult]]
object PredefResults {
val emptyPR = List(Option.empty[PredefResult])
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJValue(pres: PredefResults): JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.PredefResultsSerialization.{ writer => PredefResultsWriter }
toJSON(pres)(PredefResultsWriter)
}
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJson(pres: PredefResults, prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue(pres)))
} else {
compactRender(toJValue(pres))
}
def apply(m: PredefResult): PredefResults = nels(m.some)
def empty: PredefResults = nel(emptyPR.head, emptyPR.tail)
}
type PredefCloudResults = NonEmptyList[Option[PredefCloudResult]]
object PredefCloudResults {
val emptyPC = List(Option.empty[PredefCloudResult])
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJValue(prres: PredefCloudResults): JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.PredefCloudResultsSerialization.{ writer => PredefCloudResultsWriter }
toJSON(prres)(PredefCloudResultsWriter)
}
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJson(nres: PredefCloudResults, prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue(nres)))
} else {
compactRender(toJValue(nres))
}
def apply(m: PredefCloudResult): PredefCloudResults = nels(m.some)
def empty: PredefCloudResults = nel(emptyPC.head, emptyPC.tail)
}
type RequestResults = NonEmptyList[Option[RequestResult]]
object RequestResults {
val emptyRR = List(Option.empty[RequestResult])
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJValue(nres: RequestResults): JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.RequestResultsSerialization.{ writer => RequestResultsWriter }
toJSON(nres)(RequestResultsWriter)
}
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJson(nres: RequestResults, prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue(nres)))
} else {
compactRender(toJValue(nres))
}
def apply(m: Option[RequestResult]) = nels(m)
def apply(m: RequestResult): RequestResults = RequestResults(m.some)
def empty: RequestResults = nel(emptyRR.head, emptyRR.tail)
}
implicit def transformPredefResults2Json(pres: PredefResults): Option[String] = PredefResults.toJson(pres, true).some
implicit def transformPredefCloudResults22Json(prres: PredefCloudResults): Option[String] = PredefCloudResults.toJson(prres, true).some
type CloudToolSettingResults = NonEmptyList[Option[CloudToolSettingResult]]
object CloudToolSettingResults {
val emptyPC = List(Option.empty[CloudToolSettingResult])
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJValue(prres: CloudToolSettingResults): JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.CloudToolSettingResultsSerialization.{ writer => CloudToolSettingResultsWriter }
toJSON(prres)(CloudToolSettingResultsWriter)
}
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJson(nres: CloudToolSettingResults, prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue(nres)))
} else {
compactRender(toJValue(nres))
}
def apply(m: CloudToolSettingResult): CloudToolSettingResults = nels(m.some)
def empty: CloudToolSettingResults = nel(emptyPC.head, emptyPC.tail)
}
type SshKeyResults = NonEmptyList[Option[SshKeyResult]]
object SshKeyResults {
val emptyPC = List(Option.empty[SshKeyResult])
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJValue(prres: SshKeyResults): JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.SshKeyResultsSerialization.{ writer => SshKeyResultsWriter }
toJSON(prres)(SshKeyResultsWriter)
}
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJson(nres: SshKeyResults, prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue(nres)))
} else {
compactRender(toJValue(nres))
}
def apply(m: SshKeyResult): SshKeyResults = nels(m.some)
def empty: SshKeyResults = nel(emptyPC.head, emptyPC.tail)
}
type MarketPlaceResults = NonEmptyList[Option[MarketPlaceResult]]
object MarketPlaceResults {
val emptyPC = List(Option.empty[MarketPlaceResult])
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJValue(prres: MarketPlaceResults): JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.MarketPlaceResultsSerialization.{ writer => MarketPlaceResultsWriter }
toJSON(prres)(MarketPlaceResultsWriter)
}
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJson(nres: MarketPlaceResults, prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue(nres)))
} else {
compactRender(toJValue(nres))
}
def apply(m: MarketPlaceResult): MarketPlaceResults = nels(m.some)
def empty: MarketPlaceResults = nel(emptyPC.head, emptyPC.tail)
}
type MarketPlaceAddonsResults = NonEmptyList[Option[MarketPlaceAddonsResult]]
object MarketPlaceAddonsResults {
val emptyRR = List(Option.empty[MarketPlaceAddonsResult])
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJValue(nres: MarketPlaceAddonsResults): JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.MarketPlaceAddonsResultsSerialization.{ writer => MarketPlaceAddonsResultsWriter }
toJSON(nres)(MarketPlaceAddonsResultsWriter)
}
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJson(nres: MarketPlaceAddonsResults, prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue(nres)))
} else {
compactRender(toJValue(nres))
}
def apply(m: Option[MarketPlaceAddonsResult]) = nels(m)
def apply(m: MarketPlaceAddonsResult): MarketPlaceAddonsResults = MarketPlaceAddonsResults(m.some)
def empty: MarketPlaceAddonsResults = nel(emptyRR.head, emptyRR.tail)
}
type MarketPlaceAddonsConfigurationResults = NonEmptyList[Option[MarketPlaceAddonsConfigurationResult]]
object MarketPlaceAddonsConfigurationResults {
val emptyRR = List(Option.empty[MarketPlaceAddonsConfigurationResult])
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJValue(nres: MarketPlaceAddonsConfigurationResults): JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.MarketPlaceAddonsConfigurationResultsSerialization.{ writer => MarketPlaceAddonsConfigurationResultsWriter }
toJSON(nres)(MarketPlaceAddonsConfigurationResultsWriter)
}
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJson(nres: MarketPlaceAddonsConfigurationResults, prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue(nres)))
} else {
compactRender(toJValue(nres))
}
def apply(m: Option[MarketPlaceAddonsConfigurationResult]) = nels(m)
def apply(m: MarketPlaceAddonsConfigurationResult): MarketPlaceAddonsConfigurationResults = MarketPlaceAddonsConfigurationResults(m.some)
def empty: MarketPlaceAddonsConfigurationResults = nel(emptyRR.head, emptyRR.tail)
}
type MarketPlacePlans = List[MarketPlacePlan]
object MarketPlacePlans {
val emptyRR = List(MarketPlacePlan.empty)
def toJValue(nres: MarketPlacePlans): JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.MarketPlacePlansSerialization.{ writer => MarketPlacePlansWriter }
toJSON(nres)(MarketPlacePlansWriter)
}
def fromJValue(jValue: JValue)(implicit charset: Charset = UTF8Charset): Result[MarketPlacePlans] = {
import net.liftweb.json.scalaz.JsonScalaz.fromJSON
import models.json.MarketPlacePlansSerialization.{ reader => MarketPlacePlansReader }
fromJSON(jValue)(MarketPlacePlansReader)
}
def toJson(nres: MarketPlacePlans, prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue(nres)))
} else {
compactRender(toJValue(nres))
}
def apply(plansList: List[MarketPlacePlan]): MarketPlacePlans = plansList
def empty: List[MarketPlacePlan] = emptyRR
}
type AppRequestResults = NonEmptyList[Option[AppRequestResult]]
object AppRequestResults {
val emptyPC = List(Option.empty[AppRequestResult])
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJValue(prres: AppRequestResults): JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.AppRequestResultsSerialization.{ writer => AppRequestResultsWriter }
toJSON(prres)(AppRequestResultsWriter)
}
//screwy. you pass an instance. may be FunnelResponses needs be to a case class
def toJson(nres: AppRequestResults, prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue(nres)))
} else {
compactRender(toJValue(nres))
}
def apply(m: AppRequestResult): AppRequestResults = nels(m.some)
def empty: AppRequestResults = nel(emptyPC.head, emptyPC.tail)
}
}
|
rajthilakmca/megam_play
|
app/models/tosca/CSARJson.scala
|
/*
** Copyright [2013-2014] [Megam Systems]
**
** 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 models.tosca
import scalaz._
import Scalaz._
import scalaz.effect.IO
import scalaz.EitherT._
import scalaz.Validation
//import scalaz.Validation.FlatMap._
import scalaz.NonEmptyList._
import scalaz.syntax.SemigroupOps
import org.megam.util.Time
import controllers.stack._
import controllers.Constants._
import controllers.funnel.FunnelErrors._
import models._
import models.cache._
import models.riak._
import com.stackmob.scaliak._
import com.basho.riak.client.core.query.indexes.{ RiakIndexes, StringBinIndex, LongIntIndex }
import com.basho.riak.client.core.util.{ Constants => RiakConstants }
import org.megam.common.riak.{ GSRiak, GunnySack }
import org.megam.common.uid.UID
import net.liftweb.json._
import net.liftweb.json.scalaz.JsonScalaz._
import java.nio.charset.Charset
import scala.collection.JavaConversions._
import models.cache._
import org.yaml.snakeyaml.Yaml
import scala.collection.mutable.LinkedHashMap
import scala.collection.mutable.ListBuffer
import java.util.ArrayList
import scala.util.control.Breaks._
/**
* @author rajthilak
*
*/
case class CSARListOutput(key: String, value: String) {
val json = "{\"key\":\"" + key + "\",\"value\":\"" + value + "\"}"
val outputkey = key
val outputvalue = value
}
case class CSARPolicyOutput(key: String, value: Any) {
// val json = "{\"key\":\"" + key + "\",\"value\":" + value + "}"
val policykey = key
val policyvalue = value
}
object CSARJson {
implicit val formats = DefaultFormats
def toJson(input: String): ValidationNel[Throwable, String] = {
play.api.Logger.debug(("%-20s -->[%s]").format("tosca.CSARs", "CSAR to JSON"))
val csarInput: Map[String, String] = mapAsScalaMap[String, String](new Yaml().load(input).asInstanceOf[java.util.Map[String, String]]).toMap
var a = "{\"tosca_definitions_version\":\"tosca_simple_yaml_1_0\",\"description\":\"Template for deploying a two-tier application servers on two\"}";
val inputsList = scala.collection.mutable.MutableList[String]()
csarInput.get("inputs") match {
case Some(thatGS) =>
if (thatGS.asInstanceOf[AnyRef].getClass.getSimpleName == "LinkedHashMap") {
val linkinput: Map[String, String] = mapAsScalaMap[String, String](thatGS.asInstanceOf[java.util.Map[String, String]]).toMap
val cc = linkinput foreach {
case (lkey, lvalue) =>
inputsList += "{\"key\":\"" + lkey + "\", \"value\":\"" + lvalue + "\"}"
}
}
case None => ""
}
val componentList = scala.collection.mutable.MutableList[scala.collection.mutable.MutableList[String]]()
csarInput.get("node_templates") match {
case Some(thatGS) =>
val csarInput1: Map[String, String] = mapAsScalaMap[String, String](thatGS.asInstanceOf[java.util.Map[String, String]]).toMap
csarInput1 foreach {
case (key, value) =>
componentList += createComponentArray(key, value)
}
case None => ""
}
val policylist = scala.collection.mutable.MutableList[CSARPolicyOutput]()
csarInput.get("group") match {
case Some(thatGS) =>
val csarInput1: Map[String, String] = mapAsScalaMap[String, String](thatGS.asInstanceOf[java.util.Map[String, String]]).toMap
csarInput1 foreach {
case (key, value) =>
val csarInput2: Map[String, String] = mapAsScalaMap[String, String](value.asInstanceOf[java.util.Map[String, String]]).toMap
csarInput2 foreach {
case (key2, value2) =>
if (key2 == "policies") {
val tlist = value2.asInstanceOf[java.util.ArrayList[String]].toList.size()
for (i <- 0 to tlist) {
if (i < tlist) {
val data = value2.asInstanceOf[java.util.ArrayList[Any]].toList(i)
val policydata: Map[String, String] = mapAsScalaMap[String, String](data.asInstanceOf[java.util.Map[String, String]]).toMap
policydata foreach {
case (datakey, datavalue) =>
if (datakey == "my_placement_policy") {
csarInput2 foreach {
case (memkey, memvalue) =>
if (memkey == "members") {
policylist += new CSARPolicyOutput(key, memvalue)
}
}
}
}
}
}
}
}
}
case None => play.api.Logger.debug("-------***************None case--------------")
}
val afterFitComponents: scala.collection.mutable.MutableList[Component] = componentInputsBuilder(inputsList, componentList)
val afterFitAssembly: scala.collection.mutable.MutableList[Assembly] = assemblyBuilder(afterFitComponents, policylist)
val afterFitAssemblies: String = assembliesBuilder(afterFitAssembly)
Validation.success[Throwable, String](afterFitAssemblies).toValidationNel
}
def createComponentArray(key: String, value: Any): scala.collection.mutable.MutableList[String] = {
var i = 0;
var j = 0;
val list = scala.collection.mutable.MutableList[String]()
play.api.Logger.debug(("%-20s -->[%s]").format("tosca.CSARs Parse Hash", "CSAR to JSON"))
list += "{\"key\":\"name\", \"value\":\"" + key + "\"}"
val csarInput1: Map[String, String] = mapAsScalaMap[String, String](value.asInstanceOf[java.util.Map[String, String]]).toMap
val cc = csarInput1 foreach {
case (cckey, ccvalue) =>
if (ccvalue != null) {
if (ccvalue.asInstanceOf[AnyRef].getClass.getSimpleName == "String") {
list += "{\"key\":\"" + cckey + "\", \"value\":\"" + ccvalue + "\"}"
}
if (ccvalue.asInstanceOf[AnyRef].getClass.getSimpleName == "ArrayList") {
val tlist = ccvalue.asInstanceOf[java.util.ArrayList[String]].toList.size()
val resultList = scala.collection.mutable.MutableList[String]()
for (i <- 0 to tlist) {
if (i < tlist) {
val rlist: scala.collection.mutable.MutableList[String] = parseLinkedHashMap(cckey, ccvalue.asInstanceOf[java.util.ArrayList[String]].toList(i), resultList)
for (j <- 0 to rlist.size()) {
if (j < rlist.size()) {
list += rlist(j)
}
}
}
}
}
if (ccvalue.asInstanceOf[AnyRef].getClass.getSimpleName == "LinkedHashMap") {
val linkinput: Map[String, String] = mapAsScalaMap[String, String](ccvalue.asInstanceOf[java.util.Map[String, String]]).toMap
val cc = linkinput foreach {
case (lkey, lvalue) =>
list += "{\"key\":\"" + lkey + "\", \"value\":\"" + lvalue + "\"}"
}
}
}
}
list
}
def componentInputsBuilder(inputsList: scala.collection.mutable.MutableList[String], componentList: scala.collection.mutable.MutableList[scala.collection.mutable.MutableList[String]]): scala.collection.mutable.MutableList[Component] = {
val duplicateComponentList: scala.collection.mutable.MutableList[scala.collection.mutable.MutableList[String]] = componentList
val cc: scala.collection.mutable.MutableList[Component] = componentList.map {
case (lvalue) =>
val valu = new Component(getValue("name", lvalue), getValue("type", lvalue), new ComponentRequirements(getValue("host", lvalue), ""),
new ComponentInputs(getValue("domain", lvalue), "", "", "", "", getValue("source", lvalue),
new DesignInputs("", "", "", "", ComponentDesignInputsWires.empty), new ServiceInputs("", ""), CI.empty),
"", new Artifacts("", "", ""),
"", new ComponentOperations("", ""), ComponentOthers.empty)
valu
}
return cc
}
def assemblyBuilder(componentList: scala.collection.mutable.MutableList[Component], policyList: scala.collection.mutable.MutableList[CSARPolicyOutput]): scala.collection.mutable.MutableList[Assembly] = {
val assemblylist = scala.collection.mutable.MutableList[Assembly]()
if (policyList.size() > 0) {
val plist = new ListBuffer[String]()
policyList foreach {
case (plistvalue) =>
val tlist = plistvalue.policyvalue.asInstanceOf[java.util.ArrayList[String]].toList.size()
for (i <- 0 to tlist) {
if (i < tlist) {
plist += plistvalue.policyvalue.asInstanceOf[java.util.ArrayList[String]].toList(i)
}
}
}
policyList foreach {
case (pvalue) =>
val clist = new ListBuffer[Component]()
val tlist = pvalue.policyvalue.asInstanceOf[java.util.ArrayList[String]].toList.size()
for (i <- 0 to tlist) {
if (i < tlist) {
componentList foreach {
case (component) =>
if (component.name == pvalue.policyvalue.asInstanceOf[java.util.ArrayList[String]].toList(i)) {
clist += component
}
}
}
}
assemblylist += new Assembly(pvalue.policykey, clist.toList, PoliciesList.empty, "", "", OutputsList.empty, "")
}
componentList foreach {
case (cvalue) =>
var flag = false
for (i <- 0 to plist.size()) {
if (i < plist.size()) {
if (plist(i) == cvalue.name) {
flag = true
}
}
}
if (flag != true) {
assemblylist += new Assembly(getRandomName(), List(cvalue), PoliciesList.empty, "", "", OutputsList.empty, "")
}
}
} else {
componentList foreach {
case (cvalue) =>
assemblylist += new Assembly(getRandomName(), List(cvalue), PoliciesList.empty, "", "", OutputsList.empty, "")
}
}
return assemblylist
}
def assembliesBuilder(assemblyList: scala.collection.mutable.MutableList[Assembly]): String = {
var assembly_lists = new ListBuffer[Assembly]()
for (assembly <- assemblyList) {
assembly_lists += assembly
}
val cc: String = new AssembliesInput(getRandomName(), assembly_lists.toList, AssembliesInputs.empty).json
return cc
}
def parseLinkedHashMap(checkKey: String, mapvalue: Any, resultList: scala.collection.mutable.MutableList[String]): scala.collection.mutable.MutableList[String] = {
val csarInput1: Map[String, String] = mapAsScalaMap[String, String](mapvalue.asInstanceOf[java.util.Map[String, String]]).toMap
csarInput1.map {
case (key, value) =>
if (value.asInstanceOf[AnyRef].getClass.getSimpleName == "String") {
resultList += "{\"key\":\"" + key + "\", \"value\":\"" + value + "\"}"
}
if (value.asInstanceOf[AnyRef].getClass.getSimpleName == "LinkedHashMap") {
parseLinkedHashMap(key, value, resultList)
}
}
return resultList
}
def getValue(key: String, value: scala.collection.mutable.MutableList[String]): String = {
var str = ""
value foreach {
case (lvalue) =>
val parsedValue = parse(lvalue).extract[CSARListOutput]
if (key == parsedValue.outputkey) {
str = parsedValue.outputvalue
}
}
str
}
def getRandomName(): String = {
val random = new scala.util.Random
val alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"
val s = Stream.continually(random.nextInt(alphabet.size)).map(alphabet).take(10).mkString
return s
}
/* def createComponent(key: String, value: Any): String = {
play.api.Logger.debug(("%-20s -->[%s]").format("tosca.CSARs create component", "CSAR to JSON"))
val csarInput1: Map[String, String] = mapAsScalaMap[String, String](value.asInstanceOf[java.util.Map[String, String]]).toMap
val valu = new Component(key, parseOption(csarInput1.get("type")), new ComponentRequirements(parseHash("host", csarInput1.get("requirements")), ""),
new ComponentInputs(parseHash("domain", csarInput1.get("requirements")), "port", "username", "password", "version", "source",
new DesignInputs("id", "x", "y", "z", ComponentDesignInputsWires.empty), new ServiceInputs("dbname", "dbpassword")),
"external_management_resource", new Artifacts("artifact_type", "content", "artifact_requirements"),
"related_components", new ComponentOperations("operation_type", "target_resource")).json
valu
}
def parseArrayList(key: String, value: String): String = {
play.api.Logger.debug("-------value--------------" + value.asInstanceOf[AnyRef].getClass.getSimpleName)
val tlist = value.asInstanceOf[java.util.ArrayList[String]].toList.size()
for (i <- 0 to tlist) {
// play.api.Logger.debug("---------------------" + parseLinkedHashMap(key, value.asInstanceOf[java.util.ArrayList[String]].toList(i)))
play.api.Logger.debug("---------------------" + value.asInstanceOf[java.util.ArrayList[String]].toList(i).asInstanceOf[AnyRef].getClass.getSimpleName)
}
play.api.Logger.debug("---------------------" + value.asInstanceOf[java.util.ArrayList[String]].toList.size())
""
// case None => ""
}
// }
def parseHash(key: String, value: Option[String]): String = {
play.api.Logger.debug(("%-20s -->[%s]").format("tosca.CSARs Parse Hash", "CSAR to JSON"))
parseOptionAny(key, value)
val csarInput1: Map[String, String] = mapAsScalaMap[String, String](value.asInstanceOf[java.util.Map[String, String]]).toMap
parseOption(csarInput1.get(key))
}
def parseOption(value: Option[String]): String = {
value match {
case Some(thatGS) => thatGS
case None => ""
}
}
/* def parseLinkedHashMap(checkKey: String, value: Any): String = {
val csarInput1: Map[String, String] = mapAsScalaMap[String, String](value.asInstanceOf[java.util.Map[String, String]]).toMap
val cc = csarInput1 foreach {
case (key, value) =>
if (checkKey == key) {
return value
}
}
return ""
}*/
def parseOptionAny(key: String, value: Option[String]): String = {
play.api.Logger.debug("-------value--------------" + value.asInstanceOf[AnyRef].getClass.getSimpleName)
value match {
case Some(thatGS) =>
val tlist = thatGS.asInstanceOf[java.util.ArrayList[String]].toList.size()
for (i <- 0 to tlist) {
// play.api.Logger.debug("---------------------" + parseLinkedHashMap(key, thatGS.asInstanceOf[java.util.ArrayList[String]].toList(i)))
play.api.Logger.debug("---------------------" + thatGS.asInstanceOf[java.util.ArrayList[String]].toList(i).asInstanceOf[AnyRef].getClass.getSimpleName)
}
play.api.Logger.debug("---------------------" + thatGS.asInstanceOf[java.util.ArrayList[String]].toList.size())
""
case None => ""
}
} */
}
|
rajthilakmca/megam_play
|
app/models/json/RequestResultSerialization.scala
|
/*
** Copyright [2013-2014] [Megam Systems]
**
** 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 models.json
import scalaz._
import scalaz.NonEmptyList._
import scalaz.Validation
import scalaz.Validation._
import Scalaz._
import net.liftweb.json._
import net.liftweb.json.scalaz.JsonScalaz._
import java.util.Date
import java.nio.charset.Charset
import controllers.funnel.FunnelErrors._
import controllers.Constants._
import controllers.funnel.SerializationBase
import models.{RequestResult}
/**
* @author ram
*
*/
class RequestResultSerialization(charset: Charset = UTF8Charset) extends SerializationBase[RequestResult] {
protected val JSONClazKey = controllers.Constants.JSON_CLAZ
protected val IdKey = "id"
protected val NodeIDKey = "node_id"
protected val NodeNameKey = "node_name"
protected val ReqTypeKey = "req_type"
protected val CreatedAtKey ="created_at"
override implicit val writer = new JSONW[RequestResult] {
override def write(h: RequestResult): JValue = {
JObject(
JField(IdKey, toJSON(h.id)) ::
JField(NodeIDKey, toJSON(h.node_id)) ::
JField(JSONClazKey, toJSON("Megam::Request")) ::
JField(NodeNameKey, toJSON(h.node_name)) ::
JField(ReqTypeKey, toJSON(h.req_type)) ::
JField(CreatedAtKey, toJSON(h.created_at)) :: Nil)
}
}
override implicit val reader = new JSONR[RequestResult] {
override def read(json: JValue): Result[RequestResult] = {
val idField = field[String](IdKey)(json)
val nodeIdField = field[String](NodeIDKey)(json)
val nodeNameField = field[String](NodeNameKey)(json)
val reqtypeField = field[String](ReqTypeKey)(json)
val createdAtField = field[String](CreatedAtKey)(json)
(idField |@| nodeIdField |@| nodeNameField |@| reqtypeField |@| createdAtField) {
(id: String, node_id: String, node_name: String, req_type: String, created_at: String) =>
new RequestResult(id, node_id, node_name, req_type, created_at)
}
}
}
}
|
rajthilakmca/megam_play
|
app/models/json/tosca/ServiceInputsSerialization.scala
|
/*
** Copyright [2013-2014] [Megam Systems]
**
** 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 models.json.tosca
import scalaz._
import scalaz.NonEmptyList._
import scalaz.Validation
import scalaz.Validation._
import Scalaz._
import net.liftweb.json._
import net.liftweb.json.scalaz.JsonScalaz._
import java.util.Date
import java.nio.charset.Charset
import controllers.funnel.FunnelErrors._
import controllers.Constants._
import controllers.funnel.SerializationBase
import models.tosca.{ ServiceInputs }
/**
* @author rajthilak
*
*/
object ServiceInputsSerialization extends SerializationBase[ServiceInputs] {
protected val DBNameKey = "dbname"
protected val DBPasswordKey = "dbpassword"
override implicit val writer = new JSONW[ServiceInputs] {
override def write(h: ServiceInputs): JValue = {
JObject(
JField(DBNameKey, toJSON(h.dbname)) ::
JField(DBPasswordKey, toJSON(h.dbpassword)) ::
Nil)
}
}
override implicit val reader = new JSONR[ServiceInputs] {
override def read(json: JValue): Result[ServiceInputs] = {
val dbnameField = field[String](DBNameKey)(json)
val dbpasswordField = field[String](DBPasswordKey)(json)
(dbnameField |@| dbpasswordField ) {
(dbname: String, dbpassword: String) =>
new ServiceInputs(dbname, dbpassword)
}
}
}
}
|
rajthilakmca/megam_play
|
app/models/json/tosca/ComponentOthersSerialization.scala
|
/*
** Copyright [2013-2014] [Megam Systems]
**
** 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 models.json.tosca
import scalaz._
import scalaz.NonEmptyList._
import Scalaz._
import net.liftweb.json._
import net.liftweb.json.scalaz.JsonScalaz._
import controllers.funnel.SerializationBase
import models._
import java.nio.charset.Charset
import models.tosca.{ ComponentOthers, ComponentOther }
/**
* @author rajthilak
*
*/
object ComponentOthersSerialization extends SerializationBase[ComponentOthers] {
protected val JSONClazKey = controllers.Constants.JSON_CLAZ
protected val ResultsKey = "others"
implicit override val writer = new JSONW[ComponentOthers] {
override def write(h: ComponentOthers): JValue = {
val nrsList: Option[List[JValue]] = h.map {
nrOpt: ComponentOther => nrOpt.toJValue
}.some
JArray(nrsList.getOrElse(List.empty[JValue]))
}
}
implicit override val reader = new JSONR[ComponentOthers] {
override def read(json: JValue): Result[ComponentOthers] = {
json match {
case JArray(jObjectList) => {
val list = jObjectList.flatMap { jValue: JValue =>
ComponentOther.fromJValue(jValue) match {
case Success(nr) => List(nr)
case Failure(fail) => List[ComponentOther]()
}
}.some
val nrs: ComponentOthers = ComponentOthers(list.getOrElse(ComponentOthers.empty))
nrs.successNel[Error]
}
case j => UnexpectedJSONError(j, classOf[JArray]).failureNel[ComponentOthers]
}
}
}
}
|
rajthilakmca/megam_play
|
app/models/tosca/Components.scala
|
/*
** Copyright [2013-2014] [Megam Systems]
**
** 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 models.tosca
import scalaz._
import scalaz.syntax.SemigroupOps
import scalaz.NonEmptyList._
import scalaz.effect.IO
import scalaz.Validation._
import scalaz.EitherT._
import Scalaz._
import org.megam.util.Time
import controllers.stack._
import controllers.Constants._
import controllers.funnel.FunnelErrors._
import models.tosca._
import models._
import models.Accounts
import models.cache._
import models.riak._
import com.stackmob.scaliak._
import com.basho.riak.client.core.query.indexes.{ RiakIndexes, StringBinIndex, LongIntIndex }
import com.basho.riak.client.core.util.{ Constants => RiakConstants }
import org.megam.common.riak.{ GSRiak, GunnySack }
import org.megam.common.uid.UID
import net.liftweb.json._
import net.liftweb.json.scalaz.JsonScalaz._
import java.nio.charset.Charset
/**
* @author rajthilak
*
*/
case class ComponentRequirements(host: String, dummy: String) {
val json = "{\"host\":\"" + host + "\",\"dummy\":\"" + dummy + "\"}"
}
object ComponentRequirements {
def empty: ComponentRequirements = new ComponentRequirements(new String(), new String())
}
case class DesignInputs(id: String, x: String, y: String, z: String, wires: models.tosca.ComponentDesignInputsWires) {
val json = "{\"id\":\"" + id + "\",\"x\":\"" + x + "\",\"y\":\"" + y + "\",\"z\":\"" + z +
"\",\"wires\":" + ComponentDesignInputsWires.toJson(wires, true) + "}"
}
object DesignInputs {
def empty: DesignInputs = new DesignInputs(new String(), new String(), new String(), new String(), ComponentDesignInputsWires.empty)
}
case class ServiceInputs(dbname: String, dbpassword: String) {
val json = "{\"dbname\":\"" + dbname + "\",\"dbpassword\":\"" + dbpassword + "\"}"
}
object ServiceInputs {
def empty: ServiceInputs = new ServiceInputs(new String(), new String())
}
case class ComponentInputs(domain: String, port: String, username: String, password: String, version: String, source: String, design_inputs: DesignInputs, service_inputs: ServiceInputs, ci: CI) {
val json = "{\"domain\":\"" + domain + "\",\"port\":\"" + port + "\",\"username\":\"" + username +
"\",\"password\":\"" + password + "\",\"version\":\"" + version + "\",\"source\":\"" + source +
"\",\"design_inputs\":" + design_inputs.json + ",\"service_inputs\":" + service_inputs.json + ",\"ci\":" + ci.json + "}"
}
object ComponentInputs {
def empty: ComponentInputs = new ComponentInputs(new String(), new String(), new String, new String(), new String(), new String(), DesignInputs.empty, ServiceInputs.empty, CI.empty)
}
case class ComponentInputsResult(domain: String, port: String, username: String, password: String, version: String, source: String, design_inputs: DesignInputs, service_inputs: ServiceInputs, ci_id: String) {
val json = "{\"domain\":\"" + domain + "\",\"port\":\"" + port + "\",\"username\":\"" + username +
"\",\"password\":\"" + password + "\",\"version\":\"" + version + "\",\"source\":\"" + source +
"\",\"design_inputs\":" + design_inputs.json + ",\"service_inputs\":" + service_inputs.json + ",\"ci_id\":\"" + ci_id + "\"}"
}
object ComponentInputsResult {
def empty: ComponentInputsResult = new ComponentInputsResult(new String(), new String(), new String, new String(), new String(), new String(), DesignInputs.empty, ServiceInputs.empty, new String())
}
case class CI(scm: String, enable: String, token: String, owner: String) {
val json = "{\"scm\":\"" + scm + "\",\"enable\":\"" + enable + "\",\"token\":\"" + token + "\",\"owner\":\"" + owner + "\"}"
}
object CI {
def empty: CI = new CI(new String(), new String(), new String(), new String())
}
case class ExResource(url: String) {
val json = "{\"url\":\"" + url + "\"}"
}
object ExResource {
def empty: ExResource = new ExResource(new String())
}
//case class Artifacts(artifact_type: String, content: String, requirements: ArtifactRequirements) {
case class Artifacts(artifact_type: String, content: String, artifact_requirements: String) {
val json = "{\"artifact_type\":\"" + artifact_type + "\",\"content\":\"" + content + "\",\"artifact_requirements\":\"" + artifact_requirements + "\"}"
}
object Artifacts {
// def empty: Artifacts = new Artifacts(new String(), new String(), ArtifactRequirements.empty)
def empty: Artifacts = new Artifacts(new String(), new String(), new String())
}
case class ArtifactRequirements(requirement_type: String) {
val json = "{\"requirement_type\":\"" + requirement_type + "\"}"
}
object ArtifactRequirements {
def empty: ArtifactRequirements = new ArtifactRequirements(new String())
}
case class ComponentOperations(operation_type: String, target_resource: String) {
val json = "{\"operation_type\":\"" + operation_type + "\",\"target_resource\":\"" + target_resource + "\"}"
}
object ComponentOperations {
def empty: ComponentOperations = new ComponentOperations(new String(), new String())
}
case class ComponentOther(otherkey: String, othervalue: String) {
val json = "{\"otherkey\":\"" + otherkey + "\",\"othervalue\":\"" + othervalue + "\"}"
def toJValue: JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.tosca.ComponentOtherSerialization.{ writer => ComponentOtherWriter }
toJSON(this)(ComponentOtherWriter)
}
def toJson(prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue))
} else {
compactRender(toJValue)
}
}
object ComponentOther {
def empty: ComponentOther = new ComponentOther(new String(), new String())
def fromJValue(jValue: JValue)(implicit charset: Charset = UTF8Charset): Result[ComponentOther] = {
import net.liftweb.json.scalaz.JsonScalaz.fromJSON
import models.json.tosca.ComponentOtherSerialization.{ reader => ComponentOtherReader }
fromJSON(jValue)(ComponentOtherReader)
}
def fromJson(json: String): Result[ComponentOther] = (Validation.fromTryCatch[net.liftweb.json.JValue] {
play.api.Logger.debug(("%-20s -->[%s]").format("---json------------------->", json))
parse(json)
} leftMap { t: Throwable =>
UncategorizedError(t.getClass.getCanonicalName, t.getMessage, List())
}).toValidationNel.flatMap { j: JValue => fromJValue(j) }
}
case class ComponentResult(id: String, name: String, tosca_type: String, requirements: ComponentRequirements, inputs: ComponentInputsResult, external_management_resource: String, artifacts: Artifacts, related_components: String, operations: ComponentOperations, others: ComponentOthers, created_at: String) {
def toJValue: JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.tosca.ComponentResultSerialization
val preser = new ComponentResultSerialization()
toJSON(this)(preser.writer)
}
def toJson(prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue))
} else {
compactRender(toJValue)
}
}
object ComponentResult {
def fromJValue(jValue: JValue)(implicit charset: Charset = UTF8Charset): Result[ComponentResult] = {
import net.liftweb.json.scalaz.JsonScalaz.fromJSON
import models.json.tosca.ComponentResultSerialization
val preser = new ComponentResultSerialization()
fromJSON(jValue)(preser.reader)
}
def fromJson(json: String): Result[ComponentResult] = (Validation.fromTryCatch {
parse(json)
} leftMap { t: Throwable =>
UncategorizedError(t.getClass.getCanonicalName, t.getMessage, List())
}).toValidationNel.flatMap { j: JValue => fromJValue(j) }
}
case class ComponentUpdateInput(id: String, name: String, tosca_type: String, requirements: ComponentRequirements, inputs: ComponentInputsResult, external_management_resource: String, artifacts: Artifacts, related_components: String, operations: ComponentOperations, others: models.tosca.ComponentOthers, created_at: String) {
val json = "{\"id\":\"" + id + "\",\"name\":\"" + name + "\",\"tosca_type\":\"" + tosca_type + "\",\"requirements\":" + requirements.json +
",\"inputs\":" + inputs.json + ",\"external_management_resource\":\"" + external_management_resource + "\",\"artifacts\":" + artifacts.json +
",\"related_components\":\"" + related_components + "\",\"operations\":" + operations.json + ",\"others\":" + ComponentOthers.toJson(others, true) + ",\"created_at\":\"" + created_at + "\"}"
}
//case class Component(name: String, tosca_type: String, requirements: ComponentRequirements, inputs: ComponentInputs, external_management_resource: ExResource, artifacts: Artifacts, related_components: String, operations: ComponentOperations) {
case class Component(name: String, tosca_type: String, requirements: ComponentRequirements, inputs: ComponentInputs, external_management_resource: String, artifacts: Artifacts, related_components: String, operations: ComponentOperations, others: models.tosca.ComponentOthers) {
val json = "{\"name\":\"" + name + "\",\"tosca_type\":\"" + tosca_type + "\",\"requirements\":" + requirements.json +
",\"inputs\":" + inputs.json + ",\"external_management_resource\":\"" + external_management_resource + "\",\"artifacts\":" + artifacts.json +
",\"related_components\":\"" + related_components + "\",\"operations\":" + operations.json + ",\"others\":" + ComponentOthers.toJson(others, true) + "}"
def toJValue: JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
val preser = new models.json.tosca.ComponentSerialization()
toJSON(this)(preser.writer)
}
def toJson(prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue))
} else {
compactRender(toJValue)
}
}
object Component {
implicit val formats = DefaultFormats
private val riak = GWRiak("components")
val metadataKey = "COMPONENT"
val metadataVal = "Component Creation"
val bindex = "component"
// def empty: Component = new Component(new String(), new String(), ComponentRequirements.empty, ComponentInputs.empty, ExResource.empty, Artifacts.empty, new String(), ComponentOperations.empty)
def empty: Component = new Component(new String(), new String(), ComponentRequirements.empty, ComponentInputs.empty, new String(), Artifacts.empty, new String(), ComponentOperations.empty, ComponentOthers.empty)
def fromJValue(jValue: JValue)(implicit charset: Charset = UTF8Charset): Result[Component] = {
import net.liftweb.json.scalaz.JsonScalaz.fromJSON
val preser = new models.json.tosca.ComponentSerialization()
fromJSON(jValue)(preser.reader)
}
def fromJson(json: String): Result[Component] = (Validation.fromTryCatch {
play.api.Logger.debug(("%-20s -->[%s]").format("---json------------------->", json))
parse(json)
} leftMap { t: Throwable =>
UncategorizedError(t.getClass.getCanonicalName, t.getMessage, List())
}).toValidationNel.flatMap { j: JValue => fromJValue(j) }
def findByNodeName(componentID: Option[List[String]]): ValidationNel[Throwable, ComponentsResults] = {
play.api.Logger.debug(("%-20s -->[%s]").format("models.Component", "findByNodeName:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("nodeNameList", componentID))
(componentID map {
_.map { asm_id =>
play.api.Logger.debug(("%-20s -->[%s]").format("Component ID", asm_id))
(riak.fetch(asm_id) leftMap { t: NonEmptyList[Throwable] =>
new ServiceUnavailableError(asm_id, (t.list.map(m => m.getMessage)).mkString("\n"))
}).toValidationNel.flatMap { xso: Option[GunnySack] =>
xso match {
case Some(xs) => {
//JsonScalaz.Error doesn't descend from java.lang.Error or Throwable. Screwy.
(ComponentResult.fromJson(xs.value) leftMap
{ t: NonEmptyList[net.liftweb.json.scalaz.JsonScalaz.Error] =>
JSONParsingError(t)
}).toValidationNel.flatMap { j: ComponentResult =>
play.api.Logger.debug(("%-20s -->[%s]").format("Component result", j))
Validation.success[Throwable, ComponentsResults](nels(j.some)).toValidationNel //screwy kishore, every element in a list ?
}
}
case None => {
Validation.failure[Throwable, ComponentsResults](new ResourceItemNotFound(asm_id, "")).toValidationNel
}
}
}
} // -> VNel -> fold by using an accumulator or successNel of empty. +++ => VNel1 + VNel2
} map {
_.foldRight((ComponentsResults.empty).successNel[Throwable])(_ +++ _)
}).head //return the folded element in the head.
}
private def updateGunnySack(email: String, input: String): ValidationNel[Throwable, Option[GunnySack]] = {
play.api.Logger.debug(("%-20s -->[%s]").format("tosca.Component Update", "mkGunnySack:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("email", email))
play.api.Logger.debug(("%-20s -->[%s]").format("json", input))
val ripNel: ValidationNel[Throwable, ComponentUpdateInput] = (Validation.fromTryCatch {
parse(input).extract[ComponentUpdateInput]
} leftMap { t: Throwable => new MalformedBodyError(input, t.getMessage) }).toValidationNel //capture failure
for {
rip <- ripNel
aor <- (Accounts.findByEmail(email) leftMap { t: NonEmptyList[Throwable] => t })
} yield {
val bvalue = Set(aor.get.id)
val json = ComponentResult(rip.id, rip.name, rip.tosca_type, rip.requirements, rip.inputs, rip.external_management_resource, rip.artifacts, rip.related_components, rip.operations, rip.others, rip.created_at).toJson(false)
new GunnySack((rip.id), json, RiakConstants.CTYPE_TEXT_UTF8, None,
Map(metadataKey -> metadataVal), Map((bindex, bvalue))).some
}
}
def update(email: String, input: String): ValidationNel[Throwable, ComponentsResults] = {
play.api.Logger.debug(("%-20s -->[%s]").format("models.Components", "update:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("json", input))
for {
gs <- (updateGunnySack(email, input) leftMap { err: NonEmptyList[Throwable] => err })
maybeGS <- (riak.store(gs.get) leftMap { t: NonEmptyList[Throwable] => t })
} yield {
val nrip = parse(gs.get.value).extract[ComponentResult]
maybeGS match {
case Some(thatGS) =>
nels(ComponentResult(thatGS.key, nrip.name, nrip.tosca_type, nrip.requirements, nrip.inputs, nrip.external_management_resource, nrip.artifacts, nrip.related_components, nrip.operations, nrip.others, nrip.created_at).some)
case None => {
play.api.Logger.warn(("%-20s -->[%s]").format("Component.updated successfully", "Scaliak returned => None. Thats OK."))
nels(ComponentResult(nrip.id, nrip.name, nrip.tosca_type, nrip.requirements, nrip.inputs, nrip.external_management_resource, nrip.artifacts, nrip.related_components, nrip.operations, nrip.others, nrip.created_at).some)
}
}
}
}
}
object ComponentsList {
implicit val formats = DefaultFormats
implicit def ComponentsResultsSemigroup: Semigroup[ComponentsResults] = Semigroup.instance((f1, f2) => f1.append(f2))
val emptyRR = List(Component.empty)
def toJValue(nres: ComponentsList): JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.tosca.ComponentsListSerialization.{ writer => ComponentsListWriter }
toJSON(nres)(ComponentsListWriter)
}
def fromJValue(jValue: JValue)(implicit charset: Charset = UTF8Charset): Result[ComponentsList] = {
import net.liftweb.json.scalaz.JsonScalaz.fromJSON
import models.json.tosca.ComponentsListSerialization.{ reader => ComponentsListReader }
fromJSON(jValue)(ComponentsListReader)
}
def toJson(nres: ComponentsList, prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue(nres)))
} else {
compactRender(toJValue(nres))
}
def apply(componentList: List[Component]): ComponentsList = { println(componentList); componentList }
def empty: List[Component] = emptyRR
private val riak = GWRiak("components")
val metadataKey = "COMPONENT"
val metadataVal = "Component Creation"
val bindex = "component"
/**
* A private method which chains computation to make GunnySack when provided with an input json, email.
* parses the json, and converts it to nodeinput, if there is an error during parsing, a MalformedBodyError is sent back.
* After that flatMap on its success and the account id information is looked up.
* If the account id is looked up successfully, then yield the GunnySack object.
*/
private def mkGunnySack(email: String, input: Component, asm_id: String): ValidationNel[Throwable, Option[GunnySack]] = {
play.api.Logger.debug(("%-20s -->[%s]").format("tosca.Component", "mkGunnySack:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("json", input))
for {
aor <- (Accounts.findByEmail(email) leftMap { t: NonEmptyList[Throwable] => t })
uir <- (UID(MConfig.snowflakeHost, MConfig.snowflakePort, "com").get leftMap { ut: NonEmptyList[Throwable] => ut })
cig <- (ContiniousIntegration.create(email, "{\"enable\":\"" + input.inputs.ci.enable +"\",\"scm\":\""+ input.inputs.ci.scm + "\",\"token\":\"" + input.inputs.ci.token + "\",\"owner\":\""+ input.inputs.ci.owner + "\",\"component_id\":\""+ (uir.get._1 + uir.get._2) + "\",\"assembly_id\":\""+ asm_id +"\",\"action\":\"webhook\"}") leftMap { t: NonEmptyList[Throwable] => t })
ciq <- (ContiniousIntegrationPublish((uir.get._1 + uir.get._2), cig.get._1).dop leftMap { ut: NonEmptyList[Throwable] => ut })
} yield {
val bvalue = Set(aor.get.id)
val inputsResult = "{\"domain\":\"" + input.inputs.domain + "\",\"port\":\""+ input.inputs.port + "\",\"username\":\"" +input.inputs.username + "\",\"password\":\"" + input.inputs.password + "\",\"version\":\"" + input.inputs.version + "\",\"source\":\"" + input.inputs.source +"\",\"design_inputs\":" + input.inputs.design_inputs.json + ",\"service_inputs\":" + input.inputs.service_inputs.json + ",\"ci_id\":\"" + cig.get._1 +"\"}"
val json = "{\"id\": \"" + (uir.get._1 + uir.get._2) + "\",\"name\":\"" + input.name + "\",\"tosca_type\":\"" + input.tosca_type + "\",\"requirements\":" + input.requirements.json + ",\"inputs\":" + inputsResult + ",\"external_management_resource\":\"" + input.external_management_resource + "\",\"artifacts\":" + input.artifacts.json + ",\"related_components\":\"" + input.related_components + "\",\"operations\":" + input.operations.json + ",\"others\":" + ComponentOthers.toJson(input.others, true) + ",\"created_at\":\"" + Time.now.toString + "\"}"
new GunnySack((uir.get._1 + uir.get._2), json, RiakConstants.CTYPE_TEXT_UTF8, None,
Map(metadataKey -> metadataVal), Map((bindex, bvalue))).some
}
}
def createLinks(email: String, input: ComponentsList, asm_id: String): ValidationNel[Throwable, ComponentsResults] = {
play.api.Logger.debug(("%-20s -->[%s]").format("tosca.ComponentsList", "create:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("email", email))
play.api.Logger.debug(("%-20s -->[%s]").format("yaml", input))
val res = (input map {
asminp =>
play.api.Logger.debug(("%-20s -->[%s]").format("component", asminp))
(create(email, asminp, asm_id))
}).foldRight((ComponentsResults.empty).successNel[Throwable])(_ +++ _)
play.api.Logger.debug(("%-20s -->[%s]").format("models.tosca.Assembly", res))
res.getOrElse(new ResourceItemNotFound(email, "nodes = ah. ouh. ror some reason.").failureNel[ComponentsResults])
res
}
/*
* create new market place item with the 'name' of the item provide as input.
* A index name assemblies name will point to the "csars" bucket
*/
def create(email: String, input: Component, asm_id: String): ValidationNel[Throwable, ComponentsResults] = {
play.api.Logger.debug(("%-20s -->[%s]").format("tosca.ComponentsList", "create:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("email", email))
play.api.Logger.debug(("%-20s -->[%s]").format("yaml", input))
for {
ogsi <- mkGunnySack(email, input, asm_id) leftMap { err: NonEmptyList[Throwable] => err }
nrip <- ComponentResult.fromJson(ogsi.get.value) leftMap { t: NonEmptyList[net.liftweb.json.scalaz.JsonScalaz.Error] => println("osgi\n" + ogsi.get.value); play.api.Logger.debug(JSONParsingError(t).toString); nels(JSONParsingError(t)) }
ogsr <- riak.store(ogsi.get) leftMap { t: NonEmptyList[Throwable] => play.api.Logger.debug("--------> ooo"); t }
} yield {
play.api.Logger.debug(("%-20s -->[%s],riak returned: %s").format("Component.created successfully", email, ogsr))
ogsr match {
case Some(thatGS) => {
nels(ComponentResult(thatGS.key, nrip.name, nrip.tosca_type, nrip.requirements, nrip.inputs, nrip.external_management_resource, nrip.artifacts, nrip.related_components, nrip.operations, nrip.others, Time.now.toString()).some)
}
case None => {
play.api.Logger.warn(("%-20s -->[%s]").format("Node.created successfully", "Scaliak returned => None. Thats OK."))
nels(ComponentResult(ogsi.get.key, nrip.name, nrip.tosca_type, nrip.requirements, nrip.inputs, nrip.external_management_resource, nrip.artifacts, nrip.related_components, nrip.operations, nrip.others, Time.now.toString()).some)
}
}
}
}
}
|
rajthilakmca/megam_play
|
app/models/PlatformAppPrimer.scala
|
<reponame>rajthilakmca/megam_play
/*
** Copyright [2013-2014] [Megam Systems]
**
** 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 models
import scalaz._
import Scalaz._
import scalaz.effect.IO
import scalaz.EitherT._
import scalaz.Validation
//import scalaz.Validation.FlatMap._
import scalaz.NonEmptyList._
import controllers.funnel.{ FunnelResponse, FunnelResponses }
import play.api.http.Status._
import controllers.stack._
import controllers.Constants._
import controllers.funnel.FunnelErrors._
import models._
import play.api.Logger
import models.tosca._
/**
* @author ram
*
*/
object PlatformAppPrimer {
//on board a sandbox account during start of the play server.
def sandboxAcct = models.Accounts.create(
AccountInput(MEGAM_ADMIN_EMAIL, MEGAM_ADMIN_APIKEY, "normal").json)
def sandboxDummyAcct = models.Accounts.create(
AccountInput(DEMO_EMAIL, DEMO_APIKEY, "demo").json)
//populate the predefinitions of the platform supported by megam.
def predefs = models.Predefs.create
//populate the marketplace addons
def marketplace_addons = models.MarketPlaces.createMany(MarketPlaceInput.toMap)
def sandbox_ec2_default = PredefCloudInput("clouddefault",
new PredefCloudSpec("ec2", "megam", "ami-a0074df2", "t1.micro", ""),
new PredefCloudAccess("megam_ec2", "cloudkeys/" + MEGAM_ADMIN_EMAIL + "/default/megam_ec2.pem", "ubuntu", "https://s3-ap-southeast-1.amazonaws.com/cloudkeys/" + MEGAM_ADMIN_EMAIL + "/default", "", "", "ap-southeast-1")).json
def sandbox_google_default = PredefCloudInput("clouddefault",
new PredefCloudSpec("google", "", "debian-7-wheezy-v20131120", "f1-micro", ""),
new PredefCloudAccess("", "cloudkeys/" + MEGAM_ADMIN_EMAIL + "/id_rsa.pub", "ubuntu", "https://s3-ap-southeast-1.amazonaws.com/cloudkeys/" + MEGAM_ADMIN_EMAIL + "/gdefault", "", "europe-west1-a", "")).json
def clone_predefcloud = { ccemail: String => models.PredefClouds.create(ccemail, sandbox_google_default) }
def acc_prep: ValidationNel[Throwable, FunnelResponses] = for {
sada <- sandboxAcct
dummy <- sandboxDummyAcct
} yield {
val chainedComps = List[FunnelResponse](
FunnelResponse(CREATED, """Account created successfully(%s, %s).
|
|Your email registered successully.""".
format(sada.get.email, dummy.get.email).stripMargin, "Megam::Account"))
FunnelResponses(chainedComps)
}
def prep: ValidationNel[Throwable, FunnelResponses] = for {
lpd <- predefs
ccd <- clone_predefcloud(MEGAM_ADMIN_EMAIL)
cdsd <- clone_predefcloud(DEMO_EMAIL)
} yield {
val chainedComps = List[FunnelResponse](
FunnelResponse(CREATED, """Predefs created successfully. Cache gets loaded upon first fetch.
|
|%nLoaded values are ----->%n[%s]""".format(lpd.toString).stripMargin, "Megam::Predef"),
FunnelResponse(CREATED, """Predefs cloud created successfully(%s,%s).
|
|You can use the the 'predefs cloud name':{%s}.""".format(MEGAM_ADMIN_EMAIL, DEMO_EMAIL, cdsd.getOrElse("none")), "Megam::PredefCloud"))
FunnelResponses(chainedComps)
}
def mkp_prep: ValidationNel[Throwable, FunnelResponses] = for {
mkp <- marketplace_addons
} yield {
val chainedComps = List[FunnelResponse](
FunnelResponse(CREATED, """Market Place addons created successfully. Cache gets loaded upon first fetch.
|
|%nLoaded results are ----->%n[%s]""".format(mkp.list.size + " addons primed.").stripMargin, "Megam::MarketPlaces"))
FunnelResponses(chainedComps)
}
def clone_organizations = { clonefor_email: String =>
models.tosca.Organizations.create(clonefor_email,
OrganizationsInput(DEFAULT_ORG_NAME).json)
}
def organizations_default = models.tosca.Organizations.create(MEGAM_ADMIN_EMAIL,
OrganizationsInput(DEFAULT_ORG_NAME).json)
def org_prep: ValidationNel[Throwable, FunnelResponses] = for {
org <- organizations_default
} yield {
val chainedComps = List[FunnelResponse](
FunnelResponse(CREATED, """Organization created successfully(%s).
|
|Your email registered successully.""".format(org.get.name).stripMargin, "Megam::Organizations"))
FunnelResponses(chainedComps)
}
def domains_default = models.tosca.Domains.create(MEGAM_ADMIN_EMAIL,
DomainsInput(DEFAULT_DOMAIN_NAME).json)
def dmn_prep: ValidationNel[Throwable, FunnelResponses] = for {
dmn <- domains_default
} yield {
val chainedComps = List[FunnelResponse](
FunnelResponse(CREATED, """Domains created successfully(%s).
|
|Your email registered successully.""".
format(dmn.get.name).stripMargin, "Megam::Domains"))
FunnelResponses(chainedComps)
}
}
|
rajthilakmca/megam_play
|
app/models/Accounts.scala
|
<filename>app/models/Accounts.scala
/*
** Copyright [2013-2014] [Megam Systems]
**
** 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 models
import scalaz._
import Scalaz._
import scalaz.effect.IO
import scalaz.EitherT._
import scalaz.Validation
//import scalaz.Validation.FlatMap._
import scalaz.NonEmptyList._
import com.stackmob.scaliak._
import org.megam.common.riak.{ GSRiak, GunnySack }
import org.megam.common.uid.UID
import org.megam.util.Time
import net.liftweb.json._
import net.liftweb.json.scalaz.JsonScalaz._
import java.nio.charset.Charset
import com.basho.riak.client.core.query.indexes.{ RiakIndexes, StringBinIndex, LongIntIndex }
import com.basho.riak.client.core.util.{ Constants => RiakConstants }
import models.cache._
import models.riak._
import controllers.funnel.FunnelErrors._
import controllers.Constants._
import controllers.stack.MConfig
/**
* @author rajthilak
* authority
*/
case class AccountResult(id: String, email: String, api_key: String, authority: String, created_at: String) {
def toJValue: JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.AccountResultSerialization
val acctser = new AccountResultSerialization()
toJSON(this)(acctser.writer)
}
def toJson(prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue))
} else {
compactRender(toJValue)
}
}
object AccountResult {
def apply(id: String, email: String, api_key: String, authority: String) = new AccountResult(id, email, api_key, authority, Time.now.toString)
def apply(email: String): AccountResult = AccountResult("not found", email, new String(), new String())
def fromJValue(jValue: JValue)(implicit charset: Charset = UTF8Charset): Result[AccountResult] = {
import net.liftweb.json.scalaz.JsonScalaz.fromJSON
import models.json.AccountResultSerialization
val acctser = new AccountResultSerialization()
fromJSON(jValue)(acctser.reader)
}
def fromJson(json: String): Result[AccountResult] = (Validation.fromTryCatch[net.liftweb.json.JValue] {
parse(json)
} leftMap { t: Throwable =>
UncategorizedError(t.getClass.getCanonicalName, t.getMessage, List())
}).toValidationNel.flatMap { j: JValue => fromJValue(j) }
}
case class AccountInput(email: String, api_key: String, authority: String) {
val json = "{\"email\":\"" + email + "\",\"api_key\":\"" + api_key + "\",\"authority\":\"" + authority + "\"}"
}
object Accounts {
implicit val formats = DefaultFormats
private val riak = GWRiak("accounts")
/**
* Parse the input body when you start, if its ok, then we process it.
* Or else send back a bad return code saying "the body contains invalid character, with the message received.
* If there is an error in the snowflake connection, we need to send one.
*/
def create(input: String): ValidationNel[Throwable, Option[AccountResult]] = {
play.api.Logger.debug(("%-20s -->[%s]").format("models.Accounts", "create:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("input json", input))
(Validation.fromTryCatch[models.AccountInput] {
parse(input).extract[AccountInput]
} leftMap { t: Throwable => new MalformedBodyError(input, t.getMessage)
}).toValidationNel.flatMap { m: AccountInput =>
play.api.Logger.debug(("%-20s -->[%s]").format("AccountInput", m))
UID(MConfig.snowflakeHost, MConfig.snowflakePort, "act").get match {
case Success(uid) => {
val metadataKey = "Field"
val metadataVal = "1002"
val bindex = "accountId"
val bvalue = Set(uid.get._1 + uid.get._2)
val acctRes = AccountResult(uid.get._1 + uid.get._2, m.email, m.api_key, m.authority)
play.api.Logger.debug(("%-20s -->[%s]").format("json with uid", acctRes.toJson(false)))
val storeValue = riak.store(new GunnySack(m.email, acctRes.toJson(false), RiakConstants.CTYPE_TEXT_UTF8, None, Map(metadataKey -> metadataVal), Map((bindex, bvalue))))
storeValue match {
case Success(succ) => acctRes.some.successNel[Throwable]
case Failure(err) => Validation.failure[Throwable, Option[AccountResult]](
new ServiceUnavailableError(input, (err.list.map(m => m.getMessage)).mkString("\n"))).toValidationNel
}
}
case Failure(err) => Validation.failure[Throwable, Option[AccountResult]](
new ServiceUnavailableError(input, (err.list.map(m => m.getMessage)).mkString("\n"))).toValidationNel
}
}
}
/**
* Performs a fetch from Riak bucket. If there is an error then ServiceUnavailable is sent back.
* If not, if there a GunnySack value, then it is parsed. When on parsing error, send back ResourceItemNotFound error.
* When there is no gunnysack value (None), then return back a failure - ResourceItemNotFound
*/
def findByEmail(email: String): ValidationNel[Throwable, Option[AccountResult]] = {
play.api.Logger.debug(("%-20s -->[%s]").format("models.Accounts", "findByEmail:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("findByEmail", email))
InMemory[ValidationNel[Throwable, Option[AccountResult]]]({
name: String =>
{
play.api.Logger.debug(("%-20s -->[%s]").format("InMemory", email))
(riak.fetch(email) leftMap { t: NonEmptyList[Throwable] =>
new ServiceUnavailableError(email, (t.list.map(m => m.getMessage)).mkString("\n"))
}).toValidationNel.flatMap { xso: Option[GunnySack] =>
xso match {
case Some(xs) => {
(Validation.fromTryCatch[models.AccountResult] {
// initiate_default_cloud(email)
parse(xs.value).extract[AccountResult]
} leftMap { t: Throwable =>
new ResourceItemNotFound(email, t.getMessage)
}).toValidationNel.flatMap { j: AccountResult =>
Validation.success[Throwable, Option[AccountResult]](j.some).toValidationNel
}
}
case None => Validation.failure[Throwable, Option[AccountResult]](new ResourceItemNotFound(email, "")).toValidationNel
}
}
}
}).get(email).eval(InMemoryCache[ValidationNel[Throwable, Option[AccountResult]]]())
}
/**
* Find by the accounts id.
*/
def findByAccountsId(id: String): ValidationNel[Throwable, Option[AccountResult]] = {
play.api.Logger.debug(("%-20s -->[%s]").format("models.Accounts", "findByAccountsId:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("accounts id", id))
val metadataKey = "Field"
val metadataVal = "1002"
val bindex = ""
val bvalue = Set("")
val fetchValue = riak.fetchIndexByValue(new GunnySack("accountId", id,
RiakConstants.CTYPE_TEXT_UTF8, None, Map(metadataKey -> metadataVal), Map((bindex, bvalue))))
fetchValue match {
case Success(msg) => {
val key = msg match {
case List(x) => x
}
findByEmail(key)
}
case Failure(err) => Validation.failure[Throwable, Option[AccountResult]](
new ServiceUnavailableError(id, (err.list.map(m => m.getMessage)).mkString("\n"))).toValidationNel
}
}
implicit val sedimentAccountEmail = new Sedimenter[ValidationNel[Throwable, Option[AccountResult]]] {
def sediment(maybeASediment: ValidationNel[Throwable, Option[AccountResult]]): Boolean = {
val notSed = maybeASediment.isSuccess
play.api.Logger.debug("%-20s -->[%s]".format("|^/^|-->ACT:sediment:", notSed))
notSed
}
}
}
|
rajthilakmca/megam_play
|
app/controllers/funnel/FunnelResponseSerialization.scala
|
/*
** Copyright [2013-2014] [Megam Systems]
**
** 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 controllers.funnel
import scalaz._
import Scalaz._
import scalaz.effect.IO
import scalaz.EitherT._
import scalaz.Validation
//import scalaz.Validation.FlatMap._
import scalaz.NonEmptyList._
import net.liftweb.json._
import net.liftweb.json.scalaz.JsonScalaz._
import java.util.Date
import java.nio.charset.Charset
import controllers.funnel.FunnelErrors._
import controllers.Constants._
/**
* @author ram
*
*/
class FunnelResponseSerialization(charset: Charset = UTF8Charset) extends SerializationBase[FunnelResponse] {
protected val JSONClazKey = JSON_CLAZ
protected val CodeKey = "code"
protected val MessageTypeKey = "msg_type"
protected val MessageKey = "msg"
protected val MoreKey = "more"
protected val LinksKey ="links"
override implicit val writer = new JSONW[FunnelResponse] {
override def write(h: FunnelResponse): JValue = {
JObject(
JField(CodeKey, toJSON(h.code)) ::
JField(MessageTypeKey, toJSON(h.msg_type)) ::
JField (MessageKey, toJSON(h.msg)) ::
JField(MoreKey, toJSON(h.more)) :: JField(JSONClazKey, toJSON(h.json_claz)) :: JField(LinksKey, toJSON(h.links)) ::Nil)
}
}
override implicit val reader = new JSONR[FunnelResponse] {
override def read(json: JValue): Result[FunnelResponse] = {
val codeField = field[Int](CodeKey)(json)
val msgTypeField = field[String](MessageTypeKey)(json)
val msgField = field[String](MessageKey)(json)
val moreField = field[String](MoreKey)(json)
val jsonClazField = field[String](JSONClazKey)(json)
(codeField |@| msgTypeField |@| msgField |@| moreField |@| jsonClazField) {
(code: Int, msg: String, more: String, msgType: String,jsonClazField: String) =>
new FunnelResponse(code, msg, more,msgType,jsonClazField)
}
}
}
}
|
rajthilakmca/megam_play
|
app/models/json/tosca/ComponentOtherSerialization.scala
|
/*
** Copyright [2013-2014] [Megam Systems]
**
** 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 models.json.tosca
import scalaz._
import scalaz.NonEmptyList._
import scalaz.Validation
import scalaz.Validation._
import Scalaz._
import net.liftweb.json._
import net.liftweb.json.scalaz.JsonScalaz._
import java.util.Date
import java.nio.charset.Charset
import controllers.funnel.FunnelErrors._
import controllers.Constants._
import controllers.funnel.SerializationBase
import models.tosca.{ ComponentOther }
/**
* @author rajthilak
*
*/
object ComponentOtherSerialization extends SerializationBase[ComponentOther] {
protected val OtherkeyKey = "otherkey"
protected val OtherValueKey = "othervalue"
override implicit val writer = new JSONW[ComponentOther] {
override def write(h: ComponentOther): JValue = {
JObject(
JField(OtherkeyKey, toJSON(h.otherkey)) ::
JField(OtherValueKey, toJSON(h.othervalue)) ::
Nil)
}
}
override implicit val reader = new JSONR[ComponentOther] {
override def read(json: JValue): Result[ComponentOther] = {
val otherkeyField = field[String](OtherkeyKey)(json)
val othervalueField = field[String](OtherValueKey)(json)
(otherkeyField |@| othervalueField ) {
(otherkey: String, othervalue: String) =>
new ComponentOther(otherkey, othervalue)
}
}
}
}
|
rajthilakmca/megam_play
|
app/models/json/tosca/ComponentInputsSerialization.scala
|
/*
** Copyright [2013-2014] [Megam Systems]
**
** 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 models.json.tosca
import scalaz._
import scalaz.NonEmptyList._
import scalaz.Validation
import scalaz.Validation._
import Scalaz._
import net.liftweb.json._
import net.liftweb.json.scalaz.JsonScalaz._
import java.util.Date
import java.nio.charset.Charset
import controllers.funnel.FunnelErrors._
import controllers.Constants._
import controllers.funnel.SerializationBase
import models.tosca.{ ComponentInputs, DesignInputs, ServiceInputs, CI }
/**
* @author rajthilak
*
*/
object ComponentInputsSerialization extends SerializationBase[ComponentInputs] {
protected val DomainKey = "domain"
protected val PortKey = "port"
protected val UserNameKey = "username"
protected val PasswordKey = "password"
protected val VersionKey = "version"
protected val SourceKey = "source"
protected val DesignInputsKey = "design_inputs"
protected val ServiceInputsKey = "service_inputs"
protected val CIKey = "ci"
override implicit val writer = new JSONW[ComponentInputs] {
import DesignInputsSerialization.{ writer => DesignInputsWriter }
import ServiceInputsSerialization.{ writer => ServiceInputsWriter }
import CISerialization.{ writer => CIWriter }
override def write(h: ComponentInputs): JValue = {
JObject(
JField(DomainKey, toJSON(h.domain)) ::
JField(PortKey, toJSON(h.port)) ::
JField(UserNameKey, toJSON(h.username)) ::
JField(PasswordKey, toJSON(h.password)) ::
JField(VersionKey, toJSON(h.version)) ::
JField(SourceKey, toJSON(h.source)) ::
JField(DesignInputsKey, toJSON(h.design_inputs)(DesignInputsWriter)) ::
JField(ServiceInputsKey, toJSON(h.service_inputs)(ServiceInputsWriter)) ::
JField(CIKey, toJSON(h.ci)(CIWriter)) ::
Nil)
}
}
override implicit val reader = new JSONR[ComponentInputs] {
import DesignInputsSerialization.{ reader => DesignInputsReader }
import ServiceInputsSerialization.{ reader => ServiceInputsReader }
import CISerialization.{ reader => CIReader }
override def read(json: JValue): Result[ComponentInputs] = {
val domainField = field[String](DomainKey)(json)
val portField = field[String](PortKey)(json)
val usernameField = field[String](UserNameKey)(json)
val passwordField = field[String](PasswordKey)(json)
val versionField = field[String](VersionKey)(json)
val sourceField = field[String](SourceKey)(json)
val designinputsField = field[DesignInputs](DesignInputsKey)(json)(DesignInputsReader)
val serviceinputsField = field[ServiceInputs](ServiceInputsKey)(json)(ServiceInputsReader)
val ciField = field[CI](CIKey)(json)(CIReader)
(domainField |@| portField |@| usernameField |@| passwordField |@| versionField |@| sourceField |@| designinputsField |@| serviceinputsField |@| ciField) {
(domain: String, port: String, username: String, password: String, version: String, source: String, design_inputs: DesignInputs, service_inputs: ServiceInputs, ci: CI) =>
new ComponentInputs(domain, port, username, password, version, source, design_inputs, service_inputs, ci)
}
}
}
}
|
rajthilakmca/megam_play
|
app/models/json/tosca/ArtifactsSerialization.scala
|
/*
** Copyright [2013-2014] [Megam Systems]
**
** 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 models.json.tosca
import scalaz._
import scalaz.NonEmptyList._
import scalaz.Validation
import scalaz.Validation._
import Scalaz._
import net.liftweb.json._
import net.liftweb.json.scalaz.JsonScalaz._
import java.util.Date
import java.nio.charset.Charset
import controllers.funnel.FunnelErrors._
import controllers.Constants._
import controllers.funnel.SerializationBase
import models.tosca.{ Artifacts }
/**
* @author rajthilak
*
*/
object ArtifactsSerialization extends SerializationBase[Artifacts] {
protected val ArtifactTypeKey = "artifact_type"
protected val ContentKey = "content"
protected val ArtifactRequirementsKey = "artifact_requirements"
override implicit val writer = new JSONW[Artifacts] {
// import ArtifactRequirementsSerialization.{ writer => ArtifactRequirementsWriter }
override def write(h: Artifacts): JValue = {
JObject(
JField(ArtifactTypeKey, toJSON(h.artifact_type)) ::
JField(ContentKey, toJSON(h.content)) ::
// JField(RequirementsKey, toJSON(h.requirements)(ArtifactRequirementsWriter)) ::
JField(ArtifactRequirementsKey, toJSON(h.artifact_requirements)) ::
Nil)
}
}
override implicit val reader = new JSONR[Artifacts] {
// import ArtifactRequirementsSerialization.{ reader => ArtifactRequirementsReader }
override def read(json: JValue): Result[Artifacts] = {
val artifacttypeField = field[String](ArtifactTypeKey)(json)
val contentField = field[String](ContentKey)(json)
// val requirementsField = field[String](RequirementsKey)(json)(ArtifactRequirementsReader)
val artifactrequirementsField = field[String](ArtifactRequirementsKey)(json)
(artifacttypeField |@| contentField |@| artifactrequirementsField) {
(artifacttype: String, content: String, artifact_requirements: String) =>
new Artifacts(artifacttype, content, artifact_requirements)
}
}
}
}
|
rajthilakmca/megam_play
|
app/models/tosca/Assemblies.scala
|
/*
** Copyright [2013-2014] [Megam Systems]
**
** 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 models.tosca
import scalaz._
import scalaz.syntax.SemigroupOps
import scalaz.NonEmptyList._
import scalaz.effect.IO
import scalaz.Validation._
import scalaz.EitherT._
import Scalaz._
import org.megam.util.Time
import scala.collection.mutable.ListBuffer
import controllers.stack._
import controllers.Constants._
import controllers.funnel.FunnelErrors._
import models.tosca._
import models._
import models.riak._
import models.cache._
import com.stackmob.scaliak._
import com.basho.riak.client.core.query.indexes.{ RiakIndexes, StringBinIndex, LongIntIndex }
import com.basho.riak.client.core.util.{ Constants => RiakConstants }
import org.megam.common.riak.{ GSRiak, GunnySack }
import org.megam.common.uid.UID
import net.liftweb.json._
import net.liftweb.json.scalaz.JsonScalaz._
import java.nio.charset.Charset
/**
* @author rajthilak
*
*/
case class AssembliesInput(name: String, assemblies: models.tosca.AssembliesList, inputs: AssembliesInputs) {
val json = "{\"name\":\"" + name + "\", \"assemblies\":" + AssembliesList.toJson(assemblies, true) + ",\"inputs\":" + inputs.json + "}"
}
case class CloudSetting(id: String, cstype: String, cloudsettings: String, x: String, y: String, z: String, wires: models.tosca.CSWiresList) {
val json = "{\"id\":\"" + id + "\",\"cstype\":\"" + cstype + "\",\"cloudsettings\":\"" + cloudsettings + "\",\"x\":\"" + x + "\",\"y\":\"" + y + "\",\"z\":\"" + z + "\",\"wires\":" + CSWiresList.toJson(wires, true) + "}"
def toJValue: JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
val preser = new models.json.tosca.CloudSettingSerialization()
toJSON(this)(preser.writer)
}
def toJson(prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue))
} else {
compactRender(toJValue)
}
}
object CloudSetting {
def empty: CloudSetting = new CloudSetting(new String(), new String(), new String, new String(), new String, new String(), CSWiresList.empty)
def fromJValue(jValue: JValue)(implicit charset: Charset = UTF8Charset): Result[CloudSetting] = {
import net.liftweb.json.scalaz.JsonScalaz.fromJSON
val preser = new models.json.tosca.CloudSettingSerialization()
fromJSON(jValue)(preser.reader)
}
def fromJson(json: String): Result[CloudSetting] = (Validation.fromTryCatch {
play.api.Logger.debug(("%-20s -->[%s]").format("---json------------------->", json))
parse(json)
} leftMap { t: Throwable =>
UncategorizedError(t.getClass.getCanonicalName, t.getMessage, List())
}).toValidationNel.flatMap { j: JValue => fromJValue(j) }
}
case class AssembliesInputs(id: String, assemblies_type: String, label: String, cloudsettings: models.tosca.CloudSettingsList) {
val json = "{\"id\": \"" + id + "\", \"assemblies_type\":\"" + assemblies_type + "\",\"label\" : \"" + label + "\",\"cloudsettings\":" + CloudSettingsList.toJson(cloudsettings, true) + "}"
}
object AssembliesInputs {
def empty: AssembliesInputs = new AssembliesInputs(new String(), new String(), new String, models.tosca.CloudSettingsList.emptyRR)
}
case class AssembliesResult(id: String, accounts_id: String, name: String, assemblies: models.tosca.AssemblyLinks, inputs: AssembliesInputs, created_at: String) {
def toJValue: JValue = {
import net.liftweb.json.scalaz.JsonScalaz.toJSON
import models.json.tosca.AssembliesResultSerialization
val preser = new AssembliesResultSerialization()
toJSON(this)(preser.writer)
}
def toJson(prettyPrint: Boolean = false): String = if (prettyPrint) {
pretty(render(toJValue))
} else {
compactRender(toJValue)
}
}
object AssembliesResult {
def fromJValue(jValue: JValue)(implicit charset: Charset = UTF8Charset): Result[AssembliesResult] = {
import net.liftweb.json.scalaz.JsonScalaz.fromJSON
import models.json.tosca.AssembliesResultSerialization
val preser = new AssembliesResultSerialization()
fromJSON(jValue)(preser.reader)
}
def fromJson(json: String): Result[AssembliesResult] = (Validation.fromTryCatch {
parse(json)
} leftMap { t: Throwable =>
UncategorizedError(t.getClass.getCanonicalName, t.getMessage, List())
}).toValidationNel.flatMap { j: JValue => fromJValue(j) }
}
object Assemblies {
implicit val formats = DefaultFormats
private val riak = GWRiak("assemblies")
val metadataKey = "assemblies"
val metadataVal = "Assemblies Creation"
val bindex = "assemblies"
/**
* A private method which chains computation to make GunnySack when provided with an input json, email.
* parses the json, and converts it to nodeinput, if there is an error during parsing, a MalformedBodyError is sent back.
* After that flatMap on its success and the account id information is looked up.
* If the account id is looked up successfully, then yield the GunnySack object.
*/
private def mkGunnySack(email: String, input: String): ValidationNel[Throwable, Option[GunnySack]] = {
play.api.Logger.debug(("%-20s -->[%s]").format("tosca.Assemblies", "mkGunnySack:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("email", email))
play.api.Logger.debug(("%-20s -->[%s]").format("json", input))
val ripNel: ValidationNel[Throwable, AssembliesInput] = (Validation.fromTryCatch {
parse(input).extract[AssembliesInput]
} leftMap { t: Throwable => new MalformedBodyError(input, t.getMessage) }).toValidationNel //capture failure
for {
rip <- ripNel
aor <- (Accounts.findByEmail(email) leftMap { t: NonEmptyList[Throwable] => t })
aem <- (AssembliesList.createLinks(email, rip.assemblies) leftMap { t: NonEmptyList[Throwable] => t })
uir <- (UID(MConfig.snowflakeHost, MConfig.snowflakePort, "ams").get leftMap { ut: NonEmptyList[Throwable] => ut })
req <- (Requests.createforNewNode("{\"node_id\": \"" + (uir.get._1 + uir.get._2) + "\",\"node_name\": \"" + rip.name + "\",\"req_type\": \"create\"}") leftMap { t: NonEmptyList[Throwable] => t })
} yield {
val bvalue = Set(aor.get.id)
var assembly_links = new ListBuffer[String]()
for (assembly <- aem) {
assembly match {
case Some(value) => assembly_links += value.id
case None => assembly_links += ""
}
}
val json = new AssembliesResult(uir.get._1 + uir.get._2, aor.get.id, rip.name, assembly_links.toList, rip.inputs, Time.now.toString).toJson(false)
new GunnySack((uir.get._1 + uir.get._2), json, RiakConstants.CTYPE_TEXT_UTF8, None,
Map(metadataKey -> metadataVal), Map((bindex, bvalue))).some
}
}
/*
* create new market place item with the 'name' of the item provide as input.
* A index name assemblies name will point to the "csars" bucket
*/
def create(email: String, input: String): ValidationNel[Throwable, Option[AssembliesResult]] = {
play.api.Logger.debug(("%-20s -->[%s]").format("tosca.Assemblies", "create:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("email", email))
play.api.Logger.debug(("%-20s -->[%s]").format("yaml", input))
(mkGunnySack(email, input) leftMap { err: NonEmptyList[Throwable] =>
new ServiceUnavailableError(input, (err.list.map(m => m.getMessage)).mkString("\n"))
}).toValidationNel.flatMap { gs: Option[GunnySack] =>
(riak.store(gs.get) leftMap { t: NonEmptyList[Throwable] => t }).
flatMap { maybeGS: Option[GunnySack] =>
maybeGS match {
case Some(thatGS) => (parse(thatGS.value).extract[AssembliesResult].some).successNel[Throwable]
case None => {
play.api.Logger.warn(("%-20s -->[%s]").format("Assemblies.created success", "Scaliak returned => None. Thats OK."))
(parse(gs.get.value).extract[AssembliesResult].some).successNel[Throwable];
}
}
}
}
}
def findById(assembliesID: Option[List[String]]): ValidationNel[Throwable, AssembliesResults] = {
play.api.Logger.debug(("%-20s -->[%s]").format("models.Assemblies", "findByNodeName:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("nodeNameList", assembliesID))
(assembliesID map {
_.map { asm_id =>
play.api.Logger.debug(("%-20s -->[%s]").format("Assemblies ID", asm_id))
(riak.fetch(asm_id) leftMap { t: NonEmptyList[Throwable] =>
new ServiceUnavailableError(asm_id, (t.list.map(m => m.getMessage)).mkString("\n"))
}).toValidationNel.flatMap { xso: Option[GunnySack] =>
xso match {
case Some(xs) => {
//JsonScalaz.Error doesn't descend from java.lang.Error or Throwable. Screwy.
(AssembliesResult.fromJson(xs.value) leftMap
{ t: NonEmptyList[net.liftweb.json.scalaz.JsonScalaz.Error] =>
JSONParsingError(t)
}).toValidationNel.flatMap { j: AssembliesResult =>
play.api.Logger.debug(("%-20s -->[%s]").format("assemblies result", j))
Validation.success[Throwable, AssembliesResults](nels(j.some)).toValidationNel //screwy kishore, every element in a list ?
}
}
case None => {
Validation.failure[Throwable, AssembliesResults](new ResourceItemNotFound(asm_id, "")).toValidationNel
}
}
}
} // -> VNel -> fold by using an accumulator or successNel of empty. +++ => VNel1 + VNel2
} map {
_.foldRight((AssembliesResults.empty).successNel[Throwable])(_ +++ _)
}).head //return the folded element in the head.
}
/*
* An IO wrapped finder using an email. Upon fetching the account_id for an email,
* the csarnames are listed on the index (account.id) in bucket `CSARs`.
* Using a "csarname" as key, return a list of ValidationNel[List[CSARResult]]
* Takes an email, and returns a Future[ValidationNel, List[Option[CSARResult]]]
*/
def findByEmail(email: String): ValidationNel[Throwable, AssembliesResults] = {
play.api.Logger.debug(("%-20s -->[%s]").format("tosca.Assemblies", "findByEmail:Entry"))
play.api.Logger.debug(("%-20s -->[%s]").format("email", email))
val res = eitherT[IO, NonEmptyList[Throwable], ValidationNel[Throwable, AssembliesResults]] {
(((for {
aor <- (Accounts.findByEmail(email) leftMap { t: NonEmptyList[Throwable] => t }) //captures failure on the left side, success on right ie the component before the (<-)
} yield {
val bindex = ""
val bvalue = Set("")
play.api.Logger.debug(("%-20s -->[%s]").format("tosca.Assemblies", "findByEmail" + aor.get.id))
new GunnySack("assemblies", aor.get.id, RiakConstants.CTYPE_TEXT_UTF8,
None, Map(metadataKey -> metadataVal), Map((bindex, bvalue))).some
}) leftMap { t: NonEmptyList[Throwable] => t } flatMap {
gs: Option[GunnySack] => riak.fetchIndexByValue(gs.get)
} map { nm: List[String] =>
(if (!nm.isEmpty) findById(nm.some) else
new ResourceItemNotFound(email, "Assemblies = nothing found for the user.").failureNel[AssembliesResults])
}).disjunction).pure[IO]
}.run.map(_.validation).unsafePerformIO
res.getOrElse(new ResourceItemNotFound(email, "Assemblies = nothing found for the users.").failureNel[AssembliesResults])
}
}
|
birdie7761/kafka-manager
|
app/kafka/manager/utils/zero82/LogConfig.scala
|
<reponame>birdie7761/kafka-manager
/**
* 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 kafka.manager.utils.zero82
import java.util.Properties
import kafka.manager.utils.TopicConfigs
/**
* Copied from kafka 0.8.2.1
* https://git-wip-us.apache.org/repos/asf?p=kafka.git;a=blob;f=core/src/main/scala/kafka/log/LogConfig.scala
*/
object Defaults {
val SegmentSize = 1024 * 1024
val SegmentMs = Long.MaxValue
val SegmentJitterMs = 0L
val FlushInterval = Long.MaxValue
val FlushMs = Long.MaxValue
val RetentionSize = Long.MaxValue
val RetentionMs = Long.MaxValue
val MaxMessageSize = Int.MaxValue
val MaxIndexSize = 1024 * 1024
val IndexInterval = 4096
val FileDeleteDelayMs = 60 * 1000L
val DeleteRetentionMs = 24 * 60 * 60 * 1000L
val MinCleanableDirtyRatio = 0.5
val Compact = false
val UncleanLeaderElectionEnable = true
val MinInSyncReplicas = 1
}
/**
* Configuration settings for a log
* @param segmentSize The soft maximum for the size of a segment file in the log
* @param segmentMs The soft maximum on the amount of time before a new log segment is rolled
* @param segmentJitterMs The maximum random jitter subtracted from segmentMs to avoid thundering herds of segment rolling
* @param flushInterval The number of messages that can be written to the log before a flush is forced
* @param flushMs The amount of time the log can have dirty data before a flush is forced
* @param retentionSize The approximate total number of bytes this log can use
* @param retentionMs The age approximate maximum age of the last segment that is retained
* @param maxIndexSize The maximum size of an index file
* @param indexInterval The approximate number of bytes between index entries
* @param fileDeleteDelayMs The time to wait before deleting a file from the filesystem
* @param deleteRetentionMs The time to retain delete markers in the log. Only applicable for logs that are being compacted.
* @param minCleanableRatio The ratio of bytes that are available for cleaning to the bytes already cleaned
* @param compact Should old segments in this log be deleted or deduplicated?
* @param uncleanLeaderElectionEnable Indicates whether unclean leader election is enabled; actually a controller-level property
* but included here for topic-specific configuration validation purposes
* @param minInSyncReplicas If number of insync replicas drops below this number, we stop accepting writes with -1 (or all) required acks
*
*/
case class LogConfig(val segmentSize: Int = Defaults.SegmentSize,
val segmentMs: Long = Defaults.SegmentMs,
val segmentJitterMs: Long = Defaults.SegmentJitterMs,
val flushInterval: Long = Defaults.FlushInterval,
val flushMs: Long = Defaults.FlushMs,
val retentionSize: Long = Defaults.RetentionSize,
val retentionMs: Long = Defaults.RetentionMs,
val maxMessageSize: Int = Defaults.MaxMessageSize,
val maxIndexSize: Int = Defaults.MaxIndexSize,
val indexInterval: Int = Defaults.IndexInterval,
val fileDeleteDelayMs: Long = Defaults.FileDeleteDelayMs,
val deleteRetentionMs: Long = Defaults.DeleteRetentionMs,
val minCleanableRatio: Double = Defaults.MinCleanableDirtyRatio,
val compact: Boolean = Defaults.Compact,
val uncleanLeaderElectionEnable: Boolean = Defaults.UncleanLeaderElectionEnable,
val minInSyncReplicas: Int = Defaults.MinInSyncReplicas) {
def toProps: Properties = {
val props = new Properties()
import LogConfig._
props.put(SegmentBytesProp, segmentSize.toString)
props.put(SegmentMsProp, segmentMs.toString)
props.put(SegmentJitterMsProp, segmentJitterMs.toString)
props.put(SegmentIndexBytesProp, maxIndexSize.toString)
props.put(FlushMessagesProp, flushInterval.toString)
props.put(FlushMsProp, flushMs.toString)
props.put(RetentionBytesProp, retentionSize.toString)
props.put(RententionMsProp, retentionMs.toString)
props.put(MaxMessageBytesProp, maxMessageSize.toString)
props.put(IndexIntervalBytesProp, indexInterval.toString)
props.put(DeleteRetentionMsProp, deleteRetentionMs.toString)
props.put(FileDeleteDelayMsProp, fileDeleteDelayMs.toString)
props.put(MinCleanableDirtyRatioProp, minCleanableRatio.toString)
props.put(CleanupPolicyProp, if(compact) "compact" else "delete")
props.put(UncleanLeaderElectionEnableProp, uncleanLeaderElectionEnable.toString)
props.put(MinInSyncReplicasProp, minInSyncReplicas.toString)
props
}
/**
* Get the absolute value of the given number. If the number is Int.MinValue return 0.
* This is different from java.lang.Math.abs or scala.math.abs in that they return Int.MinValue (!).
*/
def abs(n: Int) = if(n == Integer.MIN_VALUE) 0 else math.abs(n)
def randomSegmentJitter: Long =
if (segmentJitterMs == 0) 0 else abs(scala.util.Random.nextInt()) % math.min(segmentJitterMs, segmentMs)
}
object LogConfig extends TopicConfigs {
val SegmentBytesProp = "segment.bytes"
val SegmentMsProp = "segment.ms"
val SegmentJitterMsProp = "segment.jitter.ms"
val SegmentIndexBytesProp = "segment.index.bytes"
val FlushMessagesProp = "flush.messages"
val FlushMsProp = "flush.ms"
val RetentionBytesProp = "retention.bytes"
val RententionMsProp = "retention.ms"
val MaxMessageBytesProp = "max.message.bytes"
val IndexIntervalBytesProp = "index.interval.bytes"
val DeleteRetentionMsProp = "delete.retention.ms"
val FileDeleteDelayMsProp = "file.delete.delay.ms"
val MinCleanableDirtyRatioProp = "min.cleanable.dirty.ratio"
val CleanupPolicyProp = "cleanup.policy"
val UncleanLeaderElectionEnableProp = "unclean.leader.election.enable"
val MinInSyncReplicasProp = "min.insync.replicas"
val ConfigNames = Seq(SegmentBytesProp,
SegmentMsProp,
SegmentJitterMsProp,
SegmentIndexBytesProp,
FlushMessagesProp,
FlushMsProp,
RetentionBytesProp,
RententionMsProp,
MaxMessageBytesProp,
IndexIntervalBytesProp,
FileDeleteDelayMsProp,
DeleteRetentionMsProp,
MinCleanableDirtyRatioProp,
CleanupPolicyProp,
UncleanLeaderElectionEnableProp,
MinInSyncReplicasProp)
def configNames = ConfigNames
/**
* Parse the given properties instance into a LogConfig object
*/
def fromProps(props: Properties): LogConfig = {
new LogConfig(segmentSize = props.getProperty(SegmentBytesProp, Defaults.SegmentSize.toString).toInt,
segmentMs = props.getProperty(SegmentMsProp, Defaults.SegmentMs.toString).toLong,
segmentJitterMs = props.getProperty(SegmentJitterMsProp, Defaults.SegmentJitterMs.toString).toLong,
maxIndexSize = props.getProperty(SegmentIndexBytesProp, Defaults.MaxIndexSize.toString).toInt,
flushInterval = props.getProperty(FlushMessagesProp, Defaults.FlushInterval.toString).toLong,
flushMs = props.getProperty(FlushMsProp, Defaults.FlushMs.toString).toLong,
retentionSize = props.getProperty(RetentionBytesProp, Defaults.RetentionSize.toString).toLong,
retentionMs = props.getProperty(RententionMsProp, Defaults.RetentionMs.toString).toLong,
maxMessageSize = props.getProperty(MaxMessageBytesProp, Defaults.MaxMessageSize.toString).toInt,
indexInterval = props.getProperty(IndexIntervalBytesProp, Defaults.IndexInterval.toString).toInt,
fileDeleteDelayMs = props.getProperty(FileDeleteDelayMsProp, Defaults.FileDeleteDelayMs.toString).toInt,
deleteRetentionMs = props.getProperty(DeleteRetentionMsProp, Defaults.DeleteRetentionMs.toString).toLong,
minCleanableRatio = props.getProperty(MinCleanableDirtyRatioProp,
Defaults.MinCleanableDirtyRatio.toString).toDouble,
compact = props.getProperty(CleanupPolicyProp, if(Defaults.Compact) "compact" else "delete")
.trim.toLowerCase != "delete",
uncleanLeaderElectionEnable = props.getProperty(UncleanLeaderElectionEnableProp,
Defaults.UncleanLeaderElectionEnable.toString).toBoolean,
minInSyncReplicas = props.getProperty(MinInSyncReplicasProp,Defaults.MinInSyncReplicas.toString).toInt)
}
/**
* Create a log config instance using the given properties and defaults
*/
def fromProps(defaults: Properties, overrides: Properties): LogConfig = {
val props = new Properties(defaults)
props.putAll(overrides)
fromProps(props)
}
/**
* Check that property names are valid
*/
def validateNames(props: Properties) {
import scala.collection.JavaConverters._
for(name <- props.keys().asScala)
require(LogConfig.ConfigNames.asJava.contains(name), "Unknown configuration \"%s\".".format(name))
}
/**
* Check that the given properties contain only valid log config names, and that all values can be parsed.
*/
def validate(props: Properties) {
validateNames(props)
validateMinInSyncReplicas(props)
LogConfig.fromProps(LogConfig().toProps, props) // check that we can parse the values
}
/**
* Check that MinInSyncReplicas is reasonable
* Unfortunately, we can't validate its smaller than number of replicas
* since we don't have this information here
*/
private def validateMinInSyncReplicas(props: Properties) {
val minIsr = props.getProperty(MinInSyncReplicasProp)
if(minIsr != null) {
require(minIsr.toInt >= 1, "Wrong value " + minIsr + " of min.insync.replicas in topic configuration; " +
" Valid values are at least 1")
}
}
def configNamesAndDoc: Seq[(String, String)] = {
configNames.map(n => n -> "")
}
}
|
jvz/sbt-rat-plugin
|
src/main/scala/org/musigma/sbt/rat/SbtRatPlugin.scala
|
<reponame>jvz/sbt-rat-plugin
/*
Copyright 2018 <NAME>
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 org.musigma.sbt.rat
import org.apache.rat.analysis.IHeaderMatcher
import org.apache.rat.analysis.license.FullTextMatchingLicense
import org.apache.rat.analysis.util.HeaderMatcherMultiplexer
import org.apache.rat.document.impl.FileDocument
import org.apache.rat.license.ILicenseFamily
import org.apache.rat.license.SimpleLicenseFamily
import org.apache.rat.mp.util.ScmIgnoreParser
import org.apache.rat.report.claim.{ ClaimStatistic => RatReport }
import org.apache.rat.report.{ IReportable, RatReport => ApacheRatReport }
import org.apache.rat.{ Report, ReportConfiguration, Defaults => RatDefaults }
import sbt.Keys._
import sbt._
import sbt.plugins.JvmPlugin
import scala.collection.JavaConverters._
object SbtRatPlugin extends AutoPlugin {
override def trigger = allRequirements
override def requires = JvmPlugin
object autoImport {
val ratCheck = taskKey[Unit]("Performs a release audit check")
val ratReport = taskKey[RatReport]("Generates a release audit report")
val ratAddDefaultLicenseMatchers = settingKey[Boolean]("Whether to add the default list of license matchers.")
val ratLicenseFamilies = settingKey[Seq[String]]("Specifies the license families to accept.")
val ratLicenses = settingKey[Seq[(String, String, String)]]("Extra license to match--each Seq item is a tuple of (category, name, license text)")
val ratExcludes = settingKey[Seq[File]]("Files to exlucde from audit checks, relative to the baseDirectory")
val ratParseSCMIgnoresAsExcludes = settingKey[Boolean]("Whether to parse source code management system (SCM) ignore files and use their contents as excludes.")
val ratReportStyle = settingKey[String]("Which style of rat report to generate, either 'txt', or 'adoc'")
val ratTarget = settingKey[File]("Output file to save the rat report to")
val ratFailBinaries = settingKey[Boolean]("If true, causes ratCheck to fail if binaries are found")
}
import autoImport._
override lazy val projectSettings: Seq[Setting[_]] = Seq(
ratCheck := SbtRatCheck(
ratReport.value,
ratTarget.value,
ratFailBinaries.value,
streams.value.log
),
ratReport := SbtRatReport(
ratTarget.value,
baseDirectory.value,
ratAddDefaultLicenseMatchers.value,
ratLicenseFamilies.value,
ratLicenses.value,
ratReportStyle.value,
(includeFilter in ratReport).value,
(excludeFilter in ratReport).value
),
ratAddDefaultLicenseMatchers := true,
ratLicenseFamilies := Nil,
ratLicenses := Nil,
ratExcludes := Nil,
ratParseSCMIgnoresAsExcludes := true,
ratReportStyle := "txt",
ratTarget := target.value / ("rat." + ratReportStyle.value),
ratFailBinaries := false,
includeFilter in ratReport := AllPassFilter,
excludeFilter in ratReport := SbtRatExcludeFilter(
baseDirectory.value,
ratExcludes.value,
ratParseSCMIgnoresAsExcludes.value
)
)
override lazy val buildSettings: Seq[Setting[_]] = Nil
override lazy val globalSettings: Seq[Setting[_]] = Seq(
aggregate in ratCheck := false,
aggregate in ratReport := false
)
}
object SbtRatExcludeFilter {
def apply(baseDir: File, customExclusions: Seq[File], parseSCMIgnores: Boolean) = {
val scmExclusionsFilter =
if (parseSCMIgnores) {
val scmExclusions = ScmIgnoreParser.getExclusionsFromSCM(baseDir).asScala
scmExclusions.foldLeft(NothingFilter: sbt.FileFilter) {
case (filter: FileFilter, exclusion) => filter || new ExactFilter(exclusion)
}
} else {
NothingFilter
}
val customExclusionsFilter = customExclusions.foldLeft(NothingFilter: sbt.FileFilter) {
case (filter: FileFilter, exclusion) => filter || new SimpleFileFilter(file => {
val rel = baseDir.relativize(file)
rel.map { f =>
// excludes a file if either
// 1) the exclusion matches the exact path of the file
// 2) the exclusion does not contain a parent directory (i.e.
// it's just a file name) and it matches the name of the file
f.compareTo(exclusion) == 0 || new java.io.File(f.getName).compareTo(exclusion) == 0
}.getOrElse(false)
})
}
scmExclusionsFilter || customExclusionsFilter
}
}
object SbtRatReport {
def makeHeaderMatcher(licenses: Seq[(String, String, String)], addDefaultMatchers: Boolean): IHeaderMatcher = {
val customHeaders = licenses.map { case (category, family, text) =>
val license = new FullTextMatchingLicense()
license.setLicenseFamilyCategory(category)
license.setLicenseFamilyName(family)
license.setFullText(text)
license
}
val defaultHeaders = if (addDefaultMatchers) RatDefaults.DEFAULT_MATCHERS.asScala else Nil
val headerMatcher = new HeaderMatcherMultiplexer((customHeaders ++ defaultHeaders).asJava)
headerMatcher
}
def makeLicenseFamilies(families: Seq[String]): Seq[ILicenseFamily] = {
families.map { new SimpleLicenseFamily(_) }
}
def apply(target: File, baseDir: File,
addDefaultMatchers: Boolean, families: Seq[String], licenses: Seq[(String, String, String)],
ratReportStyle: String,
includeFilter: FileFilter,
excludeFilter: FileFilter): RatReport = {
val targetDir = target.getAbsoluteFile.getParentFile
if (!targetDir.exists()) targetDir.mkdirs()
val inputs: Seq[File] =
PathFinder(baseDir).descendantsExcept(includeFilter, excludeFilter)
.get
.filter { _.isFile }
.map { baseDir.relativize(_).get }
val base = new IReportable {
override def run(report: ApacheRatReport): Unit = {
report.startReport()
inputs.map(new FileDocument(_)).foreach(report.report)
report.endReport()
}
}
val headerMatcher = makeHeaderMatcher(licenses, addDefaultMatchers)
val licenseFamilies = makeLicenseFamilies(families).asJava
val config = new ReportConfiguration
config.setApproveDefaultLicenses(addDefaultMatchers)
config.setApprovedLicenseNames(licenseFamilies)
config.setHeaderMatcher(headerMatcher)
val stylesheet = ratReportStyle match {
case "adoc" => SbtRatPlugin.getClass.getResourceAsStream("/META-INF/asciidoc-rat.xsl")
case "txt" => RatDefaults.getPlainStyleSheet
case _ => RatDefaults.getPlainStyleSheet
}
val writer = new java.io.FileWriter(target)
val results = Report.report(writer, base, stylesheet, config)
results
}
}
object SbtRatCheck {
class UnapprovedLicenseException()
extends RuntimeException("Unapproved licenses")
with FeedbackProvidedException
def apply(report: RatReport, target: File, failBinaries: Boolean, log: Logger): Unit = {
val numUnApproved = report.getNumUnApproved
if (numUnApproved > 0) {
log.error(s"Unapproved licenses found: $numUnApproved. See full report in $target")
}
val numUnApprovedBinaries =
if (failBinaries) {
report.getDocumentCategoryMap.asScala.get("binary").map(_.intValue).getOrElse(0)
} else {
0
}
if (numUnApprovedBinaries > 0) {
log.error(s"Unapproved binaries found: $numUnApprovedBinaries. See full report in $target")
}
if (numUnApproved + numUnApprovedBinaries > 0) {
throw new UnapprovedLicenseException
}
}
}
|
jvz/sbt-rat-plugin
|
src/sbt-test/sbt-rat/apache-headers/build.sbt
|
/*
* 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.
*/
version := "0.1"
scalaVersion := "2.12.4"
ratExcludes := Seq(
file("project/build.properties")
)
excludeFilter in ratReport := (excludeFilter in ratReport).value || ".gitignore"
ratLicenses := Seq(
("BSD3 ", BSD3_LICENSE_NAME, BSD3_LICENSE_TEXT)
)
ratLicenseFamilies := Seq(
BSD3_LICENSE_NAME
)
lazy val BSD3_LICENSE_NAME = "BSD 3-Clause License"
lazy val BSD3_LICENSE_TEXT =
"""
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
|
jvz/sbt-rat-plugin
|
build.sbt
|
<reponame>jvz/sbt-rat-plugin
import xerial.sbt.Sonatype.GitHubHosting
import ReleaseTransformations._
lazy val metadataSettings = Seq(
name := "SBT Release Audit Tool",
organization := "org.musigma",
moduleName := "sbt-rat",
licenses := Seq("Apache License, Version 2.0" -> url("https://www.apache.org/licenses/LICENSE-2.0.txt")),
developers := List(
Developer("jvz", "<NAME>", "<EMAIL>", url("https://musigma.blog/")),
Developer("stevedlawrence", "<NAME>", "<EMAIL>", url("https://github.com/stevedlawrence"))
),
scmInfo := Some(ScmInfo(url("https://github.com/jvz/sbt-rat"), "scm:git:git@github.com:jvz/sbt-rat.git")),
homepage := Some(url("https://github.com/jvz/sbt-rat"))
)
lazy val buildSettings = Seq(
sbtPlugin := true,
crossSbtVersions := Seq("0.13.17", "1.1.2"),
libraryDependencies += "org.apache.rat" % "apache-rat-core" % "0.13",
scriptedLaunchOpts ++= Seq("-Xmx1024M", "-Dplugin.version=" + version.value),
initialCommands in console := "import org.musigma.sbt.rat._"
)
lazy val signatureSettings = Seq(
usePgpKeyHex("CF71A1CAFE39DE54EE88333708CF5E81AFBAB81E"),
useGpgPinentry := false,
useGpgAgent := false,
// override gpg command to as workaround for https://github.com/sbt/sbt-pgp/issues/173
PgpKeys.gpgCommand in Global := (baseDirectory.value / "gpg-no-tty").getAbsolutePath
)
lazy val releaseSettings = Seq(
credentials ++= {
for {
user <- sys.env.get("SONATYPE_USER")
pass <- sys.env.get("SONATYPE_PASS")
} yield Credentials("Sonatype Nexus Repository Manager", "oss.sonatype.org", user, pass)
}.toList,
publishMavenStyle := true,
publishTo := sonatypePublishTo.value,
sonatypeProjectHosting := Some(GitHubHosting("jvz", "sbt-rat", "<NAME>", "<EMAIL>")),
releaseProcess := Seq(
checkSnapshotDependencies,
inquireVersions,
runClean,
releaseStepCommandAndRemaining("^scripted"),
setReleaseVersion,
commitReleaseVersion,
tagRelease,
releaseStepCommandAndRemaining("^publishSigned"),
releaseStepCommand("sonatypeReleaseAll"),
setNextVersion,
commitNextVersion,
pushChanges
)
)
lazy val packageSettings = for (task <- Seq(packageBin, packageSrc, packageDoc))
yield mappings in (Compile, task) ++= Seq(
(baseDirectory.value / "LICENSE", "META-INF/LICENSE"),
(baseDirectory.value / "NOTICE", "META-INF/NOTICE")
)
lazy val root = (project in file("."))
.settings(metadataSettings: _*)
.settings(buildSettings: _*)
.settings(signatureSettings: _*)
.settings(releaseSettings: _*)
.settings(packageSettings: _*)
|
adamwkaczmarek/akka-streams-kafka-examples
|
project/plugins.sbt
|
addSbtPlugin("com.softwaremill.sbt-softwaremill" % "sbt-softwaremill" % "1.6.1")
addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "1.3.19")
|
adamwkaczmarek/akka-streams-kafka-examples
|
core/src/main/scala/com/softwaremill/k8s/example/User.scala
|
package com.softwaremill.k8s.example
case class User(userId: String, regionId: String, gender: String)
|
adamwkaczmarek/akka-streams-kafka-examples
|
core/src/main/scala/com/softwaremill/k8s/example/UserDao.scala
|
package com.softwaremill.k8s.example
import com.typesafe.scalalogging.StrictLogging
class UserDao extends StrictLogging {
def saveUser(user: User): Unit =
logger.info(s"Saving user ${user}")
}
|
adamwkaczmarek/akka-streams-kafka-examples
|
core/src/test/scala/com/softwaremill/k8s/example/UserConsumersManagerSpec.scala
|
<reponame>adamwkaczmarek/akka-streams-kafka-examples<filename>core/src/test/scala/com/softwaremill/k8s/example/UserConsumersManagerSpec.scala
package com.softwaremill.k8s.example
import akka.Done
import akka.actor.ActorSystem
import akka.kafka.scaladsl.Consumer.DrainingControl
import akka.kafka.{CommitterSettings, ConsumerSettings, ProducerSettings}
import akka.kafka.scaladsl.Producer
import akka.kafka.testkit.scaladsl.TestcontainersKafkaLike
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Source
import akka.stream.testkit.javadsl.TestSink
import org.apache.kafka.clients.producer.ProducerRecord
import org.apache.kafka.common.serialization.{StringDeserializer, StringSerializer}
import org.scalatest.BeforeAndAfterAll
import akka.stream.testkit.scaladsl.StreamTestKit.assertAllStagesStopped
import scala.concurrent.duration._
import scala.concurrent.{Await, Future}
class UserConsumersManagerSpec extends SpecBase with TestcontainersKafkaLike {
"UserConsumer atLeastOnce delivery" should "read message from user topic" in assertAllStagesStopped {
//given
val topic = createTopic()
val userDao = new UserDao()
val consumerSettings = consumerDefaults.withGroupId(createGroupId()).withStopTimeout(Duration.Zero)
val committerSettings = CommitterSettings(system)
val consumersManager = new UserConsumersManager(userDao, consumerSettings, committerSettings)
//when
val control: DrainingControl[Done] = consumersManager.consumerAtlLeastOneDelivery(topic).run()
awaitProduce(produceString(topic, List("user1", "user2")))
//then
control.drainAndShutdown().futureValue shouldBe Done
}
}
|
adamwkaczmarek/akka-streams-kafka-examples
|
core/src/main/scala/com/softwaremill/k8s/example/UserConsumersManager.scala
|
package com.softwaremill.k8s.example
import akka.Done
import akka.actor.ActorSystem
import akka.kafka.{CommitterSettings, ConsumerSettings, Subscriptions}
import akka.kafka.scaladsl.Consumer.DrainingControl
import akka.kafka.scaladsl.{Committer, Consumer}
import com.typesafe.scalalogging.StrictLogging
import scala.concurrent.{ExecutionContext, Future}
class UserConsumersManager(userDao: UserDao, consumerSettings: ConsumerSettings[String, String], committerSettings: CommitterSettings)(
implicit val system: ActorSystem,
ec: ExecutionContext
) extends StrictLogging {
def consumerAtlLeastOneDelivery(topic: String) = {
Consumer
.committableSource(consumerSettings, Subscriptions.topics(topic))
.mapAsync(1) { msg =>
processing(msg.record.key, msg.record.value).map(_ => {
val offset = msg.committableOffset
logger.info(s"Comiting offset $offset")
offset
})
}
.toMat(Committer.sink(committerSettings))(DrainingControl.apply)
}
def processing(key: String, value: String): Future[Done] = {
logger.info(s"Processing record : $value")
Future.successful(Done)
}
}
|
adamwkaczmarek/akka-streams-kafka-examples
|
core/src/main/scala/com/softwaremill/k8s/example/Main.scala
|
<reponame>adamwkaczmarek/akka-streams-kafka-examples<filename>core/src/main/scala/com/softwaremill/k8s/example/Main.scala
package com.softwaremill.k8s.example
import java.io.StringWriter
import java.util.concurrent.atomic.AtomicBoolean
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import cats.effect._
import cats.implicits._
import com.typesafe.scalalogging.StrictLogging
import io.prometheus.client.{CollectorRegistry, Counter}
import io.prometheus.client.exporter.common.TextFormat
import io.prometheus.client.hotspot.DefaultExports
import org.http4s.{HttpApp, HttpRoutes}
import org.http4s.dsl.io._
import org.http4s.implicits._
import org.http4s.server.Router
import org.http4s.server.blaze._
object Main extends IOApp with StrictLogging {
private implicit val system = ActorSystem("QuickStart")
private implicit val materializer = ActorMaterializer()
// metrics
DefaultExports.initialize()
val requestCounter: Counter = Counter.build().name("request_count").help("The request count").register()
val isAlive = new AtomicBoolean(true)
val helloWorldService: HttpRoutes[IO] = HttpRoutes.of[IO] {
case GET -> Root / "hello" / name =>
if (name.equalsIgnoreCase("adam")) {
logger.error("Security alert!", new IllegalStateException())
} else {
logger.info(s"Saying hello to $name.")
}
requestCounter.inc()
Ok(s"Hello, $name.")
case POST -> Root / "kill" =>
logger.info("Killing the service")
isAlive.set(false)
Ok()
}
val metricsService: HttpRoutes[IO] = HttpRoutes.of[IO] {
case GET -> Root =>
val writer = new StringWriter
TextFormat.write004(writer, CollectorRegistry.defaultRegistry.metricFamilySamples)
Ok(writer.toString)
}
val statusService: HttpRoutes[IO] = HttpRoutes.of[IO] {
case GET -> Root =>
if (isAlive.get()) {
Ok()
} else {
ServiceUnavailable()
}
}
val httpApp: HttpApp[IO] = Router("/api" -> helloWorldService, "/metrics" -> metricsService, "/status" -> statusService).orNotFound
def run(args: List[String]): IO[ExitCode] =
BlazeServerBuilder[IO]
.bindHttp(8080, "0.0.0.0")
.withHttpApp(httpApp)
.serve
.compile
.drain
.as(ExitCode.Success)
}
|
scalamorphing/slowparser
|
shared/src/main/scala/expert/scalamorphing/slowparser/SlowParser.scala
|
<gh_stars>0
package expert.scalamorphing.slowparser
import fastparse.core.Implicits._
import fastparse.core._
import fastparse.parsers.Combinators._
class SlowParserImpl[+T, Elem, Repr](self: Parser[T, Elem, Repr])
(implicit repr: fastparse.utils.ReprOps[Elem, Repr], delimiters: Parser[Unit, Elem, Repr])
extends ParserApiImpl[T, Elem, Repr](self) with SlowParserApi[T, Elem, Repr] {
override def rep[R](implicit ev: Repeater[T, R]): Parser[R, Elem, Repr] =
Repeat(self, 0, Int.MaxValue, delimiters)
override def rep[R](min: Int = 0, sep: Parser[_, Elem, Repr],
max: Int = Int.MaxValue, exactly: Int = -1)
(implicit ev: Repeater[T, R]): Parser[R, Elem, Repr] = {
if (exactly < 0)
Repeat(Sequence(self, Optional(delimiters), cut = false), min, max, Sequence(sep, Optional(delimiters), cut=false))
else
Repeat(Sequence(self, Optional(delimiters), cut = false), exactly, exactly, Sequence(sep, Optional(delimiters), cut=false))
}
override def |[V >: T](p: Parser[V, Elem, Repr]): Parser[V, Elem, Repr] =
Either[V, Elem, Repr](
Either.flatten(
Vector(
self,
Sequence(p, Optional(delimiters), cut=false)
)
):_*
)
override def ~[V, R](p: Parser[V, Elem, Repr])(implicit ev: Sequencer[T, V, R]): Parser[R, Elem, Repr] =
Sequence.flatten(
Sequence(
self,
Sequence(Optional(delimiters),
p,
cut=false),
cut=false
).asInstanceOf[Sequence[R, R, R, Elem, Repr]])
override def ~/[V, R](p: Parser[V, Elem, Repr])(implicit ev: Sequencer[T, V, R]): Parser[R, Elem, Repr] =
Sequence.flatten(Sequence(self, p, cut=true).asInstanceOf[Sequence[R, R, R, Elem, Repr]])
def plural[R](pluralSuffix: Parser[Unit, Elem, Repr]): Parser[R, Elem, Repr] =
Sequence(self, pluralSuffix, cut = false).asInstanceOf[Sequence[R, R, R, Elem, Repr]]
}
trait SlowParserApi[+T, Elem, Repr]
extends ParserApi[T, Elem, Repr] {
def plural[R](pluralSuffix: Parser[Unit, Elem, Repr]): Parser[R, Elem, Repr]
}
object api extends fastparse.StringApi {
implicit def parserApi[T, V](p: T)(implicit c: T => fastparse.core.Parser[V, Char, String],
reprOps: fastparse.utils.ReprOps[Char, String],
delimiters: Set[Char]): SlowParserApi[V, Char, String] =
new SlowParserImpl[V, Char, String](p)(reprOps, P(CharsWhile(delimiters.contains)))
}
|
scalamorphing/slowparser
|
build.sbt
|
<gh_stars>0
import sbt.Keys.version
scalaVersion in ThisBuild := "2.11.8"
lazy val slowparser = {
crossProject in file(".")
}.settings(
Seq(
name := "slowparser",
version := "0.0.1",
organization := "expert.scalamorphing",
libraryDependencies += "com.lihaoyi" %%% "fastparse" % "0.4.1",
libraryDependencies += "org.scalactic" %%% "scalactic" % "3.0.1" % "test",
libraryDependencies += "org.scalatest" %%% "scalatest" % "3.0.1" % "test",
scapegoatVersion := "1.1.0",
credentials += Credentials(Path.userHome / ".ivy2" / ".credentials"),
publishTo := Some("bintray-scalamorphing-slowparser" at "https://api.bintray.com/maven/scalamorphing/maven/slowparser")
)
)
lazy val slowparserJS = slowparser.js.settings(
Seq(
version := "0.0.1"
)
)
lazy val slowparserJVM = slowparser.jvm.settings(
Seq(
version := "0.0.1"
)
)
|
scalamorphing/slowparser
|
shared/src/test/scala/expert/scalamorphing/slowparser/SlowParserTest.scala
|
package expert.scalamorphing.slowparser
import org.scalatest.{FlatSpec, Matchers}
import scala.collection.mutable.ArrayBuffer
class SlowParserTest extends FlatSpec with Matchers {
implicit val delimiters = Set[Char](" \n\r\t" :_*)
import expert.scalamorphing.slowparser.api._
"plurals" should "be parsed" in {
val pluralQueen: P[String] = P("Queen".!.plural("s".?))
val queensParse = pluralQueen.parse("Queens")
queensParse should be (Parsed.Success("Queen", "Queens".length))
}
"whitespace" should "be skipped with ~ parser combinator" in {
val parser: P[String] = P("Queen".! ~ "is" ~ "a" ~ "great" ~ "person")
val input = "Queen is a great person"
val parsed = parser.parse(input)
parsed should be (Parsed.Success("Queen", input.length))
}
"whitespace" should "be skipped with | parser combinator" in {
val parser: P[String] = P(("Queen" | "King" | "Knight").!)
val input = "Queen "
val parsed = parser.parse(input)
parsed should be (Parsed.Success("Queen", "Queen".length))
}
"whitespace" should "be skipped with rep parser combinator" in {
val parser: P[Seq[String]] = P("Queen".!.rep(sep = ","))
val input = 1 to 10 map (_ => "Queen , ")
val parsed = parser.parse(input.mkString + "Queen")
parsed should be (
Parsed.Success(
ArrayBuffer((input ++ Seq("Queen")).map(_ => "Queen") :_*),
(input.mkString + "Queen").length
)
)
}
}
|
scalamorphing/slowparser
|
jvm/build.sbt
|
name := "slowparser"
version := "0.0.1"
|
scalamorphing/slowparser
|
project/plugins.sbt
|
resolvers += "Typesafe Repository" at "https://repo.typesafe.com/typesafe/releases/"
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "0.6.14")
addSbtPlugin("com.sksamuel.scapegoat" %% "sbt-scapegoat" % "1.0.4")
|
laidback/cbdi
|
build.sbt
|
name := "fti-jerry-service"
version := "1.0"
maintainer := "<NAME> <<EMAIL>>"
packageSummary := "Jerry internal API Service"
//javaHome := Some(file("/path/to/java"))
//javaOptions += "-Xmx256"
//javacOptions ++= Seq("-source", "1.5", "-target", "1.5")
scalaVersion := "2.11.8"
//scalaHome := Some(file("/path/to/scala"))
scalacOptions += "-deprecation"
enablePlugins(JavaAppPackaging, GitBranchPrompt)
fork in run := true
libraryDependencies ++= Seq (
"com.typesafe" % "config" % "1.3.1",
"com.typesafe.akka" %% "akka-actor" % "2.4.18",
"com.typesafe.akka" %% "akka-stream" % "2.4.18",
"com.typesafe.akka" %% "akka-stream-testkit" % "2.4.18",
"com.typesafe.akka" %% "akka-remote" % "2.4.18",
"com.typesafe.akka" %% "akka-cluster" % "2.4.18",
"com.typesafe.akka" %% "akka-cluster-tools" % "2.4.18",
"com.typesafe.akka" %% "akka-testkit" % "2.4.18",
"com.typesafe.akka" %% "akka-slf4j" % "2.4.18",
"com.typesafe.akka" %% "akka-http" % "10.0.5",
"com.typesafe.akka" %% "akka-http-spray-json" % "10.0.5",
"com.typesafe.akka" %% "akka-http-testkit" % "10.0.5",
"com.lightbend.akka" %% "akka-management-cluster-http" % "0.3",
"com.lihaoyi" %% "scalatags" % "0.6.5",
"ch.qos.logback" % "logback-classic" % "1.2.1" % Runtime,
"org.scalatest" %% "scalatest" % "3.0.3",
"org.specs2" %% "specs2-core" % "3.8.9" % Test
)
mappings in Universal += {
val conf = (resourceDirectory in Compile).value / "application.conf"
conf -> "conf/application.conf"
}
mappings in Universal += {
val log = (resourceDirectory in Compile).value / "logback.xml"
log -> "conf/logback.xml"
}
// Native packager docker settings
packageName in Docker := name.value
version in Docker := version.value
maintainer in Docker := maintainer.value
// dockerBaseImage := "registry.gitlab01.fti.int/lcb/fti-akka-skeleton/scala-sbt-docker"
dockerRepository := Some("registry.gitlab01.fti.int/lcb")
dockerUpdateLatest := true
|
laidback/cbdi
|
src/main/scala/Main.scala
|
package io.github.laidback.cbdi
import akka.Done
import akka.NotUsed
import akka.util._
import akka.event.{Logging, LoggingAdapter}
import akka.actor._
import akka.stream._
import akka.stream.scaladsl._
import akka.http._
import akka.http.scaladsl._
import akka.http.scaladsl.server._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.model._
import scala.io.StdIn
import scala.util.{Try, Success, Failure}
import scala.concurrent.Future
trait RemoteService
trait HttpRemoteService extends RemoteService {
implicit val httpClient: Flow[(HttpRequest, NotUsed), (Try[HttpResponse], NotUsed), _]
}
trait HttpRemoteServiceImpl extends HttpRemoteService {
implicit val httpClient: Flow[(HttpRequest, NotUsed), (Try[HttpResponse], NotUsed), _]
}
trait TopComponent
extends UserComponent
with ProjectComponent
trait TopComponentImpl
extends TopComponent
with UserComponentImpl
with ProjectComponentImpl
abstract class MyApp extends TopComponent
object Main extends App
with ProjectComponentImpl
with UserComponentImpl {
/** Instantiate global implicits */
implicit val actorSystem = ActorSystem()
implicit val materializer = ActorMaterializer()
implicit val executionContext = actorSystem.dispatcher
implicit val log: LoggingAdapter = Logging(actorSystem, getClass)
/** Wire up your application calling your components directly */
val userComponent = new UserServiceComponentImpl
with UserRepositoryComponentImpl
// with HttpRemoteServiceImpl
userComponent.userService.create("Lukas", "From Component")
val projectComponent = new ProjectServiceComponentImpl
with ProjectRepositoryComponentImpl
projectComponent.projectService.create("MyProject", User("Lukas", "From Component"))
/** Wire up your application injected through the traits */
userService.create("Lukas", "From Trait with Service")
userRepository.create(User("Lukas", "From Trait with Repo"))
projectService.create("MyProject", User("Lukas", "From Trait with Service"))
projectRepository.create(Project("MyProject", User("Lukas", "From Trait with Repo")))
/** Wire up your application calling the application directly with its dependency */
val appWithTop = new MyApp with TopComponentImpl
appWithTop.userService.create("Lukas", "From App with Top with Service")
appWithTop.userRepository.create(User("Lukas", "From App with Top with Repo"))
appWithTop.projectService.create("MyProject", User("Lukas", "From App with Top with Service"))
appWithTop.projectRepository.create(Project("MyProject", User("Lukas", "From App with Top with Repo")))
/** Wire up your application calling the application directly with its dependencies separate */
val appWithSingle = new MyApp with UserComponentImpl with ProjectComponentImpl
appWithSingle.userService.create("Lukas", "From App no Top with Service")
appWithSingle.userRepository.create(User("Lukas", "From App no Top with Repo"))
appWithSingle.projectService.create("MyProject", User("Lukas", "From App no Top with Service"))
appWithSingle.projectRepository.create(Project("MyProject", User("Lukas", "From App no Top with Repo")))
System.exit(0)
}
|
laidback/cbdi
|
src/test/scala/RoutesTestkit.scala
|
<reponame>laidback/cbdi
package de.fti.skeleton
import org.scalatest._
import akka.http.scaladsl.server._
import akka.http.scaladsl.model._
import akka.http.scaladsl.testkit.ScalatestRouteTest
import com.typesafe.config.ConfigFactory
class RoutesTestkit extends WordSpec
with Matchers
with ScalatestRouteTest
with HomeComponent
with StatusComponent {
val config = ConfigFactory.load()
val homeActor = system.actorOf(HomeActor.props)
val statusActor = system.actorOf(StatusActor.props)
"Home Page" should {
"GET home page should return 200 OK" in {
val getRequest = HttpRequest(HttpMethods.GET, uri="/")
getRequest ~> homeRoute ~> check {
status.isSuccess() shouldEqual true
}
}
}
"Status Page" should {
"GET status page should return 200 OK" in {
val getRequest = HttpRequest(HttpMethods.GET, uri="/status")
getRequest ~> statusRoute ~> check {
status.isSuccess() shouldEqual true
}
}
}
}
|
laidback/cbdi
|
src/main/scala/Project.scala
|
package io.github.laidback.cbdi
case class Project(name: String, user: User)
trait ProjectRepositoryComponent {
val projectRepository: ProjectRepository
trait ProjectRepository {
def create(project: Project): Unit
}
}
trait ProjectRepositoryComponentImpl extends ProjectRepositoryComponent {
override val projectRepository: ProjectRepository = new ProjectRepositoryImpl
private class ProjectRepositoryImpl extends ProjectRepository {
override def create(project: Project): Unit = println(project)
}
}
trait ProjectServiceComponent {
val projectService: ProjectService
trait ProjectService {
def create(name: String, user: User): Unit
}
}
trait ProjectServiceComponentImpl extends ProjectServiceComponent {
this: ProjectRepositoryComponent =>
override val projectService: ProjectService = new ProjectServiceImpl
private class ProjectServiceImpl extends ProjectService {
def create(name: String, user: User): Unit =
projectRepository.create(Project(name, user))
}
}
trait ProjectComponent extends ProjectServiceComponent with ProjectRepositoryComponent
trait ProjectComponentImpl extends ProjectComponent
with ProjectServiceComponentImpl
with ProjectRepositoryComponentImpl
|
laidback/cbdi
|
src/main/scala/User.scala
|
<gh_stars>0
package io.github.laidback.cbdi
case class User(username: String, password: String)
trait UserRepositoryComponent {
val userRepository: UserRepository
trait UserRepository {
def create(user: User): Unit
}
}
trait UserRepositoryComponentImpl extends UserRepositoryComponent {
override val userRepository: UserRepository = new UserRepositoryImpl
private class UserRepositoryImpl extends UserRepository {
override def create(user: User): Unit = println(user)
}
}
trait UserServiceComponent {
val userService: UserService
trait UserService {
def create(username: String, password: String): Unit
}
}
trait UserServiceComponentImpl extends UserServiceComponent {
this: UserRepositoryComponent =>
// this: UserRepositoryComponent with HttpRemoteService =>
override val userService: UserService = new UserServiceImpl
private class UserServiceImpl extends UserService {
def create(username: String, password: String): Unit =
userRepository.create(User(username, password))
}
}
trait UserComponent extends UserServiceComponent
with UserRepositoryComponent
// with HttpRemoteServiceImpl
trait UserComponentImpl extends UserComponent
with UserServiceComponentImpl
with UserRepositoryComponentImpl
// with HttpRemoteServiceImpl
|
laidback/cbdi
|
src/main/scala/RemoteService.scala
|
package io.github.laidback.cbdi
case class Remote(username: String, password: String)
trait RemoteRepositoryComponent {
val userRepository: RemoteRepository
trait RemoteRepository {
def create(user: Remote): Unit
}
}
trait RemoteRepositoryComponentImpl extends RemoteRepositoryComponent {
override val userRepository: RemoteRepository = new RemoteRepositoryImpl
private class RemoteRepositoryImpl extends RemoteRepository {
override def create(user: Remote): Unit = println(user)
}
}
trait RemoteServiceComponent {
val userService: RemoteService
trait RemoteService {
def create(username: String, password: String): Unit
}
}
trait RemoteServiceComponentImpl extends RemoteServiceComponent {
this: RemoteRepositoryComponent =>
override val userService: RemoteService = new RemoteServiceImpl
private class RemoteServiceImpl extends RemoteService {
def create(username: String, password: String): Unit =
userRepository.create(Remote(username, password))
}
}
trait RemoteComponent extends RemoteServiceComponent with RemoteRepositoryComponent
trait RemoteComponentImpl extends RemoteComponent
with RemoteServiceComponentImpl
with RemoteRepositoryComponentImpl
|
laidback/cbdi
|
project/plugins.sbt
|
<reponame>laidback/cbdi<gh_stars>0
resolvers += "Typesafe repository" at "https://repo.typesafe.com/typesafe/releases/"
resolvers += "Scoverate bintray" at "https://dl.bintray.com/sksamuel/sbt-plugins/"
addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "1.2.0-M8")
addSbtPlugin("com.typesafe.sbt" % "sbt-git" % "0.8.5")
addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.5.0")
|
EvanKrall/marathon
|
src/test/scala/mesosphere/marathon/state/MarathonStoreTest.scala
|
package mesosphere.marathon.state
import java.lang.{ Boolean => JBoolean }
import java.util.concurrent.{ ExecutionException, Future => JFuture }
import mesosphere.marathon.state.PathId._
import mesosphere.marathon.{ MarathonSpec, StorageException }
import org.apache.mesos.state.{ InMemoryState, State, Variable }
import org.mockito.Matchers._
import org.mockito.Mockito._
import scala.collection.immutable.Seq
import scala.concurrent.duration._
import scala.concurrent.{ Await, Future }
import scala.language.postfixOps
class MarathonStoreTest extends MarathonSpec {
test("Fetch") {
val state = mock[State]
val future = mock[JFuture[Variable]]
val variable = mock[Variable]
val appDef = AppDefinition(id = "testApp".toPath, args = Some(Seq("arg")))
when(variable.value()).thenReturn(appDef.toProtoByteArray)
when(future.get(anyLong, any[TimeUnit])).thenReturn(variable)
when(state.fetch("app:testApp")).thenReturn(future)
when(state.fetch("__internal__:app:storage:version")).thenReturn(currentVersionFuture)
when(state.store(currentVersionVariable)).thenReturn(currentVersionFuture)
val store = new MarathonStore[AppDefinition](state, () => AppDefinition())
val res = store.fetch("testApp")
verify(state).fetch("app:testApp")
assert(Some(appDef) == Await.result(res, 5.seconds), "Should return the expected AppDef")
}
test("FetchFail") {
val state = mock[State]
val future = mock[JFuture[Variable]]
when(future.get(anyLong, any[TimeUnit])).thenReturn(null)
when(state.fetch("app:testApp")).thenReturn(future)
when(state.fetch("__internal__:app:storage:version")).thenReturn(currentVersionFuture)
when(state.store(currentVersionVariable)).thenReturn(currentVersionFuture)
val store = new MarathonStore[AppDefinition](state, () => AppDefinition())
val res = store.fetch("testApp")
verify(state).fetch("app:testApp")
intercept[StorageException] {
Await.result(res, 5.seconds)
}
}
test("Modify") {
val state = mock[State]
val future = mock[JFuture[Variable]]
val variable = mock[Variable]
val appDef = AppDefinition(id = "testApp".toPath, args = Some(Seq("arg")))
val newAppDef = appDef.copy(id = "newTestApp".toPath)
val newVariable = mock[Variable]
val newFuture = mock[JFuture[Variable]]
when(newVariable.value()).thenReturn(newAppDef.toProtoByteArray)
when(newFuture.get(anyLong, any[TimeUnit])).thenReturn(newVariable)
when(variable.value()).thenReturn(appDef.toProtoByteArray)
when(variable.mutate(any())).thenReturn(newVariable)
when(future.get(anyLong, any[TimeUnit])).thenReturn(variable)
when(state.fetch("app:testApp")).thenReturn(future)
when(state.store(newVariable)).thenReturn(newFuture)
when(state.fetch("__internal__:app:storage:version")).thenReturn(currentVersionFuture)
when(state.store(currentVersionVariable)).thenReturn(currentVersionFuture)
val store = new MarathonStore[AppDefinition](state, () => AppDefinition())
val res = store.modify("testApp") { _ =>
newAppDef
}
assert(Some(newAppDef) == Await.result(res, 5.seconds), "Should return the new AppDef")
verify(state).fetch("app:testApp")
verify(state).store(newVariable)
}
test("ModifyFail") {
val state = mock[State]
val future = mock[JFuture[Variable]]
val variable = mock[Variable]
val appDef = AppDefinition(id = "testApp".toPath, args = Some(Seq("arg")))
val newAppDef = appDef.copy(id = "newTestApp".toPath)
val newVariable = mock[Variable]
val newFuture = mock[JFuture[Variable]]
when(newVariable.value()).thenReturn(newAppDef.toProtoByteArray)
when(newFuture.get(anyLong, any[TimeUnit])).thenReturn(null)
when(variable.value()).thenReturn(appDef.toProtoByteArray)
when(variable.mutate(any())).thenReturn(newVariable)
when(future.get(anyLong, any[TimeUnit])).thenReturn(variable)
when(state.fetch("app:testApp")).thenReturn(future)
when(state.store(newVariable)).thenReturn(newFuture)
when(state.fetch("__internal__:app:storage:version")).thenReturn(currentVersionFuture)
when(state.store(currentVersionVariable)).thenReturn(currentVersionFuture)
val store = new MarathonStore[AppDefinition](state, () => AppDefinition())
val res = store.modify("testApp") { _ =>
newAppDef
}
intercept[StorageException] {
Await.result(res, 5.seconds)
}
}
test("Expunge") {
val state = mock[State]
val future = mock[JFuture[Variable]]
val variable = mock[Variable]
val resultFuture = mock[JFuture[JBoolean]]
when(future.get(anyLong, any[TimeUnit])).thenReturn(variable)
when(state.fetch("app:testApp")).thenReturn(future)
when(resultFuture.get(anyLong, any[TimeUnit])).thenReturn(true)
when(state.expunge(variable)).thenReturn(resultFuture)
when(state.fetch("__internal__:app:storage:version")).thenReturn(currentVersionFuture)
when(state.store(currentVersionVariable)).thenReturn(currentVersionFuture)
val store = new MarathonStore[AppDefinition](state, () => AppDefinition())
val res = store.expunge("testApp")
assert(Await.result(res, 5.seconds), "Expunging existing variable should return true")
verify(state).fetch("app:testApp")
verify(state).expunge(variable)
}
test("ExpungeFail") {
val state = mock[State]
val future = mock[JFuture[Variable]]
val variable = mock[Variable]
val resultFuture = mock[JFuture[JBoolean]]
when(future.get(anyLong, any[TimeUnit])).thenReturn(variable)
when(state.fetch("app:testApp")).thenReturn(future)
when(resultFuture.get(anyLong, any[TimeUnit])).thenReturn(null)
when(state.expunge(variable)).thenReturn(resultFuture)
when(state.fetch("__internal__:app:storage:version")).thenReturn(currentVersionFuture)
when(state.store(currentVersionVariable)).thenReturn(currentVersionFuture)
val store = new MarathonStore[AppDefinition](state, () => AppDefinition())
val res = store.expunge("testApp")
intercept[StorageException] {
Await.result(res, 5.seconds)
}
}
test("Names") {
val state = new InMemoryState
def populate(key: String, value: Array[Byte]) = {
val variable = state.fetch(key).get().mutate(value)
state.store(variable)
}
populate("app:foo", Array())
populate("app:bar", Array())
populate("no_match", Array())
populate("__internal__:app:storage:version", StorageVersions.current.toByteArray)
val store = new MarathonStore[AppDefinition](state, () => AppDefinition())
val res = store.names()
assert(Set("foo", "bar") == Await.result(res, 5.seconds).toSet, "Should return all application keys")
}
test("NamesFail") {
val state = mock[State]
when(state.names()).thenThrow(classOf[ExecutionException])
when(state.fetch("__internal__:app:storage:version")).thenReturn(currentVersionFuture)
when(state.store(currentVersionVariable)).thenReturn(currentVersionFuture)
val store = new MarathonStore[AppDefinition](state, () => AppDefinition())
val res = store.names()
assert(Await.result(res, 5.seconds).isEmpty, "Should return empty iterator")
}
test("ConcurrentModifications") {
import mesosphere.util.ThreadPoolContext.context
val state = new InMemoryState
val variable = state.fetch("__internal__:app:storage:version").get().mutate(StorageVersions.current.toByteArray)
state.store(variable)
val store = new MarathonStore[AppDefinition](state, () => AppDefinition())
Await.ready(store.store("foo", AppDefinition(id = "foo".toPath, instances = 0)), 2.seconds)
def plusOne() = {
store.modify("foo") { f =>
val appDef = f()
appDef.copy(instances = appDef.instances + 1)
}
}
val results = for (_ <- 0 until 1000) yield plusOne()
val res = Future.sequence(results)
Await.ready(res, 5.seconds)
assert(1000 == Await.result(store.fetch("foo"), 5.seconds).map(_.instances)
.getOrElse(0), "Instances of 'foo' should be set to 1000")
}
private val currentVersionVariable = {
val versionVariable = mock[Variable]
when(versionVariable.value()).thenReturn(StorageVersions.current.toByteArray)
when(versionVariable.mutate(any[Array[Byte]]())).thenReturn(versionVariable)
versionVariable
}
private val currentVersionFuture = {
val versionFuture = mock[JFuture[Variable]]
when(versionFuture.get(anyLong(), any[TimeUnit])).thenReturn(currentVersionVariable)
versionFuture
}
}
|
EvanKrall/marathon
|
src/main/scala/mesosphere/marathon/tasks/PortsMatcher.scala
|
<filename>src/main/scala/mesosphere/marathon/tasks/PortsMatcher.scala<gh_stars>0
package mesosphere.marathon.tasks
import scala.util.{ Try, Random }
import org.apache.mesos.Protos.Offer
import mesosphere.mesos.protos
import mesosphere.mesos.protos.{ RangesResource, Resource }
import mesosphere.marathon.PortResourceException
import mesosphere.marathon.state.AppDefinition
import mesosphere.marathon.state.Container
import mesosphere.marathon.state.Container.Docker.PortMapping
import mesosphere.util.Logging
import scala.collection.JavaConverters._
/**
* Utility class for checking if the ports resource in an offer matches the requirements of an app.
*/
class PortsMatcher(app: AppDefinition, offer: Offer) extends Logging {
val portsResource = offer.getResourcesList.asScala
.find(_.getName == Resource.PORTS)
val offeredPortRanges = portsResource
.map(_.getRanges.getRangeList.asScala)
.getOrElse(Nil)
val role = portsResource.map(_.getRole).getOrElse("*")
def portRanges: Option[RangesResource] = {
val portMappings: Option[Seq[Container.Docker.PortMapping]] =
app.container.flatMap(_.docker.map(_.portMappings)).filter(_.nonEmpty)
(app.ports, portMappings) match {
case (Nil, None) =>
Some(RangesResource(Resource.PORTS, Nil))
case (appPorts, None) if app.requirePorts =>
appPortRanges
case (appPorts, None) =>
appPortRanges.orElse(randomPortRanges)
case (_, Some(mappings)) =>
val assigned: Try[RangesResource] = mappedPortRanges(mappings)
assigned.recover {
case PortResourceException(msg) => log.info(msg)
}: Any
assigned.toOption
case _ =>
Some(RangesResource(Resource.PORTS, Nil))
}
}
def matches: Boolean = {
portRanges.isDefined
}
def ports: Seq[Long] = {
portRanges.map(_.ranges.flatMap(_.asScala())).getOrElse(Nil)
}
private def appPortRanges: Option[RangesResource] = {
val sortedPorts = app.ports.sorted
val firstPort = sortedPorts.head
val lastPort = sortedPorts.last
// Monotonically increasing ports
if (firstPort + sortedPorts.size - 1 == lastPort &&
offeredPortRanges.exists(r => r.getBegin <= firstPort && r.getEnd >= lastPort)) {
Some(RangesResource(Resource.PORTS, Seq(protos.Range(firstPort.longValue, lastPort.longValue)), role))
}
else if (app.ports.forall(p => offeredPortRanges.exists(r => r.getBegin <= p && r.getEnd >= p))) {
val portRanges = app.ports.map(p => protos.Range(p.longValue, p.longValue))
Some(RangesResource(Resource.PORTS, portRanges, role))
}
else {
None
}
}
private def randomPortRanges: Option[RangesResource] = {
for (range <- offeredPortRanges) {
// TODO use multiple ranges if one is not enough
if (range.getEnd - range.getBegin + 1 >= app.ports.length) {
val maxOffset = (range.getEnd - range.getBegin - app.ports.length + 2).toInt
val firstPort = range.getBegin.toInt + Random.nextInt(maxOffset)
val rangeProto = protos.Range(firstPort, firstPort + app.ports.length - 1)
return Some(
RangesResource(Resource.PORTS, Seq(rangeProto), role)
)
}
}
None
}
/**
* Returns Some(rangesResources) if the zero-valued docker host-ports
* can be assigned to ANY port from the resource offer, AND all other
* (non-zero-valued) docker host-ports are available in the resource offer.
*/
private def mappedPortRanges(mappings: Seq[PortMapping]): Try[RangesResource] =
Try {
val availablePorts: Iterator[Int] =
offeredPortRanges.foldLeft(Iterator.apply[Int]()) {
(acc, r) => acc ++ Iterator.range(r.getBegin.toInt, r.getEnd.toInt + 1)
}
val scalaPortRanges: Seq[Range] =
offeredPortRanges.map { r => r.getBegin.toInt to r.getEnd.toInt }
def portInOffer(port: Int): Boolean =
scalaPortRanges.exists(_ contains port)
val mappingsWithAssignedRandoms = mappings.map {
case PortMapping(containerPort, 0, protocol) =>
if (!availablePorts.hasNext) throw PortResourceException(
s"Insufficient ports in offer for app [${app.id}]"
)
PortMapping(containerPort, availablePorts.next, protocol)
case pm: PortMapping => pm
}
// ensure that each assigned port is present in the resource offer
val allPortsInOffer = mappingsWithAssignedRandoms.forall { mapping =>
portInOffer(mapping.hostPort)
}
if (!allPortsInOffer)
throw PortResourceException(
"All assigned host ports must be present in the resource offer.\n" +
"Assigned: [" + mappingsWithAssignedRandoms.mkString(", ") + "]"
)
val portRanges = mappingsWithAssignedRandoms.map {
case PortMapping(containerPort, hostPort, protocol) =>
protos.Range(hostPort.longValue, hostPort.longValue)
}
RangesResource(Resource.PORTS, portRanges, role)
}
}
|
EvanKrall/marathon
|
src/main/scala/mesosphere/marathon/health/MarathonHealthCheckManager.scala
|
package mesosphere.marathon.health
import javax.inject.{ Inject, Named }
import scala.concurrent.Future
import scala.concurrent.duration._
import akka.actor.{ ActorRef, ActorSystem, Props }
import akka.event.EventStream
import akka.pattern.ask
import akka.util.Timeout
import org.apache.mesos.Protos.TaskStatus
import mesosphere.marathon.event.{ AddHealthCheck, EventModule, RemoveHealthCheck }
import mesosphere.marathon.state.{ AppDefinition, PathId }
import mesosphere.marathon.tasks.TaskTracker
import mesosphere.util.ThreadPoolContext.context
class MarathonHealthCheckManager @Inject() (
system: ActorSystem,
@Named(EventModule.busName) eventBus: EventStream,
taskTracker: TaskTracker) extends HealthCheckManager {
protected[this] case class ActiveHealthCheck(
healthCheck: HealthCheck,
actor: ActorRef)
protected[this] var appHealthChecks = Map[PathId, Set[ActiveHealthCheck]]()
override def list(appId: PathId): Set[HealthCheck] =
appHealthChecks.get(appId).fold(Set[HealthCheck]()) { activeHealthChecks =>
activeHealthChecks.map(_.healthCheck)
}
protected[this] def find(
appId: PathId,
healthCheck: HealthCheck): Option[ActiveHealthCheck] =
appHealthChecks.get(appId).flatMap {
_.find { _.healthCheck == healthCheck }
}
override def add(appId: PathId, healthCheck: HealthCheck): Unit = {
val healthChecksForApp =
appHealthChecks.get(appId).getOrElse(Set[ActiveHealthCheck]())
if (!healthChecksForApp.exists { _.healthCheck == healthCheck }) {
val ref = system.actorOf(
Props(classOf[HealthCheckActor], appId, healthCheck, taskTracker, eventBus)
)
val newHealthChecksForApp =
healthChecksForApp + ActiveHealthCheck(healthCheck, ref)
appHealthChecks += (appId -> newHealthChecksForApp)
}
eventBus.publish(AddHealthCheck(appId, healthCheck))
}
override def addAllFor(app: AppDefinition): Unit =
app.healthChecks.foreach(add(app.id, _))
override def remove(appId: PathId, healthCheck: HealthCheck): Unit = {
for (activeHealthChecks <- appHealthChecks.get(appId)) {
activeHealthChecks.find(_.healthCheck == healthCheck) foreach deactivate
val newHealthChecksForApp =
activeHealthChecks.filterNot { _.healthCheck == healthCheck }
appHealthChecks =
if (newHealthChecksForApp.isEmpty) appHealthChecks - appId
else appHealthChecks + (appId -> newHealthChecksForApp)
}
eventBus.publish(RemoveHealthCheck(appId))
}
override def removeAll(): Unit = appHealthChecks.keys foreach removeAllFor
override def removeAllFor(appId: PathId): Unit =
for (activeHealthChecks <- appHealthChecks.get(appId)) {
activeHealthChecks foreach deactivate
appHealthChecks = appHealthChecks - appId
}
override def reconcileWith(app: AppDefinition): Unit = {
val existingHealthChecks = list(app.id)
val toRemove = existingHealthChecks -- app.healthChecks
val toAdd = app.healthChecks -- existingHealthChecks
for (hc <- toRemove) remove(app.id, hc)
for (hc <- toAdd) add(app.id, hc)
}
override def update(taskStatus: TaskStatus, version: String): Unit = {}
override def status(
appId: PathId,
taskId: String): Future[Seq[Option[Health]]] = {
import mesosphere.marathon.health.HealthCheckActor.GetTaskHealth
implicit val timeout: Timeout = Timeout(2, SECONDS)
appHealthChecks.get(appId) match {
case Some(activeHealthCheckSet) => Future.sequence(
activeHealthCheckSet.toSeq.map {
case ActiveHealthCheck(_, actor) => (actor ? GetTaskHealth(taskId)).mapTo[Option[Health]]
}
)
case None => Future.successful(Nil)
}
}
protected[this] def deactivate(healthCheck: ActiveHealthCheck): Unit =
system stop healthCheck.actor
}
|
EvanKrall/marathon
|
src/test/scala/mesosphere/marathon/api/v2/AppUpdateTest.scala
|
<reponame>EvanKrall/marathon
package mesosphere.marathon.api.v2
import javax.validation.Validation
import mesosphere.marathon.MarathonSpec
import mesosphere.marathon.health.HealthCheck
import mesosphere.marathon.state.Container._
import mesosphere.marathon.state.{ Container, PathId, Timestamp, UpgradeStrategy }
import org.apache.mesos.{ Protos => mesos }
import scala.collection.immutable.Seq
import scala.collection.JavaConverters._
import scala.concurrent.duration._
class AppUpdateTest extends MarathonSpec {
test("Validation") {
val validator = Validation.buildDefaultValidatorFactory().getValidator
def shouldViolate(update: AppUpdate, path: String, template: String) = {
val violations = validator.validate(update).asScala
assert(violations.exists(v =>
v.getPropertyPath.toString == path && v.getMessageTemplate == template))
}
def shouldNotViolate(update: AppUpdate, path: String, template: String) = {
val violations = validator.validate(update).asScala
assert(!violations.exists(v =>
v.getPropertyPath.toString == path && v.getMessageTemplate == template))
}
val update = AppUpdate()
shouldViolate(
update.copy(ports = Some(Seq(9000, 8080, 9000))),
"ports",
"Elements must be unique"
)
}
test("SerializationRoundtrip") {
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import mesosphere.jackson.CaseClassModule
import mesosphere.marathon.api.v2.json.MarathonModule
val mapper = new ObjectMapper
mapper.registerModule(DefaultScalaModule)
mapper.registerModule(new MarathonModule)
mapper.registerModule(CaseClassModule)
val update0 = AppUpdate(container = Some(Container.Empty))
val json0 = mapper.writeValueAsString(update0)
val readResult0 = mapper.readValue(json0, classOf[AppUpdate])
assert(readResult0 == update0)
val update1 = AppUpdate(
cmd = Some("sleep 60"),
args = None,
user = Some("nobody"),
env = Some(Map("LANG" -> "en-US")),
instances = Some(16),
cpus = Some(2.0),
mem = Some(256.0),
disk = Some(1024.0),
executor = Some("http://dl.corp.org/executors/some.executor"),
constraints = Some(Set()),
uris = Some(Seq("http://dl.corp.org/prodX-1.2.3.tgz")),
ports = Some(Seq(0, 0)),
backoff = Some(2.seconds),
backoffFactor = Some(1.2),
container = Some(
Container(
`type` = mesos.ContainerInfo.Type.DOCKER,
volumes = Nil,
docker = Some(Docker(image = "docker:///group/image"))
)
),
healthChecks = Some(Set[HealthCheck]()),
dependencies = Some(Set[PathId]()),
upgradeStrategy = Some(UpgradeStrategy.empty),
version = Some(Timestamp.now)
)
val json1 = mapper.writeValueAsString(update1)
val readResult1 = mapper.readValue(json1, classOf[AppUpdate])
assert(readResult1 == update1)
val update2 = AppUpdate(container = Some(Container.Empty))
val json2 = """
{
"cmd": null,
"user": null,
"env": null,
"instances": null,
"cpus": null,
"mem": null,
"disk": null,
"executor": null,
"constraints": null,
"uris": null,
"ports": null,
"backoffSeconds": null,
"backoffFactor": null,
"container": null,
"healthChecks": null,
"dependencies": null,
"version": null
}
"""
val readResult2 = mapper.readValue(json2, classOf[AppUpdate])
assert(readResult2 == update2)
val update3 = AppUpdate()
val json3 = "{}"
val readResult3 = mapper.readValue(json3, classOf[AppUpdate])
assert(readResult3 == update3)
val update4 = AppUpdate(args = Some(Seq("a", "b", "c")))
val json4 = """{ "args": ["a", "b", "c"] }"""
val readResult4 = mapper.readValue(json4, classOf[AppUpdate])
assert(readResult4 == update4)
}
}
|
EvanKrall/marathon
|
src/test/scala/mesosphere/marathon/MarathonSchedulerTest.scala
|
package mesosphere.marathon
import akka.actor.ActorSystem
import akka.event.EventStream
import akka.testkit.{ TestKit, TestProbe }
import com.codahale.metrics.MetricRegistry
import com.fasterxml.jackson.databind.ObjectMapper
import com.google.common.collect.Lists
import mesosphere.marathon.Protos.MarathonTask
import mesosphere.marathon.health.HealthCheckManager
import mesosphere.marathon.state.PathId._
import mesosphere.marathon.state.{ AppDefinition, AppRepository, Timestamp }
import mesosphere.marathon.tasks.TaskQueue.QueuedTask
import mesosphere.marathon.tasks.{ TaskIdUtil, TaskQueue, TaskTracker }
import mesosphere.mesos.util.FrameworkIdUtil
import org.apache.mesos.Protos.{ OfferID, TaskID, TaskInfo }
import org.apache.mesos.SchedulerDriver
import org.mockito.ArgumentCaptor
import org.mockito.Matchers.same
import org.mockito.Mockito._
import org.scalatest.BeforeAndAfterAll
import scala.collection.immutable.Seq
import scala.collection.JavaConverters._
import scala.concurrent.duration.Deadline
class MarathonSchedulerTest extends TestKit(ActorSystem("System")) with MarathonSpec with BeforeAndAfterAll {
var repo: AppRepository = _
var hcManager: HealthCheckManager = _
var tracker: TaskTracker = _
var queue: TaskQueue = _
var scheduler: MarathonScheduler = _
var frameworkIdUtil: FrameworkIdUtil = _
var probe: TestProbe = _
var taskIdUtil: TaskIdUtil = _
var config: MarathonConf = _
val metricRegistry = new MetricRegistry
before {
repo = mock[AppRepository]
hcManager = mock[HealthCheckManager]
tracker = mock[TaskTracker]
queue = mock[TaskQueue]
frameworkIdUtil = mock[FrameworkIdUtil]
config = defaultConfig()
taskIdUtil = mock[TaskIdUtil]
probe = TestProbe()
scheduler = new MarathonScheduler(
mock[EventStream],
new ObjectMapper,
probe.ref,
repo,
hcManager,
tracker,
queue,
frameworkIdUtil,
taskIdUtil,
mock[ActorSystem],
config
)
}
override def afterAll(): Unit = {
system.shutdown()
}
test("ResourceOffers") {
val driver = mock[SchedulerDriver]
val offer = makeBasicOffer(cpus = 4, mem = 1024, disk = 4000, beginPort = 31000, endPort = 32000).build
val offers = Lists.newArrayList(offer)
val now = Timestamp.now
val app = AppDefinition(
id = "testOffers".toRootPath,
executor = "//cmd",
ports = Seq(8080),
version = now
)
val queuedTask = QueuedTask(app, Deadline.now)
val list = Vector(queuedTask)
val allApps = Vector(app)
when(taskIdUtil.newTaskId("testOffers".toRootPath))
.thenReturn(TaskID.newBuilder.setValue("testOffers_0-1234").build)
when(tracker.checkStagedTasks).thenReturn(Seq())
when(queue.poll()).thenReturn(Some(queuedTask))
when(queue.list).thenReturn(list)
when(queue.removeAll()).thenReturn(list)
when(queue.listApps).thenReturn(allApps)
scheduler.resourceOffers(driver, offers)
val offersCaptor = ArgumentCaptor.forClass(classOf[java.util.List[OfferID]])
val taskInfosCaptor = ArgumentCaptor.forClass(classOf[java.util.List[TaskInfo]])
val marathonTaskCaptor = ArgumentCaptor.forClass(classOf[MarathonTask])
verify(driver).launchTasks(offersCaptor.capture(), taskInfosCaptor.capture())
verify(tracker).created(same(app.id), marathonTaskCaptor.capture())
assert(1 == offersCaptor.getValue.size())
assert(offer.getId == offersCaptor.getValue.get(0))
assert(1 == taskInfosCaptor.getValue.size())
val taskInfoPortVar = taskInfosCaptor.getValue.get(0).getCommand.getEnvironment
.getVariablesList.asScala.find(v => v.getName == "PORT")
assert(taskInfoPortVar.isDefined)
val marathonTaskPort = marathonTaskCaptor.getValue.getPorts(0)
assert(taskInfoPortVar.get.getValue == marathonTaskPort.toString)
val marathonTaskVersion = marathonTaskCaptor.getValue.getVersion
assert(now.toString() == marathonTaskVersion)
}
}
|
EvanKrall/marathon
|
src/test/scala/mesosphere/marathon/tasks/TaskTrackerTest.scala
|
<reponame>EvanKrall/marathon
package mesosphere.marathon.tasks
import java.io.{ ByteArrayInputStream, ByteArrayOutputStream, ObjectInputStream, ObjectOutputStream }
import com.codahale.metrics.MetricRegistry
import com.google.common.collect.Lists
import mesosphere.marathon.Protos.MarathonTask
import mesosphere.marathon.state.PathId.StringPathId
import mesosphere.marathon.{ MarathonConf, MarathonSpec }
import mesosphere.mesos.protos.Implicits._
import mesosphere.mesos.protos.TextAttribute
import org.apache.mesos.Protos
import org.apache.mesos.Protos.{ TaskID, TaskState, TaskStatus }
import org.apache.mesos.state.{ InMemoryState, State }
import org.mockito.Mockito.{ reset, spy, times, verify }
import org.mockito.Matchers.any
import scala.collection.JavaConverters._
import scala.collection._
import scala.concurrent.Await
import scala.concurrent.duration.Duration
class TaskTrackerTest extends MarathonSpec {
val TEST_APP_NAME = "foo".toRootPath
val TEST_TASK_ID = "sampleTask"
var taskTracker: TaskTracker = null
var state: State = null
val config = mock[MarathonConf]
val taskIdUtil = new TaskIdUtil
before {
val metricRegistry = new MetricRegistry
state = spy(new InMemoryState)
taskTracker = new TaskTracker(state, config)
}
def makeSampleTask(id: String) = {
makeTask(id, "host", 999)
}
def makeTask(id: String, host: String, port: Int) = {
MarathonTask.newBuilder()
.setHost(host)
.addAllPorts(Lists.newArrayList(port))
.setId(id)
.addAttributes(TextAttribute("attr1", "bar"))
.build()
}
def makeTaskStatus(id: String, state: TaskState = TaskState.TASK_RUNNING) = {
TaskStatus.newBuilder
.setTaskId(TaskID.newBuilder
.setValue(id)
)
.setState(state)
.build
}
def shouldContainTask(tasks: Iterable[MarathonTask], task: MarathonTask) {
assert(
tasks.exists(t => t.getId == task.getId
&& t.getHost == task.getHost
&& t.getPortsList == task.getPortsList),
s"Should contain task ${task.getId}"
)
}
def shouldHaveTaskStatus(task: MarathonTask, taskStatus: TaskStatus) {
assert(
task.getStatus == taskStatus, s"Should have task status ${taskStatus.getState.toString}"
)
}
def stateShouldNotContainKey(state: State, key: String) {
assert(!state.names().get().asScala.toSet.contains(key), s"Key ${key} was found in state")
}
def stateShouldContainKey(state: State, key: String) {
assert(state.names().get().asScala.toSet.contains(key), s"Key ${key} was not found in state")
}
test("SerializeAndDeserialize") {
val sampleTask = makeSampleTask(TEST_TASK_ID)
val byteOutputStream = new ByteArrayOutputStream()
val outputStream = new ObjectOutputStream(byteOutputStream)
taskTracker.serialize(sampleTask, outputStream)
val byteInputStream = new ByteArrayInputStream(byteOutputStream.toByteArray)
val inputStream = new ObjectInputStream(byteInputStream)
val deserializedTask = taskTracker.deserialize(taskTracker.getKey(TEST_APP_NAME, TEST_TASK_ID), inputStream)
assert(deserializedTask.get.equals(sampleTask), "Tasks are not properly serialized")
}
test("StoreAndFetchTask") {
val sampleTask = makeSampleTask(TEST_TASK_ID)
taskTracker.store(TEST_APP_NAME, sampleTask)
val fetchedTask = taskTracker.fetchTask(taskTracker.getKey(TEST_APP_NAME, TEST_TASK_ID))
assert(fetchedTask.get.equals(sampleTask), "Tasks are not properly stored")
}
test("FetchApp") {
val taskId1 = taskIdUtil.taskId(TEST_APP_NAME)
val taskId2 = taskIdUtil.taskId(TEST_APP_NAME)
val taskId3 = taskIdUtil.taskId(TEST_APP_NAME)
val task1 = makeSampleTask(taskId1)
val task2 = makeSampleTask(taskId2)
val task3 = makeSampleTask(taskId3)
taskTracker.store(TEST_APP_NAME, task1)
taskTracker.store(TEST_APP_NAME, task2)
taskTracker.store(TEST_APP_NAME, task3)
val testAppTasks = taskTracker.fetchApp(TEST_APP_NAME).tasks
shouldContainTask(testAppTasks.values.toSet, task1)
shouldContainTask(testAppTasks.values.toSet, task2)
shouldContainTask(testAppTasks.values.toSet, task3)
assert(testAppTasks.size == 3)
}
test("TaskLifecycle") {
val sampleTask = makeSampleTask(TEST_TASK_ID)
val sampleTaskKey = taskTracker.getKey(TEST_APP_NAME, TEST_TASK_ID)
// CREATE TASK
taskTracker.created(TEST_APP_NAME, sampleTask)
shouldContainTask(taskTracker.get(TEST_APP_NAME), sampleTask)
stateShouldNotContainKey(state, sampleTaskKey)
// TASK STATUS UPDATE
val startingTaskStatus = makeTaskStatus(TEST_TASK_ID, TaskState.TASK_STARTING)
taskTracker.statusUpdate(TEST_APP_NAME, startingTaskStatus)
shouldContainTask(taskTracker.get(TEST_APP_NAME), sampleTask)
stateShouldContainKey(state, sampleTaskKey)
taskTracker.get(TEST_APP_NAME).foreach(task => shouldHaveTaskStatus(task, startingTaskStatus))
// TASK RUNNING
val runningTaskStatus: TaskStatus = makeTaskStatus(TEST_TASK_ID, TaskState.TASK_RUNNING)
taskTracker.running(TEST_APP_NAME, runningTaskStatus)
shouldContainTask(taskTracker.get(TEST_APP_NAME), sampleTask)
stateShouldContainKey(state, sampleTaskKey)
taskTracker.get(TEST_APP_NAME).foreach(task => shouldHaveTaskStatus(task, runningTaskStatus))
// TASK TERMINATED
val finishedTaskStatus = makeTaskStatus(TEST_TASK_ID, TaskState.TASK_FINISHED)
taskTracker.terminated(TEST_APP_NAME, finishedTaskStatus)
assert(taskTracker.contains(TEST_APP_NAME), "App was not stored")
stateShouldNotContainKey(state, sampleTaskKey)
// APP SHUTDOWN
taskTracker.shutdown(TEST_APP_NAME)
assert(!taskTracker.contains(TEST_APP_NAME), "App was not removed")
// ERRONEOUS MESSAGE
val erroneousStatus = makeTaskStatus(TEST_TASK_ID, TaskState.TASK_LOST)
val updatedTask = taskTracker.statusUpdate(TEST_APP_NAME, erroneousStatus)
val taskOption = Await.result(updatedTask, Duration.Inf)
// Empty option means this message was discarded since there was no matching task
assert(taskOption.isEmpty, "Task was able to be updated and was not removed")
}
test("MultipleApps") {
val appName1 = "app1".toRootPath
val appName2 = "app2".toRootPath
val appName3 = "app3".toRootPath
val taskId1 = taskIdUtil.taskId(appName1)
val taskId2 = taskIdUtil.taskId(appName1)
val taskId3 = taskIdUtil.taskId(appName2)
val taskId4 = taskIdUtil.taskId(appName3)
val taskId5 = taskIdUtil.taskId(appName3)
val taskId6 = taskIdUtil.taskId(appName3)
val task1 = makeSampleTask(taskId1)
val task2 = makeSampleTask(taskId2)
val task3 = makeSampleTask(taskId3)
val task4 = makeSampleTask(taskId4)
val task5 = makeSampleTask(taskId5)
val task6 = makeSampleTask(taskId6)
taskTracker.created(appName1, task1)
taskTracker.running(appName1, makeTaskStatus(taskId1))
taskTracker.created(appName1, task2)
taskTracker.running(appName1, makeTaskStatus(taskId2))
taskTracker.created(appName2, task3)
taskTracker.running(appName2, makeTaskStatus(taskId3))
taskTracker.created(appName3, task4)
taskTracker.running(appName3, makeTaskStatus(taskId4))
taskTracker.created(appName3, task5)
taskTracker.running(appName3, makeTaskStatus(taskId5))
taskTracker.created(appName3, task6)
taskTracker.running(appName3, makeTaskStatus(taskId6))
assert(state.names.get.asScala.toSet.size == 6, "Incorrect number of tasks in state")
val app1Tasks = taskTracker.fetchApp(appName1).tasks
shouldContainTask(app1Tasks.values.toSet, task1)
shouldContainTask(app1Tasks.values.toSet, task2)
assert(app1Tasks.size == 2, "Incorrect number of tasks")
val app2Tasks = taskTracker.fetchApp(appName2).tasks
shouldContainTask(app2Tasks.values.toSet, task3)
assert(app2Tasks.size == 1, "Incorrect number of tasks")
val app3Tasks = taskTracker.fetchApp(appName3).tasks
shouldContainTask(app3Tasks.values.toSet, task4)
shouldContainTask(app3Tasks.values.toSet, task5)
shouldContainTask(app3Tasks.values.toSet, task6)
assert(app3Tasks.size == 3, "Incorrect number of tasks")
}
test("ExpungeOrphanedTasks") {
val ORPHANED_APP_NAME = "orphanedApp".toRootPath
val orphanedTaskId1 = taskIdUtil.taskId(ORPHANED_APP_NAME)
val orphanedTaskId2 = taskIdUtil.taskId(ORPHANED_APP_NAME)
val orphanedTaskId3 = taskIdUtil.taskId(ORPHANED_APP_NAME)
val orphanedTask1 = makeSampleTask(orphanedTaskId1)
val orphanedTask2 = makeSampleTask(orphanedTaskId2)
val orphanedTask3 = makeSampleTask(orphanedTaskId3)
taskTracker.store(ORPHANED_APP_NAME, orphanedTask1)
taskTracker.store(ORPHANED_APP_NAME, orphanedTask2)
taskTracker.store(ORPHANED_APP_NAME, orphanedTask3)
val taskId1 = taskIdUtil.taskId(TEST_APP_NAME)
val taskId2 = taskIdUtil.taskId(TEST_APP_NAME)
val taskId3 = taskIdUtil.taskId(TEST_APP_NAME)
val task1 = makeSampleTask(taskId1)
val task2 = makeSampleTask(taskId2)
val task3 = makeSampleTask(taskId3)
taskTracker.created(TEST_APP_NAME, task1)
taskTracker.running(TEST_APP_NAME, makeTaskStatus(taskId1))
taskTracker.created(TEST_APP_NAME, task2)
taskTracker.running(TEST_APP_NAME, makeTaskStatus(taskId2))
taskTracker.created(TEST_APP_NAME, task3)
taskTracker.running(TEST_APP_NAME, makeTaskStatus(taskId3))
taskTracker.expungeOrphanedTasks()
val names = state.names.get.asScala.toSet
assert(names.size == 3, "Orphaned tasks were not correctly expunged")
assert(!taskTracker.contains(ORPHANED_APP_NAME), "Orphaned app should not exist in TaskTracker")
val tasks = taskTracker.get(TEST_APP_NAME)
shouldContainTask(tasks, task1)
shouldContainTask(tasks, task2)
shouldContainTask(tasks, task3)
}
test("Should not store if state did not change (no health present)") {
val sampleTask = makeSampleTask(TEST_TASK_ID)
val status = Protos.TaskStatus
.newBuilder
.setState(Protos.TaskState.TASK_RUNNING)
.setTaskId(Protos.TaskID.newBuilder.setValue(sampleTask.getId))
.build()
taskTracker.store(TEST_APP_NAME, sampleTask)
taskTracker.running(TEST_APP_NAME, status)
taskTracker.statusUpdate(TEST_APP_NAME, status)
reset(state)
taskTracker.statusUpdate(TEST_APP_NAME, status)
verify(state, times(0)).store(any())
}
test("Should not store if state and health did not change") {
val sampleTask = makeSampleTask(TEST_TASK_ID)
val status = Protos.TaskStatus
.newBuilder
.setState(Protos.TaskState.TASK_RUNNING)
.setTaskId(Protos.TaskID.newBuilder.setValue(sampleTask.getId))
.setHealthy(true)
.build()
taskTracker.store(TEST_APP_NAME, sampleTask)
taskTracker.running(TEST_APP_NAME, status)
taskTracker.statusUpdate(TEST_APP_NAME, status)
reset(state)
taskTracker.statusUpdate(TEST_APP_NAME, status)
verify(state, times(0)).store(any())
}
test("Should store if state changed") {
val sampleTask = makeSampleTask(TEST_TASK_ID)
val status = Protos.TaskStatus
.newBuilder
.setState(Protos.TaskState.TASK_RUNNING)
.setTaskId(Protos.TaskID.newBuilder.setValue(sampleTask.getId))
.build()
taskTracker.store(TEST_APP_NAME, sampleTask)
taskTracker.running(TEST_APP_NAME, status)
taskTracker.statusUpdate(TEST_APP_NAME, status)
reset(state)
val newStatus = status.toBuilder
.setState(Protos.TaskState.TASK_FAILED)
.build()
taskTracker.statusUpdate(TEST_APP_NAME, newStatus)
verify(state, times(1)).store(any())
}
test("Should store if health changed") {
val sampleTask = makeSampleTask(TEST_TASK_ID)
val status = Protos.TaskStatus
.newBuilder
.setState(Protos.TaskState.TASK_RUNNING)
.setTaskId(Protos.TaskID.newBuilder.setValue(sampleTask.getId))
.setHealthy(true)
.build()
taskTracker.store(TEST_APP_NAME, sampleTask)
taskTracker.running(TEST_APP_NAME, status)
taskTracker.statusUpdate(TEST_APP_NAME, status)
reset(state)
val newStatus = status.toBuilder
.setHealthy(false)
.build()
taskTracker.statusUpdate(TEST_APP_NAME, newStatus)
verify(state, times(1)).store(any())
}
test("Should store if state and health changed") {
val sampleTask = makeSampleTask(TEST_TASK_ID)
val status = Protos.TaskStatus
.newBuilder
.setState(Protos.TaskState.TASK_RUNNING)
.setTaskId(Protos.TaskID.newBuilder.setValue(sampleTask.getId))
.setHealthy(true)
.build()
taskTracker.store(TEST_APP_NAME, sampleTask)
taskTracker.running(TEST_APP_NAME, status)
taskTracker.statusUpdate(TEST_APP_NAME, status)
reset(state)
val newStatus = status.toBuilder
.setState(Protos.TaskState.TASK_FAILED)
.setHealthy(false)
.build()
taskTracker.statusUpdate(TEST_APP_NAME, newStatus)
verify(state, times(1)).store(any())
}
test("Should store if health changed (no health present at first)") {
val sampleTask = makeSampleTask(TEST_TASK_ID)
val status = Protos.TaskStatus
.newBuilder
.setState(Protos.TaskState.TASK_RUNNING)
.setTaskId(Protos.TaskID.newBuilder.setValue(sampleTask.getId))
.build()
taskTracker.store(TEST_APP_NAME, sampleTask)
taskTracker.running(TEST_APP_NAME, status)
taskTracker.statusUpdate(TEST_APP_NAME, status)
reset(state)
val newStatus = status.toBuilder
.setHealthy(true)
.build()
taskTracker.statusUpdate(TEST_APP_NAME, newStatus)
verify(state, times(1)).store(any())
}
test("Should store if state and health changed (no health present at first)") {
val sampleTask = makeSampleTask(TEST_TASK_ID)
val status = Protos.TaskStatus
.newBuilder
.setState(Protos.TaskState.TASK_RUNNING)
.setTaskId(Protos.TaskID.newBuilder.setValue(sampleTask.getId))
.build()
taskTracker.store(TEST_APP_NAME, sampleTask)
taskTracker.running(TEST_APP_NAME, status)
taskTracker.statusUpdate(TEST_APP_NAME, status)
reset(state)
val newStatus = status.toBuilder
.setState(Protos.TaskState.TASK_FAILED)
.setHealthy(false)
.build()
taskTracker.statusUpdate(TEST_APP_NAME, newStatus)
verify(state, times(1)).store(any())
}
}
|
EvanKrall/marathon
|
src/test/scala/mesosphere/marathon/health/HealthCheckTest.scala
|
<reponame>EvanKrall/marathon
package mesosphere.marathon.health
import mesosphere.marathon.{ MarathonSpec, Protos }
import mesosphere.marathon.state.Command
import mesosphere.jackson.CaseClassModule
import Protos.HealthCheckDefinition.Protocol
import scala.concurrent.duration.FiniteDuration
import scala.collection.JavaConverters._
import java.util.concurrent.TimeUnit.SECONDS
import javax.validation.Validation
class HealthCheckTest extends MarathonSpec {
test("ToProto") {
val healthCheck = HealthCheck(
path = Some("/health"),
protocol = Protocol.HTTP,
portIndex = 0,
gracePeriod = FiniteDuration(10, SECONDS),
interval = FiniteDuration(60, SECONDS),
maxConsecutiveFailures = 0
)
val proto = healthCheck.toProto
assert("/health" == proto.getPath)
assert(Protocol.HTTP == proto.getProtocol)
assert(0 == proto.getPortIndex)
assert(10 == proto.getGracePeriodSeconds)
assert(60 == proto.getIntervalSeconds)
assert(0 == proto.getMaxConsecutiveFailures)
}
test("ToProtoTcp") {
val healthCheck = HealthCheck(
protocol = Protocol.TCP,
portIndex = 1,
gracePeriod = FiniteDuration(7, SECONDS),
interval = FiniteDuration(35, SECONDS),
maxConsecutiveFailures = 10
)
val proto = healthCheck.toProto
assert(Protocol.TCP == proto.getProtocol)
assert(1 == proto.getPortIndex)
assert(7 == proto.getGracePeriodSeconds)
assert(35 == proto.getIntervalSeconds)
assert(10 == proto.getMaxConsecutiveFailures)
}
test("MergeFromProto") {
val proto = Protos.HealthCheckDefinition.newBuilder
.setPath("/health")
.setProtocol(Protocol.HTTP)
.setPortIndex(0)
.setGracePeriodSeconds(10)
.setIntervalSeconds(60)
.setTimeoutSeconds(10)
.setMaxConsecutiveFailures(10)
.build
val mergeResult = HealthCheck().mergeFromProto(proto)
val expectedResult = HealthCheck(
path = Some("/health"),
protocol = Protocol.HTTP,
portIndex = 0,
gracePeriod = FiniteDuration(10, SECONDS),
interval = FiniteDuration(60, SECONDS),
timeout = FiniteDuration(10, SECONDS),
maxConsecutiveFailures = 10
)
assert(mergeResult == expectedResult)
}
test("MergeFromProtoTcp") {
val proto = Protos.HealthCheckDefinition.newBuilder
.setProtocol(Protocol.TCP)
.setPortIndex(1)
.setGracePeriodSeconds(7)
.setIntervalSeconds(35)
.setTimeoutSeconds(10)
.setMaxConsecutiveFailures(10)
.build
val mergeResult = HealthCheck().mergeFromProto(proto)
val expectedResult = HealthCheck(
path = None,
protocol = Protocol.TCP,
portIndex = 1,
gracePeriod = FiniteDuration(7, SECONDS),
interval = FiniteDuration(35, SECONDS),
timeout = FiniteDuration(10, SECONDS),
maxConsecutiveFailures = 10
)
assert(mergeResult == expectedResult)
}
test("SerializationRoundtrip") {
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import mesosphere.marathon.api.v2.json.MarathonModule
val mapper = new ObjectMapper
mapper.registerModule(DefaultScalaModule)
mapper.registerModule(new MarathonModule)
mapper.registerModule(CaseClassModule)
{
val original = HealthCheck()
val json = mapper.writeValueAsString(original)
val readResult = mapper.readValue(json, classOf[HealthCheck])
assert(readResult == original)
}
{
val json =
"""
{
"protocol": "COMMAND",
"portIndex": 0,
"command": { "value": "echo healthy" },
"gracePeriodSeconds": 15,
"intervalSeconds": 10,
"timeoutSeconds": 20,
"maxConsecutiveFailures": 3
}
"""
val expected =
HealthCheck(
protocol = Protocol.COMMAND,
command = Some(Command("echo healthy"))
)
val readResult = mapper.readValue(json, classOf[HealthCheck])
assert(readResult == expected)
}
{
val json =
"""
{
"protocol": "COMMAND",
"portIndex": 0,
"command": { "value": "echo healthy" },
"gracePeriodSeconds": 15,
"intervalSeconds": 10,
"timeoutSeconds": 20,
"maxConsecutiveFailures": 3
}
"""
val expected =
HealthCheck(
protocol = Protocol.COMMAND,
command = Some(Command("echo healthy")),
path = Some("/")
)
val readResult = mapper.readValue(json, classOf[HealthCheck])
assert(readResult == expected)
}
}
test("Validation") {
val validator = Validation.buildDefaultValidatorFactory().getValidator
def shouldViolate(hc: HealthCheck, template: String) = {
val violations = validator.validate(hc).asScala
assert(violations.exists(_.getMessageTemplate == template))
}
def shouldNotViolate(hc: HealthCheck, template: String) = {
val violations = validator.validate(hc).asScala
assert(!violations.exists(_.getMessageTemplate == template))
}
shouldNotViolate(HealthCheck(), "")
shouldViolate(
HealthCheck(protocol = Protocol.COMMAND, path = Some("/health")),
"Health check protocol must match supplied fields."
)
shouldViolate(
HealthCheck(protocol = Protocol.COMMAND, command = None),
"Health check protocol must match supplied fields."
)
shouldViolate(
HealthCheck(
protocol = Protocol.HTTP,
command = Some(Command("echo healthy"))
),
"Health check protocol must match supplied fields."
)
shouldViolate(
HealthCheck(
protocol = Protocol.TCP,
path = Some("/")
),
"Health check protocol must match supplied fields."
)
shouldViolate(
HealthCheck(
protocol = Protocol.TCP,
command = Some(Command("echo healthy"))
),
"Health check protocol must match supplied fields."
)
}
}
|
EvanKrall/marathon
|
src/main/scala/mesosphere/marathon/api/v2/InfoResource.scala
|
package mesosphere.marathon.api.v2
import javax.ws.rs.core.{ MediaType, Response }
import javax.ws.rs.{ Consumes, GET, Path, Produces }
import com.google.inject.Inject
import mesosphere.chaos.http.HttpConf
import mesosphere.marathon.event.EventConfiguration
import mesosphere.marathon.event.http.HttpEventConfiguration
import mesosphere.marathon.{ MarathonSchedulerService, BuildInfo, MarathonConf }
@Path("v2/info")
@Consumes(Array(MediaType.APPLICATION_JSON))
class InfoResource @Inject() (schedulerService: MarathonSchedulerService, conf: MarathonConf with HttpConf with EventConfiguration with HttpEventConfiguration) {
// Marathon configurations
private[this] lazy val marathonConfigValues = Map(
"master" -> conf.mesosMaster.get,
"failover_timeout" -> conf.mesosFailoverTimeout.get,
"ha" -> conf.highlyAvailable.get,
"checkpoint" -> conf.checkpoint.get,
"local_port_min" -> conf.localPortMin.get,
"local_port_max" -> conf.localPortMax.get,
"executor" -> conf.defaultExecutor.get,
"hostname" -> conf.hostname.get,
"mesos_role" -> conf.mesosRole.get,
"task_launch_timeout" -> conf.taskLaunchTimeout.get,
"reconciliation_initial_delay" -> conf.reconciliationInitialDelay.get,
"reconciliation_interval" -> conf.reconciliationInterval.get,
"mesos_user" -> conf.mesosUser.get)
// Zookeeper congiurations
private[this] lazy val zookeeperConfigValues = Map(
"zk_timeout" -> conf.zooKeeperTimeout.get,
"zk" -> conf.zooKeeperUrl.get,
"zk_hosts" -> conf.zkHosts,
"zk_path" -> conf.zkPath,
"zk_timeout" -> conf.zkTimeoutDuration,
"zk_future_timeout" -> conf.zkFutureTimeout)
private[this] lazy val eventHandlerConfigValues = {
def httpEventConfig = Map(
"http_endpoints" -> conf.httpEventEndpoints.get
)
def eventConfig = conf.eventSubscriber.get match {
case Some("http_callback") => httpEventConfig
case _ => Map()
}
Map(
"type" -> conf.eventSubscriber.get
) ++ eventConfig
}
private[this] lazy val httpConfigValues = Map(
"assets_path" -> conf.assetsFileSystemPath.get,
"http_port" -> conf.httpPort.get,
"https_port" -> conf.httpsPort.get
)
@GET
@Produces(Array(MediaType.APPLICATION_JSON))
def index(): Response = {
Response.ok(
Map(
"name" -> BuildInfo.name,
"version" -> BuildInfo.version,
"leader" -> schedulerService.getLeader,
"frameworkId" -> schedulerService.frameworkId.map(_.getValue),
"marathon_config" -> marathonConfigValues,
"zookeeper_config" -> zookeeperConfigValues,
"event_subscriber" -> conf.eventSubscriber.get.map(_ => eventHandlerConfigValues),
"http_config" -> httpConfigValues)).build()
}
}
|
parwen68/advent-of-code-2017
|
shared/src/test/scala/se/parwen/adoc/day18/SolverSpec.scala
|
package se.parwen.adoc.day18
import org.scalatest._
import se.parwen.adoc.day18.Solver._
class SolverSpec extends FlatSpec with Matchers {
"Solver parse" should "return" in {
val a = Solver.parse("""set a 1
|add a 2
|mul a a
|mod a 5
|snd a
|set a 0
|rcv a
|jgz a -1
|set a 1
|jgz a -2""".stripMargin)
a should be (Vector(Seti('a',1), Addi('a',2), Mulc('a','a'), Modi('a',5), Sndc('a'), Seti('a',0), Rcv('a'), Jgzi('a',-1), Seti('a',1), Jgzi('a',-2)))
}
"Solver solveStep1" should "return 4" in {
val a = Solver.solveStep1("""set a 1
|add a 2
|mul a a
|mod a 5
|snd a
|set a 0
|rcv a
|jgz a -1
|set a 1
|jgz a -2""".stripMargin)
a should be (4)
}
"" should "" in {
val a = Solver.solveStep2("""snd 1
|snd 2
|snd p
|rcv a
|rcv b
|rcv c
|rcv d""".stripMargin)
a should be (3)
}
}
|
parwen68/advent-of-code-2017
|
shared/src/main/scala/se/parwen/adoc/day18/Solver.scala
|
<reponame>parwen68/advent-of-code-2017
package se.parwen.adoc.day18
import scala.annotation.tailrec
import scala.util.matching.Regex
object Solver {
case class ExecCtx(
ptr: Long,
regs: Map[Char, Long],
lastPlayedSnd: Long,
inQ: List[Long] = List(),
outQ: List[Long] = List(),
sends: Int = 0,
stopped: Boolean = false
)
sealed trait Instruction {
def exec(ctx: ExecCtx) : ExecCtx
}
case class Sndi(v: Long) extends Instruction {
override def exec(ctx: ExecCtx): ExecCtx =
ctx.copy(
ptr = ctx.ptr + 1,
lastPlayedSnd = v,
outQ = ctx.outQ :+ v,
sends = ctx.sends + 1)
}
case class Sndc(r: Char) extends Instruction {
override def exec(ctx: ExecCtx): ExecCtx =
ctx.copy(
ptr = ctx.ptr + 1,
lastPlayedSnd = ctx.regs(r),
outQ = ctx.outQ :+ ctx.regs(r),
sends = ctx.sends + 1)
}
case class Rcv(r: Char) extends Instruction {
override def exec(ctx: ExecCtx): ExecCtx = {
ctx.inQ match {
case head :: tail => ctx.copy(
ptr = ctx.ptr + 1,
regs = ctx.regs.updated(r, head),
inQ = tail)
case Nil => ctx.copy(stopped = true)
}
}
}
case class Seti(r: Char, v: Long) extends Instruction {
override def exec(ctx: ExecCtx): ExecCtx =
ctx.copy(ptr = ctx.ptr + 1, regs = ctx.regs.updated(r, v))
}
case class Setc(r1: Char, r2: Char) extends Instruction {
override def exec(ctx: ExecCtx): ExecCtx =
ctx.copy(ptr = ctx.ptr + 1, regs = ctx.regs.updated(r1, ctx.regs(r2)))
}
case class Addi(r: Char, v: Long) extends Instruction {
override def exec(ctx: ExecCtx):
ExecCtx = ctx.copy(ptr = ctx.ptr + 1, regs = ctx.regs.updated(r, ctx.regs(r) + v))
}
case class Addc(r1: Char, r2: Char) extends Instruction {
override def exec(ctx: ExecCtx): ExecCtx = ctx.copy(ptr = ctx.ptr + 1, regs = ctx.regs.updated(r1, ctx.regs(r1) + ctx.regs(r2)))
}
case class Muli(r: Char, v: Long) extends Instruction {
override def exec(ctx: ExecCtx): ExecCtx = ctx.copy(ptr = ctx.ptr + 1, regs = ctx.regs.updated(r, ctx.regs(r) * v))
}
case class Mulc(r1: Char, r2: Char) extends Instruction {
override def exec(ctx: ExecCtx): ExecCtx = ctx.copy(ptr = ctx.ptr + 1, regs = ctx.regs.updated(r1, ctx.regs(r1) * ctx.regs(r2)))
}
case class Modi(r: Char, v: Long) extends Instruction {
override def exec(ctx: ExecCtx): ExecCtx = ctx.copy(ptr = ctx.ptr + 1, regs = ctx.regs.updated(r, ctx.regs(r) % v))
}
case class Modc(r1: Char, r2: Char) extends Instruction {
override def exec(ctx: ExecCtx): ExecCtx = ctx.copy(ptr = ctx.ptr + 1, regs = ctx.regs.updated(r1, ctx.regs(r1) % ctx.regs(r2)))
}
case class Jgz(v1: Long, v2: Long) extends Instruction {
override def exec(ctx: ExecCtx): ExecCtx = if(v1 > 0) ctx.copy(ptr = ctx.ptr + v2) else ctx.copy(ptr = ctx.ptr + 1)
}
case class Jgzi(r: Char, v: Long) extends Instruction {
override def exec(ctx: ExecCtx): ExecCtx = if(ctx.regs(r) > 0) ctx.copy(ptr = ctx.ptr + v) else ctx.copy(ptr = ctx.ptr + 1)
}
case class Jgzc(r1: Char, r2: Char) extends Instruction {
override def exec(ctx: ExecCtx): ExecCtx = if(ctx.regs(r1) > 0) ctx.copy(ptr = ctx.ptr + ctx.regs(r2)) else ctx.copy(ptr = ctx.ptr + 1)
}
val sndi: Regex = "snd ([-\\d]+)".r
val sndc: Regex = "snd (\\w)".r
val rcv: Regex = "rcv (\\w)".r
val seti: Regex = "set (\\w) ([-\\d]+)".r
val setc: Regex = "set (\\w) (\\w)".r
val addi: Regex = "add (\\w) ([-\\d]+)".r
val addc: Regex = "add (\\w) (\\w)".r
val muli: Regex = "mul (\\w) ([-\\d]+)".r
val mulc: Regex = "mul (\\w) (\\w)".r
val modi: Regex = "mod (\\w) ([-\\d]+)".r
val modc: Regex = "mod (\\w) (\\w)".r
val jgz: Regex = "jgz ([-\\d]+) ([-\\d]+)".r
val jgzi: Regex = "jgz (\\w) ([-\\d]+)".r
val jgzc: Regex = "jgz (\\w) (\\w)".r
def parse(input: String) : Vector[Instruction] = {
input.split('\n').map {
case sndi(v) => Sndi(v.toInt)
case sndc(r) => Sndc(r(0))
case seti(r, v) => Seti(r(0), v.toInt)
case setc(r1, r2) => Setc(r1(0), r2(0))
case addi(r, v) => Addi(r(0), v.toInt)
case addc(r1, r2) => Addc(r1(0), r2(0))
case muli(r, v) => Muli(r(0), v.toInt)
case mulc(r1, r2) => Mulc(r1(0), r2(0))
case modi(r, v) => Modi(r(0), v.toInt)
case modc(r1, r2) => Modc(r1(0), r2(0))
case rcv(r) => Rcv(r(0))
case jgz(v1, v2) => Jgz(v1.toInt, v2.toInt)
case jgzi(r, v) => Jgzi(r(0), v.toInt)
case jgzc(r1, r2) => Jgzc(r1(0), r2(0))
case e => throw new RuntimeException(e)
}.toVector
}
def solveStep1(input: String): Long = {
val prgm = parse(input)
@tailrec
def loop(ctx: ExecCtx): Long = {
prgm(ctx.ptr.toInt) match {
case Rcv(r) if ctx.regs(r) != 0 => ctx.lastPlayedSnd
case Rcv(r) if ctx.regs(r) == 0 => loop(prgm(ctx.ptr.toInt + 1).exec(ctx))
case _ => loop(prgm(ctx.ptr.toInt).exec(ctx))
}
}
loop(ExecCtx(0,('a' to 'z').map((_,0L)).toMap, 0))
}
def solveStep2(input: String): Long = {
val prgm = parse(input)
def stopped(ctx: ExecCtx) = ctx.stopped || ctx.ptr < 0 || ctx.ptr >= prgm.length
@tailrec
def loop(ctx0: ExecCtx, ctx1: ExecCtx): Int = {
if (stopped(ctx0) && stopped(ctx1)) ctx1.sends
else
loop(
prgm(ctx0.ptr.toInt).exec(ctx0.copy(inQ = ctx0.inQ ++ ctx1.outQ, outQ = List())),
prgm(ctx1.ptr.toInt).exec(ctx1.copy(inQ = ctx1.inQ ++ ctx0.outQ, outQ = List()))
)
}
val ctx0 = ExecCtx(0, ('a' to 'z').map((_,0L)).toMap.updated('p', 0L), 0)
val ctx1 = ExecCtx(0, ('a' to 'z').map((_,0L)).toMap.updated('p', 1L), 0)
loop(ctx0, ctx1)
}
}
trait Solver18 {
def solve18(): Unit = {
println("Day 18:")
val result1 = Solver.solveStep1(Input.input)
println(s"step 1 result is $result1")
val result2 = Solver.solveStep2(Input.input)
println(s"step 2 result is $result2")
}
}
object Main extends Solver18 {
def main(args: Array[String]): Unit = {
solve18()
}
}
|
parwen68/advent-of-code-2017
|
shared/src/main/scala/se/parwen/adoc/day20/Solver.scala
|
<filename>shared/src/main/scala/se/parwen/adoc/day20/Solver.scala
package se.parwen.adoc.day20
object Solver {
case class Coord(x: Int, y: Int, z: Int) {
def dist: Int = Math.abs(x) + Math.abs(y) + Math.abs(z)
}
object Coord {
def apply(x: String, y: String, z: String) : Coord = {
Coord(x.trim.toInt, y.trim.toInt, z.trim.toInt)
}
}
case class Pixel(idx: Int, p: Coord, v: Coord, a: Coord) {
def tick(): Pixel = {
val s = this.copy(v = Coord(v.x + a.x, v.y + a.y, v.z + a.z))
s.copy(p = Coord(p.x + s.v.x, p.y + s.v.y, p.z + s.v.z))
}
}
def parse(input: String): Vector[Pixel] = {
val pp = "<([\\s-\\d]+),([\\s-\\d]+),([\\s-\\d]+)>"
val pattern = s"p=$pp, v=$pp, a=$pp".r
val lines = input.split('\n')
lines.zipWithIndex.map{
case (pattern(px,py,pz,vx,vy,vz,ax,ay,az),idx)=>
Pixel(idx, Coord(px,py,pz), Coord(vx,vy,vz), Coord(ax, ay, az))
}.toVector
}
def solveStep1(input: String): Int = {
val pixles = parse(input)
val minAcc = pixles.map(p => p.a.dist).min
val minAccPixels = pixles.filter(p => p.a.dist == minAcc)
if (minAccPixels.length == 1) {
minAccPixels(0).idx
} else {
def loop(p: Vector[Pixel], dists: Vector[Int] = Vector()) : Int = {
if (dists.nonEmpty && p.zip(dists).map { case (p, d) => p.p.dist - d }.forall(_ > 0)) {
p.foldLeft(p(0))((p1, p2) => if (p1.p.dist < p2.p.dist) p1 else p2).idx
} else {
loop(p.map(p => p.tick()), p.map(p => p.p.dist))
}
}
loop(minAccPixels)
}
}
def solveStep2(input: String): Int = {
val pixels = parse(input)
def distance(p1: Pixel, p2: Pixel): Int = {
Math.abs(p1.p.x - p2.p.x) + Math.abs(p1.p.y - p2.p.y) + Math.abs(p1.p.z - p2.p.z)
}
def distances(p: Vector[Pixel]) = {
for {
p1 <- p
p2 <- p if p2 != p1
} yield distance(p1, p2)
}
def loop(p: Vector[Pixel], left: Int, times: Int = 0, dists: Vector[Int] = Vector()) : Int = {
if (dists.nonEmpty && distances(p).zip(dists).map{ case (d1, d2) => d1 - d2}.forall(_ > 0))
left
else {
val collisions = p.map(_.p).groupBy(e => e).filter(e => e._2.length > 1)
loop(
p.filterNot(v => collisions.keys.toVector.contains(v.p)).map(_.tick()),
p.length,
if (p.length == left) times + 1 else 0,
if (times > 1000) distances(p) else Vector()
)
}
}
loop(pixels, pixels.length)
}
}
trait Solver20 {
def solve20(): Unit = {
println("Day 20:")
val result1 = Solver.solveStep1(Input.input)
println(s"step 1 result is $result1")
val result2 = Solver.solveStep2(Input.input)
println(s"step 2 result is $result2")
}
}
object Main extends Solver20 {
def main(args: Array[String]): Unit = {
solve20()
}
}
|
parwen68/advent-of-code-2017
|
shared/src/test/scala/se/parwen/adoc/day6/SolverSpec.scala
|
<filename>shared/src/test/scala/se/parwen/adoc/day6/SolverSpec.scala
package se.parwen.adoc.day6
import org.scalatest._
class SolverSpec extends FlatSpec with Matchers {
import Solver._
"The Solver" should "return 5" in {
solveStep1(List(0, 2, 7, 0)) should be (5)
}
"The Solver" should "return 4" in {
solveStep2(List(0, 2, 7, 0)) should be (4)
}
"The stream blocks 10 and 4 banks" should "distribute like" in {
stream(10,4).toList should be (List(3,3,2,2))
}
"The stream blocks 2 and 4 banks" should "distribute like" in {
stream(2,4).toList should be (List(1,1,0,0))
}
}
|
parwen68/advent-of-code-2017
|
shared/src/test/scala/se/parwen/adoc/day20/SolverSpec.scala
|
package se.parwen.adoc.day20
import org.scalatest._
import se.parwen.adoc.day20.Solver.{Coord, Pixel}
class SolverSpec extends FlatSpec with Matchers {
"The Solver parser" should "return parsed result" in {
val a = Solver.parse("""p=< 3,0,0>, v=< 2,0,0>, a=<-1,0,0>
|p=< 4,0,0>, v=< 0,0,0>, a=<-2,0,0>""".stripMargin)
println(a)
}
"Pixels" should "move after tick" in {
val a = Solver.parse("""p=< 3,0,0>, v=< 2,0,0>, a=<-1,0,0>
|p=< 4,0,0>, v=< 0,0,0>, a=<-2,0,0>""".stripMargin)
val r = a.map(_.tick())
r should be (Vector(Pixel(0, Coord(4,0,0),Coord(1,0,0),Coord(-1,0,0)), Pixel(1, Coord(2,0,0),Coord(-2,0,0),Coord(-2,0,0))))
}
}
|
parwen68/advent-of-code-2017
|
shared/src/main/scala/se/parwen/adoc/day12/Input.scala
|
<reponame>parwen68/advent-of-code-2017
package se.parwen.adoc.day12
object Input {
val input2 = """0 <-> 795
|1 <-> 156
|2 <-> 715
|3 <-> 1361, 1698
|4 <-> 551, 672
|5 <-> 514
|6 <-> 1806
|7 <-> 1700
|8 <-> 599, 1068, 1850
|9 <-> 580, 1517
|10 <-> 521
|11 <-> 461
|12 <-> 896
|13 <-> 464
|14 <-> 526
|15 <-> 15
|16 <-> 627, 997
|17 <-> 725
|18 <-> 1803
|19 <-> 129, 1608, 1712
|20 <-> 1005
|21 <-> 252, 386, 1818
|22 <-> 32, 1168, 1266, 1757
|23 <-> 212, 664
|24 <-> 983
|25 <-> 1271, 1356
|26 <-> 545
|27 <-> 639
|28 <-> 509
|29 <-> 686, 959, 1521
|30 <-> 172
|31 <-> 1721
|32 <-> 22
|33 <-> 436
|34 <-> 96, 116, 661, 1102
|35 <-> 827, 1274, 1533
|36 <-> 483, 586
|37 <-> 556
|38 <-> 709
|39 <-> 551, 1196
|40 <-> 42
|41 <-> 485
|42 <-> 40, 475, 930
|43 <-> 121
|44 <-> 202, 759
|45 <-> 45, 721, 764
|46 <-> 903
|47 <-> 616, 1053
|48 <-> 1933
|49 <-> 334, 476, 516, 1212
|50 <-> 717, 1412
|51 <-> 331
|52 <-> 1953
|53 <-> 53, 853
|54 <-> 430
|55 <-> 1635
|56 <-> 826, 1985
|57 <-> 1375
|58 <-> 868, 1887
|59 <-> 908, 1307
|60 <-> 582
|61 <-> 1298
|62 <-> 1373
|63 <-> 1200, 1644
|64 <-> 547, 771, 1443
|65 <-> 235, 340, 522, 1472, 1597
|66 <-> 1605
|67 <-> 75
|68 <-> 365
|69 <-> 69
|70 <-> 1781
|71 <-> 1519
|72 <-> 1355
|73 <-> 73, 176
|74 <-> 1155
|75 <-> 67, 769, 1080
|76 <-> 470, 474, 1115
|77 <-> 1564
|78 <-> 78, 1128, 1351
|79 <-> 784
|80 <-> 80, 962, 1566
|81 <-> 1784
|82 <-> 1977
|83 <-> 892
|84 <-> 705, 892, 958, 1717
|85 <-> 493, 644, 714, 1624
|86 <-> 1079, 1547
|87 <-> 1186, 1240
|88 <-> 215, 250, 1918
|89 <-> 485
|90 <-> 595, 786, 1419, 1825, 1870
|91 <-> 1366, 1874
|92 <-> 217, 225
|93 <-> 577, 1734
|94 <-> 94
|95 <-> 1476
|96 <-> 34, 560, 1061
|97 <-> 199
|98 <-> 1311
|99 <-> 1040
|100 <-> 1397
|101 <-> 1578
|102 <-> 1719
|103 <-> 1268, 1663
|104 <-> 106, 677, 846
|105 <-> 650
|106 <-> 104, 1315
|107 <-> 1802
|108 <-> 1723, 1885
|109 <-> 658
|110 <-> 646
|111 <-> 124, 710, 1819
|112 <-> 841
|113 <-> 696
|114 <-> 1685, 1923
|115 <-> 1565
|116 <-> 34, 1116
|117 <-> 1532, 1842
|118 <-> 1058, 1225, 1495
|119 <-> 224, 1536
|120 <-> 542, 1229
|121 <-> 43, 986
|122 <-> 921
|123 <-> 345, 1655, 1848, 1974
|124 <-> 111, 1259
|125 <-> 1797
|126 <-> 126
|127 <-> 127, 260, 732, 1117, 1251
|128 <-> 1151
|129 <-> 19, 782
|130 <-> 130
|131 <-> 1582
|132 <-> 505, 592, 1545
|133 <-> 953
|134 <-> 1567
|135 <-> 559, 591, 1791
|136 <-> 868, 1449, 1470, 1954
|137 <-> 374
|138 <-> 303, 1601, 1710
|139 <-> 1011
|140 <-> 140, 1947
|141 <-> 252
|142 <-> 803, 1706
|143 <-> 1622
|144 <-> 832
|145 <-> 145
|146 <-> 904, 921, 1720
|147 <-> 611, 1788
|148 <-> 188
|149 <-> 264
|150 <-> 746, 1850
|151 <-> 151, 347
|152 <-> 393
|153 <-> 182
|154 <-> 154, 349, 673, 1039
|155 <-> 697, 1258
|156 <-> 1, 384, 453, 1232, 1995
|157 <-> 1492
|158 <-> 1245
|159 <-> 1194
|160 <-> 222, 1241
|161 <-> 1377
|162 <-> 162
|163 <-> 1825
|164 <-> 1837
|165 <-> 955, 1811
|166 <-> 825, 1817
|167 <-> 1338
|168 <-> 1037, 1290
|169 <-> 169
|170 <-> 1490
|171 <-> 553
|172 <-> 30, 308
|173 <-> 1573, 1604
|174 <-> 1297
|175 <-> 265, 1070, 1960
|176 <-> 73, 497
|177 <-> 1639, 1697
|178 <-> 494, 1490
|179 <-> 623
|180 <-> 185, 1056
|181 <-> 181
|182 <-> 153, 1678
|183 <-> 504, 601
|184 <-> 635, 1246
|185 <-> 180, 621
|186 <-> 1798
|187 <-> 1375
|188 <-> 148, 405, 950, 1322
|189 <-> 534, 1908
|190 <-> 1582
|191 <-> 361, 1879
|192 <-> 1814
|193 <-> 533, 1307, 1389
|194 <-> 1262
|195 <-> 1450
|196 <-> 335
|197 <-> 750
|198 <-> 285, 297, 671
|199 <-> 97, 199, 280, 1292
|200 <-> 200, 1584
|201 <-> 1519
|202 <-> 44, 1492, 1605, 1857, 1888
|203 <-> 363, 416, 504
|204 <-> 832
|205 <-> 350, 1385
|206 <-> 206
|207 <-> 584
|208 <-> 889, 1254, 1596
|209 <-> 996, 1402
|210 <-> 691, 977
|211 <-> 463
|212 <-> 23, 1318
|213 <-> 600, 933
|214 <-> 1657
|215 <-> 88, 274, 1264
|216 <-> 216, 301
|217 <-> 92, 217, 766
|218 <-> 986, 1439
|219 <-> 1217, 1294
|220 <-> 368, 736, 1543, 1704
|221 <-> 367, 806, 1273, 1804
|222 <-> 160, 682, 1257, 1660
|223 <-> 223
|224 <-> 119, 259
|225 <-> 92
|226 <-> 482, 1472
|227 <-> 1325
|228 <-> 379, 1914
|229 <-> 529, 765
|230 <-> 534
|231 <-> 1456
|232 <-> 924, 952
|233 <-> 1423, 1661, 1715
|234 <-> 429
|235 <-> 65
|236 <-> 1134, 1613
|237 <-> 237
|238 <-> 1728
|239 <-> 1543
|240 <-> 698, 832, 1022
|241 <-> 948, 1066, 1172, 1552
|242 <-> 594, 888
|243 <-> 965
|244 <-> 739, 1428
|245 <-> 1039
|246 <-> 471
|247 <-> 1414, 1650
|248 <-> 254, 1152
|249 <-> 383, 976
|250 <-> 88
|251 <-> 941, 1484
|252 <-> 21, 141, 803
|253 <-> 253
|254 <-> 248, 395
|255 <-> 909, 1334
|256 <-> 1001
|257 <-> 558, 1050, 1946
|258 <-> 516, 961
|259 <-> 224, 564, 630
|260 <-> 127, 1041, 1938
|261 <-> 697, 761
|262 <-> 262, 1928
|263 <-> 1068
|264 <-> 149, 818
|265 <-> 175
|266 <-> 1767, 1955
|267 <-> 326
|268 <-> 553
|269 <-> 1557, 1907
|270 <-> 971
|271 <-> 1039
|272 <-> 1053, 1176
|273 <-> 1248
|274 <-> 215
|275 <-> 590, 1539
|276 <-> 479, 749
|277 <-> 434, 827, 1014
|278 <-> 1219
|279 <-> 931, 1971
|280 <-> 199, 559
|281 <-> 1079
|282 <-> 996, 1746
|283 <-> 1970
|284 <-> 1376, 1692
|285 <-> 198, 1521, 1977
|286 <-> 623, 857, 1446
|287 <-> 1781, 1920
|288 <-> 417
|289 <-> 1073
|290 <-> 1411
|291 <-> 759, 1267, 1931
|292 <-> 448
|293 <-> 1426, 1675
|294 <-> 947, 1749
|295 <-> 1489, 1702
|296 <-> 791
|297 <-> 198
|298 <-> 372, 539, 566, 1183
|299 <-> 306, 1799
|300 <-> 300, 1762
|301 <-> 216
|302 <-> 1671
|303 <-> 138, 867
|304 <-> 671, 1553
|305 <-> 1018, 1186
|306 <-> 299, 321
|307 <-> 1125, 1976
|308 <-> 172, 383
|309 <-> 1037, 1766
|310 <-> 1345
|311 <-> 849, 1989
|312 <-> 312
|313 <-> 1052, 1595
|314 <-> 1405, 1923
|315 <-> 426, 543
|316 <-> 536, 968, 1363, 1529, 1572, 1906
|317 <-> 317, 747
|318 <-> 495, 1658
|319 <-> 556, 910
|320 <-> 845, 1225
|321 <-> 306, 321, 399, 1248, 1951
|322 <-> 1409
|323 <-> 323, 1046, 1287
|324 <-> 1103
|325 <-> 1681
|326 <-> 267, 758, 901
|327 <-> 411, 1475
|328 <-> 1789
|329 <-> 473, 1361
|330 <-> 639, 1763
|331 <-> 51, 331
|332 <-> 492, 1526, 1552
|333 <-> 888, 1362
|334 <-> 49
|335 <-> 196, 335, 1914
|336 <-> 457
|337 <-> 1452
|338 <-> 426
|339 <-> 339, 689, 928, 1037
|340 <-> 65, 1403, 1516, 1559
|341 <-> 1393
|342 <-> 380, 452
|343 <-> 1126, 1267, 1823
|344 <-> 1429
|345 <-> 123
|346 <-> 364, 1898
|347 <-> 151, 515, 1114
|348 <-> 621, 1263, 1501, 1907
|349 <-> 154
|350 <-> 205, 596, 775, 1627
|351 <-> 755, 1186
|352 <-> 644
|353 <-> 943, 1117
|354 <-> 917, 1980
|355 <-> 1036, 1858
|356 <-> 900, 1210, 1940
|357 <-> 489
|358 <-> 1611
|359 <-> 359
|360 <-> 360, 1838
|361 <-> 191, 1729
|362 <-> 1090, 1692
|363 <-> 203, 363
|364 <-> 346, 1373
|365 <-> 68, 365
|366 <-> 469, 873
|367 <-> 221
|368 <-> 220
|369 <-> 1594, 1712
|370 <-> 1150
|371 <-> 1705
|372 <-> 298, 974, 1206, 1882
|373 <-> 1044, 1753
|374 <-> 137, 697, 1902
|375 <-> 510, 722
|376 <-> 1431, 1502
|377 <-> 377, 1098
|378 <-> 552, 971, 1054
|379 <-> 228, 684, 1256
|380 <-> 342
|381 <-> 1896
|382 <-> 967, 1146, 1224, 1816
|383 <-> 249, 308
|384 <-> 156, 807
|385 <-> 510
|386 <-> 21, 1184, 1756
|387 <-> 440, 1016, 1505
|388 <-> 938, 1418, 1810
|389 <-> 1300
|390 <-> 1305, 1863
|391 <-> 458, 1911
|392 <-> 506, 808, 924
|393 <-> 152, 1258
|394 <-> 394
|395 <-> 254
|396 <-> 656
|397 <-> 1872
|398 <-> 1679
|399 <-> 321
|400 <-> 528, 1560
|401 <-> 1527
|402 <-> 464, 1145, 1496
|403 <-> 477
|404 <-> 627
|405 <-> 188, 1866
|406 <-> 720, 1174, 1272
|407 <-> 1048
|408 <-> 674
|409 <-> 1869
|410 <-> 1548
|411 <-> 327, 836, 1622, 1967
|412 <-> 1803, 1978
|413 <-> 523, 1511
|414 <-> 414, 694
|415 <-> 1022, 1988
|416 <-> 203
|417 <-> 288, 449, 1758
|418 <-> 418, 778, 900, 1062, 1639, 1789
|419 <-> 419, 1764
|420 <-> 991
|421 <-> 690
|422 <-> 567, 883, 1182, 1921
|423 <-> 870
|424 <-> 503
|425 <-> 1014
|426 <-> 315, 338, 901, 1336
|427 <-> 1966
|428 <-> 1606
|429 <-> 234, 1567, 1682
|430 <-> 54, 1157, 1177, 1894
|431 <-> 798, 926
|432 <-> 1683
|433 <-> 523, 854
|434 <-> 277
|435 <-> 471, 1002
|436 <-> 33, 810, 873, 1011
|437 <-> 1327, 1534
|438 <-> 1470, 1825
|439 <-> 1293, 1566
|440 <-> 387, 1006
|441 <-> 560, 1690
|442 <-> 442, 587
|443 <-> 1324, 1450
|444 <-> 1655
|445 <-> 1387, 1499
|446 <-> 1637, 1663
|447 <-> 447
|448 <-> 292, 1407, 1533, 1874
|449 <-> 417
|450 <-> 878, 1780
|451 <-> 451
|452 <-> 342, 960, 1981
|453 <-> 156
|454 <-> 1215
|455 <-> 647, 1336
|456 <-> 675, 1080, 1792
|457 <-> 336, 626, 1002
|458 <-> 391
|459 <-> 619
|460 <-> 695, 997, 1181
|461 <-> 11, 795, 1020
|462 <-> 1433
|463 <-> 211, 1038, 1361
|464 <-> 13, 402
|465 <-> 1159, 1674
|466 <-> 1386, 1405, 1493
|467 <-> 581, 1677
|468 <-> 911
|469 <-> 366
|470 <-> 76, 676
|471 <-> 246, 435, 1331, 1685
|472 <-> 938, 1136, 1755
|473 <-> 329
|474 <-> 76, 856, 1645
|475 <-> 42, 804, 1546
|476 <-> 49
|477 <-> 403, 854, 1165, 1962
|478 <-> 1254
|479 <-> 276
|480 <-> 1364
|481 <-> 623
|482 <-> 226, 949
|483 <-> 36, 993
|484 <-> 484
|485 <-> 41, 89, 880, 1008, 1994
|486 <-> 1523, 1588
|487 <-> 1122
|488 <-> 728
|489 <-> 357, 573
|490 <-> 717, 841, 1020, 1280
|491 <-> 1920
|492 <-> 332
|493 <-> 85, 1585
|494 <-> 178, 1800
|495 <-> 318, 631, 897, 1482
|496 <-> 1649
|497 <-> 176
|498 <-> 1828
|499 <-> 499, 1134
|500 <-> 657, 1331
|501 <-> 809
|502 <-> 628, 787, 1358
|503 <-> 424, 503
|504 <-> 183, 203
|505 <-> 132, 1402
|506 <-> 392, 990
|507 <-> 1027, 1638, 1684
|508 <-> 710, 716
|509 <-> 28, 509
|510 <-> 375, 385, 629, 1814
|511 <-> 892
|512 <-> 1175
|513 <-> 513, 1737
|514 <-> 5, 699, 1610, 1935
|515 <-> 347, 1471
|516 <-> 49, 258, 1514
|517 <-> 1361
|518 <-> 1174
|519 <-> 927
|520 <-> 520, 1456
|521 <-> 10, 1581
|522 <-> 65, 1448
|523 <-> 413, 433, 1215
|524 <-> 524
|525 <-> 1540
|526 <-> 14, 798
|527 <-> 527, 753
|528 <-> 400
|529 <-> 229
|530 <-> 1475, 1620
|531 <-> 531
|532 <-> 1286
|533 <-> 193, 1727
|534 <-> 189, 230
|535 <-> 991, 1366
|536 <-> 316
|537 <-> 1833
|538 <-> 970, 1270
|539 <-> 298, 704, 723
|540 <-> 623
|541 <-> 1160, 1498, 1909
|542 <-> 120
|543 <-> 315
|544 <-> 842, 1289, 1365
|545 <-> 26, 1550
|546 <-> 1722, 1886
|547 <-> 64, 796, 1612
|548 <-> 1582, 1945
|549 <-> 549, 1084
|550 <-> 1041
|551 <-> 4, 39
|552 <-> 378, 1257
|553 <-> 171, 268, 1160, 1493
|554 <-> 1190
|555 <-> 1050
|556 <-> 37, 319, 1551
|557 <-> 557
|558 <-> 257, 1779
|559 <-> 135, 280
|560 <-> 96, 441
|561 <-> 1244, 1986
|562 <-> 1209, 1820
|563 <-> 1215
|564 <-> 259, 1817
|565 <-> 565
|566 <-> 298, 1203
|567 <-> 422, 884, 1113
|568 <-> 760, 1768
|569 <-> 1449
|570 <-> 598, 759, 1728
|571 <-> 571
|572 <-> 1821
|573 <-> 489, 930, 942, 1459
|574 <-> 1872
|575 <-> 813, 1073, 1335
|576 <-> 653, 1111, 1616
|577 <-> 93, 1316
|578 <-> 837, 1645, 1683
|579 <-> 906, 1113
|580 <-> 9, 1318, 1657
|581 <-> 467, 1286, 1720
|582 <-> 60, 582
|583 <-> 1678
|584 <-> 207, 891, 1115
|585 <-> 624
|586 <-> 36, 586, 1501, 1512
|587 <-> 442, 823, 1620, 1853
|588 <-> 1147
|589 <-> 1096, 1641, 1730
|590 <-> 275, 654, 726, 1981
|591 <-> 135
|592 <-> 132
|593 <-> 820
|594 <-> 242, 611, 1743
|595 <-> 90, 630, 719, 1977
|596 <-> 350, 878, 1401
|597 <-> 781, 848, 1854
|598 <-> 570
|599 <-> 8, 1070
|600 <-> 213, 779, 1118, 1483, 1886, 1957
|601 <-> 183
|602 <-> 1265
|603 <-> 1860
|604 <-> 641, 1512
|605 <-> 1001
|606 <-> 900
|607 <-> 1302
|608 <-> 885
|609 <-> 837
|610 <-> 610, 1659
|611 <-> 147, 594
|612 <-> 922, 1560
|613 <-> 1381
|614 <-> 1071, 1893
|615 <-> 629, 741, 1865
|616 <-> 47
|617 <-> 896
|618 <-> 1721, 1754, 1902
|619 <-> 459, 619, 1032
|620 <-> 679, 1449
|621 <-> 185, 348, 1301
|622 <-> 1244
|623 <-> 179, 286, 481, 540
|624 <-> 585, 1009, 1134
|625 <-> 1181, 1433
|626 <-> 457, 626, 1500, 1932
|627 <-> 16, 404
|628 <-> 502
|629 <-> 510, 615, 927
|630 <-> 259, 595
|631 <-> 495, 976, 1228
|632 <-> 1912
|633 <-> 694, 894
|634 <-> 1657
|635 <-> 184
|636 <-> 911, 1730, 1945
|637 <-> 981, 1909
|638 <-> 907
|639 <-> 27, 330, 639, 1663
|640 <-> 1229, 1939
|641 <-> 604
|642 <-> 896
|643 <-> 850
|644 <-> 85, 352, 735, 1025
|645 <-> 783
|646 <-> 110, 1825
|647 <-> 455
|648 <-> 1043
|649 <-> 1532
|650 <-> 105, 833, 1060, 1371
|651 <-> 1437, 1751
|652 <-> 1019
|653 <-> 576, 1314, 1393
|654 <-> 590
|655 <-> 716, 779
|656 <-> 396, 773, 1603
|657 <-> 500
|658 <-> 109, 738
|659 <-> 1527, 1951
|660 <-> 1685
|661 <-> 34
|662 <-> 1196, 1252
|663 <-> 1729
|664 <-> 23
|665 <-> 1224
|666 <-> 1213
|667 <-> 1786, 1919
|668 <-> 1369
|669 <-> 669, 785
|670 <-> 926, 1642
|671 <-> 198, 304
|672 <-> 4
|673 <-> 154
|674 <-> 408, 1062
|675 <-> 456
|676 <-> 470, 1194
|677 <-> 104
|678 <-> 821
|679 <-> 620
|680 <-> 687, 931
|681 <-> 959, 1711
|682 <-> 222, 1941
|683 <-> 1594
|684 <-> 379
|685 <-> 1200, 1897
|686 <-> 29, 1399
|687 <-> 680
|688 <-> 722
|689 <-> 339, 1391
|690 <-> 421, 1666
|691 <-> 210
|692 <-> 1165
|693 <-> 923, 1761
|694 <-> 414, 633, 757
|695 <-> 460, 726, 1880
|696 <-> 113, 1228, 1240
|697 <-> 155, 261, 374, 1477
|698 <-> 240
|699 <-> 514, 706
|700 <-> 746
|701 <-> 905, 1064
|702 <-> 952, 1097
|703 <-> 703, 1875
|704 <-> 539, 1328
|705 <-> 84, 1621
|706 <-> 699, 1604
|707 <-> 707
|708 <-> 708
|709 <-> 38, 1064
|710 <-> 111, 508, 1362
|711 <-> 1545
|712 <-> 899, 1139
|713 <-> 1228
|714 <-> 85, 1297
|715 <-> 2, 754, 1808
|716 <-> 508, 655
|717 <-> 50, 490
|718 <-> 1382, 1648
|719 <-> 595, 1024
|720 <-> 406, 1096, 1261
|721 <-> 45, 1213
|722 <-> 375, 688, 1632
|723 <-> 539
|724 <-> 891
|725 <-> 17, 1045
|726 <-> 590, 695, 1958
|727 <-> 747
|728 <-> 488, 728
|729 <-> 729, 1150
|730 <-> 730
|731 <-> 1181, 1273
|732 <-> 127, 1269
|733 <-> 1803
|734 <-> 1005, 1496
|735 <-> 644
|736 <-> 220
|737 <-> 1383
|738 <-> 658, 1259, 1687
|739 <-> 244
|740 <-> 946, 1163, 1279
|741 <-> 615, 1690
|742 <-> 800, 878, 1609
|743 <-> 1647
|744 <-> 744, 1778
|745 <-> 1181
|746 <-> 150, 700, 1082, 1727
|747 <-> 317, 727
|748 <-> 877
|749 <-> 276, 1040
|750 <-> 197, 750, 1201
|751 <-> 1159, 1479
|752 <-> 1642
|753 <-> 527
|754 <-> 715, 1809
|755 <-> 351, 1088, 1560
|756 <-> 756
|757 <-> 694
|758 <-> 326, 954, 1988
|759 <-> 44, 291, 570, 1038
|760 <-> 568, 1304, 1620
|761 <-> 261, 1537
|762 <-> 1943
|763 <-> 948, 1232, 1375
|764 <-> 45, 1839
|765 <-> 229, 1066
|766 <-> 217
|767 <-> 1501, 1587, 1640
|768 <-> 868, 1911
|769 <-> 75
|770 <-> 1724
|771 <-> 64, 1124, 1606
|772 <-> 1721
|773 <-> 656, 1197, 1756
|774 <-> 1422, 1835
|775 <-> 350, 844
|776 <-> 1204
|777 <-> 1073, 1448
|778 <-> 418
|779 <-> 600, 655
|780 <-> 1111, 1274
|781 <-> 597
|782 <-> 129, 1600
|783 <-> 645, 1627
|784 <-> 79, 947
|785 <-> 669
|786 <-> 90
|787 <-> 502, 816, 1625, 1821
|788 <-> 943
|789 <-> 1835
|790 <-> 1625
|791 <-> 296, 1092, 1930
|792 <-> 830
|793 <-> 1876
|794 <-> 1156, 1626, 1813
|795 <-> 0, 461
|796 <-> 547
|797 <-> 1565, 1589, 1669
|798 <-> 431, 526, 1278
|799 <-> 1643
|800 <-> 742, 1761
|801 <-> 858
|802 <-> 1367
|803 <-> 142, 252
|804 <-> 475, 1268, 1758, 1991
|805 <-> 1218, 1832
|806 <-> 221
|807 <-> 384, 1140, 1460, 1872, 1999
|808 <-> 392, 1417
|809 <-> 501, 884
|810 <-> 436
|811 <-> 1813
|812 <-> 819
|813 <-> 575
|814 <-> 1282, 1966
|815 <-> 815, 1579
|816 <-> 787, 1676
|817 <-> 1051, 1671
|818 <-> 264, 928, 1065
|819 <-> 812, 819
|820 <-> 593, 868, 1107, 1919
|821 <-> 678, 879, 1551, 1681, 1774
|822 <-> 822
|823 <-> 587
|824 <-> 1092, 1412, 1992
|825 <-> 166
|826 <-> 56, 1073
|827 <-> 35, 277
|828 <-> 1847
|829 <-> 1028
|830 <-> 792, 1007
|831 <-> 1799
|832 <-> 144, 204, 240, 1329
|833 <-> 650, 1685
|834 <-> 1379
|835 <-> 1355, 1844
|836 <-> 411
|837 <-> 578, 609, 1489
|838 <-> 1144, 1441
|839 <-> 1593
|840 <-> 1045
|841 <-> 112, 490, 1436
|842 <-> 544
|843 <-> 1371
|844 <-> 775
|845 <-> 320, 1556, 1591
|846 <-> 104, 1094
|847 <-> 847, 1654
|848 <-> 597, 1090
|849 <-> 311, 1773
|850 <-> 643, 1875
|851 <-> 858, 1524
|852 <-> 1504, 1541, 1990
|853 <-> 53
|854 <-> 433, 477
|855 <-> 1502, 1860
|856 <-> 474
|857 <-> 286, 857
|858 <-> 801, 851, 858, 1547, 1652
|859 <-> 1969
|860 <-> 1181
|861 <-> 955
|862 <-> 1350, 1624
|863 <-> 863
|864 <-> 1457
|865 <-> 1355, 1491
|866 <-> 1373
|867 <-> 303, 987
|868 <-> 58, 136, 768, 820
|869 <-> 1426, 1744
|870 <-> 423, 1608
|871 <-> 1312
|872 <-> 872, 1226
|873 <-> 366, 436
|874 <-> 1983
|875 <-> 1138, 1232
|876 <-> 1324
|877 <-> 748, 1464, 1846
|878 <-> 450, 596, 742
|879 <-> 821
|880 <-> 485
|881 <-> 1246, 1286
|882 <-> 946, 1221
|883 <-> 422, 886, 1830
|884 <-> 567, 809
|885 <-> 608, 1856
|886 <-> 883, 1787
|887 <-> 1035, 1331, 1438, 1604
|888 <-> 242, 333
|889 <-> 208, 935
|890 <-> 1211, 1847
|891 <-> 584, 724
|892 <-> 83, 84, 511, 1478, 1530, 1983
|893 <-> 1494
|894 <-> 633
|895 <-> 1045, 1124, 1745
|896 <-> 12, 617, 642, 896
|897 <-> 495
|898 <-> 898, 1586
|899 <-> 712
|900 <-> 356, 418, 606, 1026, 1074
|901 <-> 326, 426
|902 <-> 1790
|903 <-> 46, 969, 1715
|904 <-> 146, 1964
|905 <-> 701, 1273, 1410
|906 <-> 579, 1713, 1878
|907 <-> 638, 907
|908 <-> 59, 1195
|909 <-> 255, 1669
|910 <-> 319
|911 <-> 468, 636
|912 <-> 1076
|913 <-> 1067, 1101, 1397, 1790
|914 <-> 1383, 1825
|915 <-> 1827
|916 <-> 1938
|917 <-> 354, 991
|918 <-> 1013
|919 <-> 1086
|920 <-> 995
|921 <-> 122, 146
|922 <-> 612
|923 <-> 693, 1916
|924 <-> 232, 392, 1782
|925 <-> 1553
|926 <-> 431, 670
|927 <-> 519, 629
|928 <-> 339, 818
|929 <-> 1220
|930 <-> 42, 573
|931 <-> 279, 680, 1593
|932 <-> 1470, 1534
|933 <-> 213
|934 <-> 1205, 1387
|935 <-> 889
|936 <-> 1984
|937 <-> 937, 1817
|938 <-> 388, 472, 1133, 1808
|939 <-> 1147, 1750, 1884
|940 <-> 1097
|941 <-> 251
|942 <-> 573, 1994
|943 <-> 353, 788
|944 <-> 1103, 1979
|945 <-> 1824
|946 <-> 740, 882, 1716
|947 <-> 294, 784, 1381, 1960
|948 <-> 241, 763, 1368
|949 <-> 482
|950 <-> 188
|951 <-> 1711
|952 <-> 232, 702
|953 <-> 133, 1028, 1375, 1519
|954 <-> 758, 1733
|955 <-> 165, 861, 1442, 1664
|956 <-> 956, 1590
|957 <-> 957
|958 <-> 84
|959 <-> 29, 681
|960 <-> 452
|961 <-> 258
|962 <-> 80
|963 <-> 963
|964 <-> 1742
|965 <-> 243, 965
|966 <-> 1515, 1745
|967 <-> 382, 1712, 1754
|968 <-> 316
|969 <-> 903, 1777
|970 <-> 538, 1278, 1463
|971 <-> 270, 378
|972 <-> 1985
|973 <-> 1565
|974 <-> 372, 1738
|975 <-> 1734
|976 <-> 249, 631
|977 <-> 210, 1846
|978 <-> 1171
|979 <-> 1786
|980 <-> 1871
|981 <-> 637
|982 <-> 1449
|983 <-> 24, 1567
|984 <-> 1372
|985 <-> 985, 1285
|986 <-> 121, 218, 988, 1836
|987 <-> 867
|988 <-> 986, 1276, 1526
|989 <-> 1268, 1709
|990 <-> 506, 990
|991 <-> 420, 535, 917, 1390
|992 <-> 1628
|993 <-> 483, 1765
|994 <-> 1068
|995 <-> 920, 995
|996 <-> 209, 282
|997 <-> 16, 460, 1122, 1769
|998 <-> 1076, 1602
|999 <-> 1001, 1697""".stripMargin
val input1 = """1000 <-> 1648, 1915
|1001 <-> 256, 605, 999, 1091
|1002 <-> 435, 457
|1003 <-> 1382
|1004 <-> 1254
|1005 <-> 20, 734, 1651
|1006 <-> 440
|1007 <-> 830, 1007
|1008 <-> 485
|1009 <-> 624
|1010 <-> 1353
|1011 <-> 139, 436, 1675
|1012 <-> 1836
|1013 <-> 918, 1891
|1014 <-> 277, 425
|1015 <-> 1191
|1016 <-> 387
|1017 <-> 1483
|1018 <-> 305
|1019 <-> 652, 1798
|1020 <-> 461, 490, 1843
|1021 <-> 1021
|1022 <-> 240, 415, 1507
|1023 <-> 1919
|1024 <-> 719, 1925
|1025 <-> 644, 1735
|1026 <-> 900
|1027 <-> 507, 1432
|1028 <-> 829, 953, 1927
|1029 <-> 1029
|1030 <-> 1923
|1031 <-> 1505
|1032 <-> 619, 1151
|1033 <-> 1949
|1034 <-> 1115
|1035 <-> 887
|1036 <-> 355
|1037 <-> 168, 309, 339, 1835
|1038 <-> 463, 759
|1039 <-> 154, 245, 271
|1040 <-> 99, 749, 1153, 1477
|1041 <-> 260, 550
|1042 <-> 1814
|1043 <-> 648, 1091
|1044 <-> 373, 1614
|1045 <-> 725, 840, 895, 1309
|1046 <-> 323
|1047 <-> 1238, 1499, 1569
|1048 <-> 407, 1533
|1049 <-> 1856
|1050 <-> 257, 555
|1051 <-> 817, 1051
|1052 <-> 313
|1053 <-> 47, 272
|1054 <-> 378, 1648
|1055 <-> 1055
|1056 <-> 180, 1387
|1057 <-> 1057, 1793, 1924
|1058 <-> 118, 1474
|1059 <-> 1566, 1851
|1060 <-> 650
|1061 <-> 96, 1063
|1062 <-> 418, 674
|1063 <-> 1061
|1064 <-> 701, 709, 1867, 1963
|1065 <-> 818
|1066 <-> 241, 765
|1067 <-> 913
|1068 <-> 8, 263, 994
|1069 <-> 1555
|1070 <-> 175, 599, 1070
|1071 <-> 614, 1245
|1072 <-> 1086, 1685
|1073 <-> 289, 575, 777, 826
|1074 <-> 900, 1434
|1075 <-> 1492
|1076 <-> 912, 998, 1119
|1077 <-> 1183
|1078 <-> 1771, 1792
|1079 <-> 86, 281, 1167
|1080 <-> 75, 456, 1168, 1337
|1081 <-> 1741
|1082 <-> 746
|1083 <-> 1378
|1084 <-> 549, 1199
|1085 <-> 1085
|1086 <-> 919, 1072
|1087 <-> 1087, 1726
|1088 <-> 755
|1089 <-> 1089
|1090 <-> 362, 848, 1474
|1091 <-> 1001, 1043
|1092 <-> 791, 824, 1933
|1093 <-> 1190
|1094 <-> 846
|1095 <-> 1095
|1096 <-> 589, 720, 1096
|1097 <-> 702, 940
|1098 <-> 377
|1099 <-> 1099
|1100 <-> 1212
|1101 <-> 913, 1543
|1102 <-> 34, 1392, 1626, 1985
|1103 <-> 324, 944, 1348, 1494, 1981
|1104 <-> 1104
|1105 <-> 1400
|1106 <-> 1678, 1842, 1974
|1107 <-> 820
|1108 <-> 1202
|1109 <-> 1219, 1539
|1110 <-> 1144, 1179
|1111 <-> 576, 780
|1112 <-> 1357
|1113 <-> 567, 579
|1114 <-> 347, 1696
|1115 <-> 76, 584, 1034, 1981
|1116 <-> 116
|1117 <-> 127, 353, 1635
|1118 <-> 600
|1119 <-> 1076, 1445
|1120 <-> 1735, 1946
|1121 <-> 1778
|1122 <-> 487, 997, 1253
|1123 <-> 1792
|1124 <-> 771, 895, 1266
|1125 <-> 307
|1126 <-> 343
|1127 <-> 1127, 1164
|1128 <-> 78, 1700
|1129 <-> 1149, 1625
|1130 <-> 1871
|1131 <-> 1131
|1132 <-> 1207, 1208, 1861
|1133 <-> 938
|1134 <-> 236, 499, 624
|1135 <-> 1489, 1607
|1136 <-> 472
|1137 <-> 1298
|1138 <-> 875
|1139 <-> 712, 1139
|1140 <-> 807
|1141 <-> 1329
|1142 <-> 1170, 1559
|1143 <-> 1143
|1144 <-> 838, 1110, 1223
|1145 <-> 402, 1145
|1146 <-> 382, 1364
|1147 <-> 588, 939
|1148 <-> 1421, 1831
|1149 <-> 1129, 1905, 1959
|1150 <-> 370, 729
|1151 <-> 128, 1032, 1233
|1152 <-> 248, 1152, 1708, 1803
|1153 <-> 1040, 1377
|1154 <-> 1209
|1155 <-> 74, 1787
|1156 <-> 794
|1157 <-> 430, 1975
|1158 <-> 1158, 1592
|1159 <-> 465, 751, 1454
|1160 <-> 541, 553, 1175
|1161 <-> 1786, 1824
|1162 <-> 1262, 1321, 1876
|1163 <-> 740, 1283, 1903
|1164 <-> 1127
|1165 <-> 477, 692
|1166 <-> 1344, 1967
|1167 <-> 1079
|1168 <-> 22, 1080
|1169 <-> 1172, 1647
|1170 <-> 1142
|1171 <-> 978, 1171
|1172 <-> 241, 1169, 1723
|1173 <-> 1375
|1174 <-> 406, 518, 1323
|1175 <-> 512, 1160, 1343, 1982
|1176 <-> 272, 1176
|1177 <-> 430
|1178 <-> 1910
|1179 <-> 1110
|1180 <-> 1596
|1181 <-> 460, 625, 731, 745, 860, 1647
|1182 <-> 422
|1183 <-> 298, 1077
|1184 <-> 386
|1185 <-> 1729, 1972
|1186 <-> 87, 305, 351
|1187 <-> 1454, 1670
|1188 <-> 1779, 1976
|1189 <-> 1731, 1794, 1980
|1190 <-> 554, 1093, 1326, 1332, 1999
|1191 <-> 1015, 1784, 1920, 1998
|1192 <-> 1923, 1937
|1193 <-> 1333
|1194 <-> 159, 676
|1195 <-> 908, 1311, 1805
|1196 <-> 39, 662
|1197 <-> 773
|1198 <-> 1468
|1199 <-> 1084, 1826
|1200 <-> 63, 685, 1490
|1201 <-> 750
|1202 <-> 1108, 1618
|1203 <-> 566
|1204 <-> 776, 1204
|1205 <-> 934
|1206 <-> 372
|1207 <-> 1132, 1207, 1342
|1208 <-> 1132
|1209 <-> 562, 1154, 1840
|1210 <-> 356
|1211 <-> 890, 1259
|1212 <-> 49, 1100, 1385
|1213 <-> 666, 721, 1469, 1583, 1984
|1214 <-> 1734
|1215 <-> 454, 523, 563
|1216 <-> 1583
|1217 <-> 219, 1749
|1218 <-> 805, 1611
|1219 <-> 278, 1109
|1220 <-> 929, 1904, 1919
|1221 <-> 882
|1222 <-> 1462
|1223 <-> 1144, 1223, 1384
|1224 <-> 382, 665
|1225 <-> 118, 320
|1226 <-> 872, 1744, 1895
|1227 <-> 1601
|1228 <-> 631, 696, 713
|1229 <-> 120, 640, 1642, 1993
|1230 <-> 1400, 1494
|1231 <-> 1942
|1232 <-> 156, 763, 875
|1233 <-> 1151
|1234 <-> 1234
|1235 <-> 1510, 1888
|1236 <-> 1591
|1237 <-> 1912
|1238 <-> 1047
|1239 <-> 1371
|1240 <-> 87, 696, 1799
|1241 <-> 160, 1915
|1242 <-> 1242, 1900
|1243 <-> 1303
|1244 <-> 561, 622, 1942
|1245 <-> 158, 1071
|1246 <-> 184, 881, 1899
|1247 <-> 1539
|1248 <-> 273, 321
|1249 <-> 1324
|1250 <-> 1354
|1251 <-> 127
|1252 <-> 662, 1304, 1374
|1253 <-> 1122
|1254 <-> 208, 478, 1004, 1378
|1255 <-> 1995
|1256 <-> 379, 1349
|1257 <-> 222, 552
|1258 <-> 155, 393, 1574, 1647
|1259 <-> 124, 738, 1211, 1409
|1260 <-> 1862
|1261 <-> 720
|1262 <-> 194, 1162, 1349, 1458
|1263 <-> 348
|1264 <-> 215
|1265 <-> 602, 1265, 1970
|1266 <-> 22, 1124
|1267 <-> 291, 343, 1729, 1918
|1268 <-> 103, 804, 989
|1269 <-> 732
|1270 <-> 538
|1271 <-> 25, 1285
|1272 <-> 406, 1629
|1273 <-> 221, 731, 905
|1274 <-> 35, 780
|1275 <-> 1752
|1276 <-> 988
|1277 <-> 1788
|1278 <-> 798, 970
|1279 <-> 740
|1280 <-> 490, 1763
|1281 <-> 1281
|1282 <-> 814, 1341
|1283 <-> 1163
|1284 <-> 1447, 1494
|1285 <-> 985, 1271
|1286 <-> 532, 581, 881
|1287 <-> 323
|1288 <-> 1681
|1289 <-> 544, 1665, 1928
|1290 <-> 168
|1291 <-> 1435
|1292 <-> 199
|1293 <-> 439
|1294 <-> 219
|1295 <-> 1526
|1296 <-> 1296, 1411
|1297 <-> 174, 714
|1298 <-> 61, 1137, 1416, 1724, 1979
|1299 <-> 1673
|1300 <-> 389, 1464
|1301 <-> 621
|1302 <-> 607, 1788
|1303 <-> 1243, 1303
|1304 <-> 760, 1252
|1305 <-> 390, 1452
|1306 <-> 1728
|1307 <-> 59, 193
|1308 <-> 1943
|1309 <-> 1045, 1403
|1310 <-> 1938
|1311 <-> 98, 1195
|1312 <-> 871, 1478, 1834
|1313 <-> 1379
|1314 <-> 653
|1315 <-> 106, 1955, 1968
|1316 <-> 577, 1523
|1317 <-> 1826
|1318 <-> 212, 580
|1319 <-> 1371
|1320 <-> 1406
|1321 <-> 1162
|1322 <-> 188
|1323 <-> 1174, 1633
|1324 <-> 443, 876, 1249, 1832
|1325 <-> 227, 1569
|1326 <-> 1190
|1327 <-> 437
|1328 <-> 704, 1689
|1329 <-> 832, 1141, 1330
|1330 <-> 1329, 1330
|1331 <-> 471, 500, 887
|1332 <-> 1190, 1429
|1333 <-> 1193, 1792
|1334 <-> 255, 1345
|1335 <-> 575
|1336 <-> 426, 455, 1913
|1337 <-> 1080
|1338 <-> 167, 1338
|1339 <-> 1517
|1340 <-> 1866
|1341 <-> 1282
|1342 <-> 1207
|1343 <-> 1175
|1344 <-> 1166
|1345 <-> 310, 1334
|1346 <-> 1346, 1719
|1347 <-> 1375
|1348 <-> 1103
|1349 <-> 1256, 1262
|1350 <-> 862, 1350
|1351 <-> 78, 1444
|1352 <-> 1845
|1353 <-> 1010, 1922
|1354 <-> 1250, 1363
|1355 <-> 72, 835, 865, 1936
|1356 <-> 25
|1357 <-> 1112, 1357
|1358 <-> 502
|1359 <-> 1814
|1360 <-> 1468
|1361 <-> 3, 329, 463, 517
|1362 <-> 333, 710
|1363 <-> 316, 1354, 1759
|1364 <-> 480, 1146
|1365 <-> 544
|1366 <-> 91, 535
|1367 <-> 802, 1543, 1609
|1368 <-> 948, 1631, 1864
|1369 <-> 668, 1964
|1370 <-> 1370
|1371 <-> 650, 843, 1239, 1319, 1528
|1372 <-> 984, 1447
|1373 <-> 62, 364, 866, 1884
|1374 <-> 1252
|1375 <-> 57, 187, 763, 953, 1173, 1347
|1376 <-> 284, 1878
|1377 <-> 161, 1153
|1378 <-> 1083, 1254, 1378, 1856
|1379 <-> 834, 1313, 1792
|1380 <-> 1967
|1381 <-> 613, 947, 1523
|1382 <-> 718, 1003, 1796
|1383 <-> 737, 914
|1384 <-> 1223
|1385 <-> 205, 1212
|1386 <-> 466, 1623
|1387 <-> 445, 934, 1056
|1388 <-> 1456
|1389 <-> 193, 1427, 1701
|1390 <-> 991
|1391 <-> 689
|1392 <-> 1102
|1393 <-> 341, 653, 1513
|1394 <-> 1509
|1395 <-> 1409
|1396 <-> 1593, 1982
|1397 <-> 100, 913
|1398 <-> 1668
|1399 <-> 686
|1400 <-> 1105, 1230
|1401 <-> 596, 1506
|1402 <-> 209, 505, 1628
|1403 <-> 340, 1309
|1404 <-> 1754
|1405 <-> 314, 466
|1406 <-> 1320, 1796, 1883
|1407 <-> 448, 1542
|1408 <-> 1616
|1409 <-> 322, 1259, 1395, 1462
|1410 <-> 905
|1411 <-> 290, 1296
|1412 <-> 50, 824
|1413 <-> 1943, 1955, 1997
|1414 <-> 247
|1415 <-> 1415
|1416 <-> 1298
|1417 <-> 808
|1418 <-> 388, 1487, 1666
|1419 <-> 90
|1420 <-> 1435, 1486, 1947
|1421 <-> 1148, 1679
|1422 <-> 774
|1423 <-> 233
|1424 <-> 1670
|1425 <-> 1910
|1426 <-> 293, 869
|1427 <-> 1389, 1634, 1740
|1428 <-> 244, 1428, 1831
|1429 <-> 344, 1332
|1430 <-> 1985
|1431 <-> 376
|1432 <-> 1027
|1433 <-> 462, 625
|1434 <-> 1074
|1435 <-> 1291, 1420
|1436 <-> 841
|1437 <-> 651, 1616
|1438 <-> 887
|1439 <-> 218
|1440 <-> 1770, 1809
|1441 <-> 838
|1442 <-> 955, 1714
|1443 <-> 64
|1444 <-> 1351
|1445 <-> 1119, 1445
|1446 <-> 286
|1447 <-> 1284, 1372
|1448 <-> 522, 777, 1969
|1449 <-> 136, 569, 620, 982
|1450 <-> 195, 443, 1516
|1451 <-> 1451
|1452 <-> 337, 1305, 1552
|1453 <-> 1801, 1906
|1454 <-> 1159, 1187
|1455 <-> 1562
|1456 <-> 231, 520, 1388, 1775, 1833
|1457 <-> 864, 1905
|1458 <-> 1262
|1459 <-> 573
|1460 <-> 807
|1461 <-> 1599, 1706
|1462 <-> 1222, 1409
|1463 <-> 970, 1937
|1464 <-> 877, 1300, 1677
|1465 <-> 1602
|1466 <-> 1919
|1467 <-> 1467
|1468 <-> 1198, 1360, 1987
|1469 <-> 1213, 1896
|1470 <-> 136, 438, 932
|1471 <-> 515, 1952
|1472 <-> 65, 226
|1473 <-> 1585
|1474 <-> 1058, 1090
|1475 <-> 327, 530
|1476 <-> 95, 1627, 1866
|1477 <-> 697, 1040, 1827
|1478 <-> 892, 1312, 1478
|1479 <-> 751
|1480 <-> 1480
|1481 <-> 1481
|1482 <-> 495
|1483 <-> 600, 1017
|1484 <-> 251, 1717, 1920
|1485 <-> 1618, 1797
|1486 <-> 1420
|1487 <-> 1418, 1828
|1488 <-> 1545
|1489 <-> 295, 837, 1135, 1859
|1490 <-> 170, 178, 1200
|1491 <-> 865, 1500, 1858
|1492 <-> 157, 202, 1075
|1493 <-> 466, 553
|1494 <-> 893, 1103, 1230, 1284
|1495 <-> 118
|1496 <-> 402, 734
|1497 <-> 1953
|1498 <-> 541, 1662
|1499 <-> 445, 1047
|1500 <-> 626, 1491, 1922
|1501 <-> 348, 586, 767
|1502 <-> 376, 855, 1960, 1965
|1503 <-> 1755
|1504 <-> 852
|1505 <-> 387, 1031, 1854
|1506 <-> 1401
|1507 <-> 1022
|1508 <-> 1853
|1509 <-> 1394, 1509, 1732
|1510 <-> 1235
|1511 <-> 413, 1990
|1512 <-> 586, 604, 1862
|1513 <-> 1393
|1514 <-> 516
|1515 <-> 966, 1716
|1516 <-> 340, 1450
|1517 <-> 9, 1339, 1587
|1518 <-> 1518, 1912, 1956
|1519 <-> 71, 201, 953
|1520 <-> 1520
|1521 <-> 29, 285, 1906
|1522 <-> 1538, 1994
|1523 <-> 486, 1316, 1381
|1524 <-> 851
|1525 <-> 1737
|1526 <-> 332, 988, 1295
|1527 <-> 401, 659
|1528 <-> 1371
|1529 <-> 316
|1530 <-> 892
|1531 <-> 1531
|1532 <-> 117, 649
|1533 <-> 35, 448, 1048
|1534 <-> 437, 932
|1535 <-> 1630
|1536 <-> 119
|1537 <-> 761, 1869
|1538 <-> 1522
|1539 <-> 275, 1109, 1247
|1540 <-> 525, 1540
|1541 <-> 852, 1541
|1542 <-> 1407, 1694
|1543 <-> 220, 239, 1101, 1367
|1544 <-> 1972
|1545 <-> 132, 711, 1488
|1546 <-> 475
|1547 <-> 86, 858
|1548 <-> 410, 1616
|1549 <-> 1852
|1550 <-> 545, 1711
|1551 <-> 556, 821
|1552 <-> 241, 332, 1452, 1987
|1553 <-> 304, 925
|1554 <-> 1554
|1555 <-> 1069, 1727
|1556 <-> 845, 1561
|1557 <-> 269
|1558 <-> 1558
|1559 <-> 340, 1142
|1560 <-> 400, 612, 755
|1561 <-> 1556
|1562 <-> 1455, 1697
|1563 <-> 1563, 1736
|1564 <-> 77, 1564
|1565 <-> 115, 797, 973
|1566 <-> 80, 439, 1059
|1567 <-> 134, 429, 983
|1568 <-> 1570
|1569 <-> 1047, 1325
|1570 <-> 1568, 1932
|1571 <-> 1628, 1755
|1572 <-> 316
|1573 <-> 173
|1574 <-> 1258
|1575 <-> 1856
|1576 <-> 1708
|1577 <-> 1577
|1578 <-> 101, 1660
|1579 <-> 815
|1580 <-> 1580
|1581 <-> 521, 1689
|1582 <-> 131, 190, 548
|1583 <-> 1213, 1216
|1584 <-> 200
|1585 <-> 493, 1473
|1586 <-> 898
|1587 <-> 767, 1517
|1588 <-> 486
|1589 <-> 797, 1822
|1590 <-> 956
|1591 <-> 845, 1236, 1688
|1592 <-> 1158
|1593 <-> 839, 931, 1396
|1594 <-> 369, 683
|1595 <-> 313, 1731
|1596 <-> 208, 1180
|1597 <-> 65
|1598 <-> 1598
|1599 <-> 1461
|1600 <-> 782
|1601 <-> 138, 1227, 1837, 1932
|1602 <-> 998, 1465
|1603 <-> 656
|1604 <-> 173, 706, 887
|1605 <-> 66, 202
|1606 <-> 428, 771
|1607 <-> 1135
|1608 <-> 19, 870, 1608
|1609 <-> 742, 1367
|1610 <-> 514, 1703
|1611 <-> 358, 1218
|1612 <-> 547
|1613 <-> 236
|1614 <-> 1044
|1615 <-> 1697
|1616 <-> 576, 1408, 1437, 1548
|1617 <-> 1617
|1618 <-> 1202, 1485
|1619 <-> 1910
|1620 <-> 530, 587, 760
|1621 <-> 705
|1622 <-> 143, 411
|1623 <-> 1386
|1624 <-> 85, 862, 1691
|1625 <-> 787, 790, 1129
|1626 <-> 794, 1102
|1627 <-> 350, 783, 1476, 1822
|1628 <-> 992, 1402, 1571
|1629 <-> 1272, 1783
|1630 <-> 1535, 1630
|1631 <-> 1368, 1973
|1632 <-> 722
|1633 <-> 1323
|1634 <-> 1427
|1635 <-> 55, 1117
|1636 <-> 1636
|1637 <-> 446
|1638 <-> 507
|1639 <-> 177, 418
|1640 <-> 767, 1989
|1641 <-> 589
|1642 <-> 670, 752, 1229
|1643 <-> 799, 1977
|1644 <-> 63
|1645 <-> 474, 578
|1646 <-> 1829
|1647 <-> 743, 1169, 1181, 1258
|1648 <-> 718, 1000, 1054
|1649 <-> 496, 1649
|1650 <-> 247, 1806
|1651 <-> 1005
|1652 <-> 858
|1653 <-> 1684, 1747, 1949
|1654 <-> 847
|1655 <-> 123, 444, 1771
|1656 <-> 1705
|1657 <-> 214, 580, 634
|1658 <-> 318
|1659 <-> 610
|1660 <-> 222, 1578
|1661 <-> 233, 1661
|1662 <-> 1498
|1663 <-> 103, 446, 639
|1664 <-> 955, 1874
|1665 <-> 1289
|1666 <-> 690, 1418
|1667 <-> 1792
|1668 <-> 1398, 1668
|1669 <-> 797, 909, 1709
|1670 <-> 1187, 1424
|1671 <-> 302, 817
|1672 <-> 1851
|1673 <-> 1299, 1673
|1674 <-> 465, 1730
|1675 <-> 293, 1011
|1676 <-> 816, 1891
|1677 <-> 467, 1464, 1787
|1678 <-> 182, 583, 1106, 1852
|1679 <-> 398, 1421
|1680 <-> 1680
|1681 <-> 325, 821, 1288
|1682 <-> 429, 1682
|1683 <-> 432, 578
|1684 <-> 507, 1653, 1806, 1841
|1685 <-> 114, 471, 660, 833, 1072
|1686 <-> 1691
|1687 <-> 738
|1688 <-> 1591
|1689 <-> 1328, 1581, 1795
|1690 <-> 441, 741, 1854
|1691 <-> 1624, 1686
|1692 <-> 284, 362
|1693 <-> 1781
|1694 <-> 1542
|1695 <-> 1775
|1696 <-> 1114
|1697 <-> 177, 999, 1562, 1615, 1996
|1698 <-> 3, 1809
|1699 <-> 1761
|1700 <-> 7, 1128
|1701 <-> 1389, 1802
|1702 <-> 295
|1703 <-> 1610
|1704 <-> 220
|1705 <-> 371, 1656, 1867
|1706 <-> 142, 1461
|1707 <-> 1960
|1708 <-> 1152, 1576, 1961
|1709 <-> 989, 1669
|1710 <-> 138
|1711 <-> 681, 951, 1550
|1712 <-> 19, 369, 967
|1713 <-> 906, 1812
|1714 <-> 1442, 1785
|1715 <-> 233, 903
|1716 <-> 946, 1515
|1717 <-> 84, 1484
|1718 <-> 1718
|1719 <-> 102, 1346
|1720 <-> 146, 581
|1721 <-> 31, 618, 772
|1722 <-> 546
|1723 <-> 108, 1172
|1724 <-> 770, 1298
|1725 <-> 1896
|1726 <-> 1087
|1727 <-> 533, 746, 1555
|1728 <-> 238, 570, 1306
|1729 <-> 361, 663, 1185, 1267
|1730 <-> 589, 636, 1674
|1731 <-> 1189, 1595
|1732 <-> 1509
|1733 <-> 954
|1734 <-> 93, 975, 1214
|1735 <-> 1025, 1120
|1736 <-> 1563
|1737 <-> 513, 1525
|1738 <-> 974
|1739 <-> 1742
|1740 <-> 1427
|1741 <-> 1081, 1950
|1742 <-> 964, 1739, 1923
|1743 <-> 594, 1921
|1744 <-> 869, 1226
|1745 <-> 895, 966, 1829
|1746 <-> 282
|1747 <-> 1653, 1747, 1910
|1748 <-> 1982
|1749 <-> 294, 1217
|1750 <-> 939
|1751 <-> 651
|1752 <-> 1275, 1752
|1753 <-> 373, 1969
|1754 <-> 618, 967, 1404
|1755 <-> 472, 1503, 1571
|1756 <-> 386, 773, 1777
|1757 <-> 22
|1758 <-> 417, 804
|1759 <-> 1363
|1760 <-> 1935
|1761 <-> 693, 800, 1699
|1762 <-> 300
|1763 <-> 330, 1280
|1764 <-> 419
|1765 <-> 993
|1766 <-> 309
|1767 <-> 266, 1821
|1768 <-> 568
|1769 <-> 997
|1770 <-> 1440
|1771 <-> 1078, 1655, 1873
|1772 <-> 1772
|1773 <-> 849
|1774 <-> 821, 1783
|1775 <-> 1456, 1695
|1776 <-> 1889, 1943
|1777 <-> 969, 1756
|1778 <-> 744, 1121
|1779 <-> 558, 1188
|1780 <-> 450
|1781 <-> 70, 287, 1693
|1782 <-> 924
|1783 <-> 1629, 1774
|1784 <-> 81, 1191
|1785 <-> 1714
|1786 <-> 667, 979, 1161
|1787 <-> 886, 1155, 1677
|1788 <-> 147, 1277, 1302, 1950
|1789 <-> 328, 418
|1790 <-> 902, 913
|1791 <-> 135
|1792 <-> 456, 1078, 1123, 1333, 1379, 1667
|1793 <-> 1057
|1794 <-> 1189, 1794
|1795 <-> 1689
|1796 <-> 1382, 1406, 1953
|1797 <-> 125, 1485, 1797
|1798 <-> 186, 1019, 1798
|1799 <-> 299, 831, 1240
|1800 <-> 494
|1801 <-> 1453
|1802 <-> 107, 1701
|1803 <-> 18, 412, 733, 1152
|1804 <-> 221
|1805 <-> 1195
|1806 <-> 6, 1650, 1684
|1807 <-> 1807
|1808 <-> 715, 938, 1985
|1809 <-> 754, 1440, 1698
|1810 <-> 388
|1811 <-> 165
|1812 <-> 1713
|1813 <-> 794, 811
|1814 <-> 192, 510, 1042, 1359
|1815 <-> 1941
|1816 <-> 382
|1817 <-> 166, 564, 937
|1818 <-> 21
|1819 <-> 111
|1820 <-> 562
|1821 <-> 572, 787, 1767
|1822 <-> 1589, 1627
|1823 <-> 343
|1824 <-> 945, 1161
|1825 <-> 90, 163, 438, 646, 914
|1826 <-> 1199, 1317, 1881
|1827 <-> 915, 1477
|1828 <-> 498, 1487
|1829 <-> 1646, 1745
|1830 <-> 883
|1831 <-> 1148, 1428, 1882
|1832 <-> 805, 1324
|1833 <-> 537, 1456
|1834 <-> 1312
|1835 <-> 774, 789, 1037
|1836 <-> 986, 1012
|1837 <-> 164, 1601
|1838 <-> 360
|1839 <-> 764
|1840 <-> 1209, 1888
|1841 <-> 1684
|1842 <-> 117, 1106, 1948
|1843 <-> 1020
|1844 <-> 835, 1890
|1845 <-> 1352, 1845
|1846 <-> 877, 977, 1878
|1847 <-> 828, 890
|1848 <-> 123, 1926
|1849 <-> 1849
|1850 <-> 8, 150
|1851 <-> 1059, 1672
|1852 <-> 1549, 1678
|1853 <-> 587, 1508
|1854 <-> 597, 1505, 1690
|1855 <-> 1855
|1856 <-> 885, 1049, 1378, 1575
|1857 <-> 202
|1858 <-> 355, 1491
|1859 <-> 1489
|1860 <-> 603, 855
|1861 <-> 1132
|1862 <-> 1260, 1512
|1863 <-> 390
|1864 <-> 1368
|1865 <-> 615
|1866 <-> 405, 1340, 1476
|1867 <-> 1064, 1705
|1868 <-> 1868
|1869 <-> 409, 1537
|1870 <-> 90
|1871 <-> 980, 1130, 1958
|1872 <-> 397, 574, 807
|1873 <-> 1771
|1874 <-> 91, 448, 1664
|1875 <-> 703, 850
|1876 <-> 793, 1162
|1877 <-> 1877
|1878 <-> 906, 1376, 1846, 1884
|1879 <-> 191
|1880 <-> 695
|1881 <-> 1826
|1882 <-> 372, 1831
|1883 <-> 1406
|1884 <-> 939, 1373, 1878
|1885 <-> 108
|1886 <-> 546, 600
|1887 <-> 58
|1888 <-> 202, 1235, 1840
|1889 <-> 1776
|1890 <-> 1844
|1891 <-> 1013, 1676
|1892 <-> 1892
|1893 <-> 614, 1893
|1894 <-> 430
|1895 <-> 1226
|1896 <-> 381, 1469, 1725
|1897 <-> 685, 1956
|1898 <-> 346
|1899 <-> 1246
|1900 <-> 1242
|1901 <-> 1901
|1902 <-> 374, 618
|1903 <-> 1163
|1904 <-> 1220
|1905 <-> 1149, 1457
|1906 <-> 316, 1453, 1521
|1907 <-> 269, 348
|1908 <-> 189, 1908
|1909 <-> 541, 637
|1910 <-> 1178, 1425, 1619, 1747
|1911 <-> 391, 768
|1912 <-> 632, 1237, 1518
|1913 <-> 1336
|1914 <-> 228, 335
|1915 <-> 1000, 1241
|1916 <-> 923
|1917 <-> 1974
|1918 <-> 88, 1267
|1919 <-> 667, 820, 1023, 1220, 1466
|1920 <-> 287, 491, 1191, 1484
|1921 <-> 422, 1743
|1922 <-> 1353, 1500
|1923 <-> 114, 314, 1030, 1192, 1742
|1924 <-> 1057
|1925 <-> 1024
|1926 <-> 1848
|1927 <-> 1028
|1928 <-> 262, 1289
|1929 <-> 1929
|1930 <-> 791, 1986
|1931 <-> 291, 1975
|1932 <-> 626, 1570, 1601
|1933 <-> 48, 1092
|1934 <-> 1934
|1935 <-> 514, 1760
|1936 <-> 1355
|1937 <-> 1192, 1463
|1938 <-> 260, 916, 1310
|1939 <-> 640
|1940 <-> 356
|1941 <-> 682, 1815
|1942 <-> 1231, 1244
|1943 <-> 762, 1308, 1413, 1776
|1944 <-> 1944
|1945 <-> 548, 636
|1946 <-> 257, 1120
|1947 <-> 140, 1420
|1948 <-> 1842
|1949 <-> 1033, 1653
|1950 <-> 1741, 1788
|1951 <-> 321, 659
|1952 <-> 1471
|1953 <-> 52, 1497, 1796
|1954 <-> 136
|1955 <-> 266, 1315, 1413, 1955
|1956 <-> 1518, 1897
|1957 <-> 600
|1958 <-> 726, 1871
|1959 <-> 1149
|1960 <-> 175, 947, 1502, 1707
|1961 <-> 1708
|1962 <-> 477
|1963 <-> 1064
|1964 <-> 904, 1369
|1965 <-> 1502
|1966 <-> 427, 814, 1966
|1967 <-> 411, 1166, 1380
|1968 <-> 1315
|1969 <-> 859, 1448, 1753
|1970 <-> 283, 1265
|1971 <-> 279
|1972 <-> 1185, 1544
|1973 <-> 1631
|1974 <-> 123, 1106, 1917
|1975 <-> 1157, 1931
|1976 <-> 307, 1188
|1977 <-> 82, 285, 595, 1643
|1978 <-> 412
|1979 <-> 944, 1298
|1980 <-> 354, 1189
|1981 <-> 452, 590, 1103, 1115
|1982 <-> 1175, 1396, 1748
|1983 <-> 874, 892
|1984 <-> 936, 1213
|1985 <-> 56, 972, 1102, 1430, 1808
|1986 <-> 561, 1930
|1987 <-> 1468, 1552
|1988 <-> 415, 758
|1989 <-> 311, 1640
|1990 <-> 852, 1511
|1991 <-> 804
|1992 <-> 824
|1993 <-> 1229
|1994 <-> 485, 942, 1522
|1995 <-> 156, 1255
|1996 <-> 1697
|1997 <-> 1413
|1998 <-> 1191
|1999 <-> 807, 1190
|""".stripMargin
val input = input2 + input1
}
|
parwen68/advent-of-code-2017
|
shared/src/main/scala/se/parwen/adoc/day1/Solver.scala
|
<filename>shared/src/main/scala/se/parwen/adoc/day1/Solver.scala<gh_stars>0
package se.parwen.adoc.day1
object Solver {
def solveStep1(input: String) = {
val pairs = input.zip(input.drop(input.length / 2) + input.take(input.length / 2))
pairs.foldLeft(0)((acc, v) => if(v._1 == v._2) acc + (v._1 - '0') else acc)
}
def solveStep2(input: String) = {
val pairs = input.zip(input.drop(input.length / 2) + input.take(input.length / 2))
pairs.foldLeft(0)((acc, v) => if(v._1 == v._2) acc + (v._1 - '0') else acc)
}
}
trait Solver1 {
def solve1(): Unit = {
println("Day 1:")
val result1 = Solver.solveStep1(Input.input)
println(s"step 1 result is $result1")
val result2 = Solver.solveStep2(Input.input)
println(s"step 2 result is $result2")
}
}
object Main extends Solver1 {
def main(args: Array[String]): Unit = {
solve1()
}
}
|
parwen68/advent-of-code-2017
|
shared/src/test/scala/se/parwen/adoc/day9/SolverSpec.scala
|
package se.parwen.adoc.day9
import org.scalatest.{FlatSpec, Matchers}
class SolverSpec extends FlatSpec with Matchers {
"The solvers step1" should "return 0 fo <>" in {
import Solver._
val r = solveStep1("<>")
r should be (0)
}
"The solvers step1" should "return 1 for {}" in {
import Solver._
val r = solveStep1("{}")
r should be (1)
}
"The solvers step1" should "return 6 for {{{}}}" in {
import Solver._
val r = solveStep1("{{{}}}")
r should be (6)
}
"The solvers step1" should "return 5 for {{},{}}" in {
import Solver._
val r = solveStep1("{{},{}}")
r should be (5)
}
"The solvers step1" should "return 16 for {{{},{},{{}}}}" in {
import Solver._
val r = solveStep1("{{{},{},{{}}}}")
r should be (16)
}
"The solvers step1" should "return 1 for {<a>,<a>,<a>,<a>}" in {
import Solver._
val r = solveStep1("{<a>,<a>,<a>,<a>}")
r should be (1)
}
"The solvers step1" should "return 9 for {{<ab>},{<ab>},{<ab>},{<ab>}}" in {
import Solver._
val r = solveStep1("{{<ab>},{<ab>},{<ab>},{<ab>}}")
r should be (9)
}
"The solvers step1" should "return 9 for {{<!!>},{<!!>},{<!!>},{<!!>}}" in {
import Solver._
val r = solveStep1("{{<!!>},{<!!>},{<!!>},{<!!>}}")
r should be (9)
}
"The solvers step1" should "return 3 for {{<a!>},{<a!>},{<a!>},{<ab>}}" in {
import Solver._
val r = solveStep1("{{<a!>},{<a!>},{<a!>},{<ab>}}")
r should be (3)
}
"The solvers step1" should "return 0 for <>" in {
import Solver._
val r = solveStep1("<>")
r should be (0)
}
"The solvers step2" should "return 0 for <>" in {
import Solver._
val r = solveStep2("<>")
r should be (0)
}
"The solvers step2" should "return 17 for <random characters>" in {
import Solver._
val r = solveStep2("<random characters>")
r should be (17)
}
"The solvers step2" should "return 3 for <<<<>" in {
import Solver._
val r = solveStep2("<<<<>")
r should be (3)
}
"The solvers step2" should "return 2 for <{!>}>" in {
import Solver._
val r = solveStep2("<{!>}>")
r should be (2)
}
"The solvers step2" should "return 0 for <!!>" in {
import Solver._
val r = solveStep2("<!!>")
r should be (0)
}
"The solvers step2" should "return 0 for <!!!>>" in {
import Solver._
val r = solveStep2("<!!!>>")
r should be (0)
}
"The solvers step2" should "return 10 for <{o\"i!a,<{i<a>" in {
import Solver._
val r = solveStep2("<{o\"i!a,<{i<a>")
r should be (10)
}
}
|
parwen68/advent-of-code-2017
|
shared/src/test/scala/se/parwen/adoc/day7/SolverSpec.scala
|
package se.parwen.adoc.day7
import org.scalatest.{FlatSpec, Matchers}
class SolverSpec extends FlatSpec with Matchers {
"The solver" should "return tknk" in {
import Solver._
val r = solveStep1("""pbga (66)
|xhth (57)
|ebii (61)
|havc (66)
|ktlj (57)
|fwft (72) -> ktlj, cntj, xhth
|qoyq (66)
|padx (45) -> pbga, havc, qoyq
|tknk (41) -> ugml, padx, fwft
|jptl (61)
|ugml (68) -> gyxo, ebii, jptl
|gyxo (61)
|cntj (57)""".stripMargin)
r should be (List("tknk"))
}
/*
"The Solver" should "return stuff" in {
import Solver._
solveStep2("""pbga (66)
|xhth (57)
|ebii (61)
|havc (66)
|ktlj (57)
|fwft (72) -> ktlj, cntj, xhth
|qoyq (66)
|padx (45) -> pbga, havc, qoyq
|tknk (41) -> ugml, padx, fwft
|jptl (61)
|ugml (68) -> gyxo, ebii, jptl
|gyxo (61)
|cntj (57)""".stripMargin)
}
*/
}
|
parwen68/advent-of-code-2017
|
shared/src/main/scala/se/parwen/adoc/day7/Input.scala
|
<gh_stars>0
package se.parwen.adoc.day7
object Input {
val input = """cfkcj (74)
|kmwhbm (32)
|uuvdgc (58)
|siyms (98)
|jgtvhkv (1885) -> ykqcpiv, gvupyd, vuyxvq
|ppdypq (86)
|lovxjut (90) -> fmvna, ddneaes, sakwdmk, lqmoz
|ijnvdm (98)
|ibzlhq (86)
|pabuo (81)
|brexb (75) -> tbmiv, iwrph
|uqiwwa (705) -> inriw, rnelci
|psyroai (498) -> porhb, qinqu, esxiq
|ldkxt (69)
|mzfbeo (68)
|spjtt (299) -> xfcxpkh, sizgye
|dnjao (243)
|rqwnb (9)
|jfnfq (94)
|giuonbb (68)
|gbywwf (103) -> ugskjw, gelpv
|fldjrj (52)
|vuxzudl (31)
|ewnboyh (38)
|bolsi (11)
|gbziz (33)
|ytkppl (95)
|rahuwnt (86)
|toprb (282) -> dzyvcxt, xlyngh, tkhbr, avufn, uhhiz, tmtqgn
|jadnvpr (13)
|rnsotgi (47)
|ovcgnvp (309) -> zlffm, iqwjlgh
|xpbro (69)
|tjulok (12)
|pvylfqc (199) -> pzybx, nbdewmj
|smwdyt (22)
|oozzs (55) -> vrqgow, iynmj
|qmzcp (89)
|ssneqxd (22)
|fqhdfwi (1041) -> ytjhh, rqpbxi, uvprg
|bgsbjcq (81)
|ilmvjcn (7)
|adnrrap (69)
|tspxgun (48)
|tbmiv (77)
|tceqj (58)
|nlptf (157) -> vpvgnt, memsb, mcsoi, ctnckd
|yzaveth (320) -> frfkpn, viockjp, cqzvhh
|dgwely (74)
|dpjpifo (47)
|lncbnc (238) -> bmiqc, uvnmx
|ppgvqkj (48)
|fdbsgs (31)
|usjpp (55) -> cxhms, niixavl, bspsg, htwyil, pyavtyz
|ovhxqx (53)
|vzyut (17)
|pvxvvv (52)
|gkouyvq (73)
|ugjmo (86)
|mblsyx (51158) -> vqpzey, bavhyuz, fqwyfso
|vyrwv (99)
|gdjawl (10)
|vxcjbsi (56)
|tiedml (44)
|ihxixk (61) -> pduyk, betaiu
|pvthg (41)
|gehqj (77)
|luxlkxu (1170) -> bzlttq, rowhly, nlptf
|irckle (65) -> kuvzyp, nkotu, uqfiwz
|fjwfhq (73)
|drzukuh (55)
|pzyxbdy (81)
|brxrm (51)
|dirdh (56)
|ovujcr (13)
|usfiw (7750) -> dtvjn, jektxhw, sfmvh
|ytjhh (219) -> jcooqy, gvuvmfz
|umnhed (1311) -> lefse, brexb, bexmjvo
|vzvwks (52)
|ydzdome (10)
|iekhet (68)
|jcooqy (5)
|pcvok (38)
|gqmqt (675) -> udebyn, agifkpl, gogsic
|gkyvjtj (69)
|uhhiz (88) -> bojcjr, krhtjha
|jenzlcn (96)
|mjntxj (48) -> mdhduoi, aztaw, tfkse
|xgelkov (12)
|rpadzt (24)
|uoewbgw (54)
|hmroizo (1564) -> hyjba, qetylot
|qinqu (78) -> pabuo, bgsbjcq
|cuikvge (150) -> vuxzudl, fdbsgs
|jqjyspz (91)
|dcaot (27) -> dnjao, bwbufij, mlzxc, auawgd, laxqy, awzuv, pvylfqc
|yheomy (69)
|kvspfv (81)
|uoxqwap (161)
|nfefd (82)
|wfgammo (97)
|mifrxb (158)
|ihvae (5)
|xfcxpkh (12)
|pjegzrx (63) -> pgigk, zijedtv, ghdgob
|xrxabjj (45)
|fqmjnw (58)
|pjgwz (99)
|uxzazjg (64)
|seeqovh (25)
|eyxbeon (35)
|umdhwh (27)
|sesui (38)
|nhnwqgh (59)
|bnnfxqe (12)
|blivyc (55)
|ilrkhhd (84)
|kzdxtck (37)
|gfsmrr (172) -> xkuubv, eyxbeon
|atwwiy (67)
|rnelci (99)
|hxlve (68)
|pkwfv (32)
|jnack (61)
|pqqxhy (235) -> xsiklw, hmpcc
|wcehmi (167) -> ygukv, upllk, kkdvdz, dqaum, synets
|onwpfb (77)
|zledwkk (7)
|mjaqsj (78)
|qsoybe (67)
|eidhz (91)
|blnsa (68) -> hftkbw, snllz, ddfnw, gefhbss
|cswrj (176) -> laydujd, hpdegx
|jtwckf (71)
|lleyk (243) -> nyfnss, veujpah
|synets (89) -> uuvdgc, vxqvj
|swqrnfi (500) -> ivohs, zzqwyx, sxuafke
|oyxlg (11)
|zuruj (5)
|loaex (63) -> jtwckf, enxsaag
|mviybt (27)
|qrxvlk (369) -> bpbfd, gdbapcx
|yagjnwy (78)
|ftlrjo (91)
|zklwp (56555) -> kaursj, lahahn, ciwjgw
|dehbyec (51)
|udoabw (123) -> ewgjf, icdyrl
|bojcjr (34)
|dwmkyes (119) -> schbl, finmnfn, iiropvx
|plhno (14)
|bsfpjtc (42) -> zklwp, zoibnsq, mblsyx, vkkwtq, cwluofv
|thfdorc (48) -> ieuus, resill, agiybx, lleyk, mqruxqs
|hupbun (52)
|nyfnss (14)
|nkhiz (51)
|gicaag (50)
|kgsyd (92) -> pzyxbdy, uozna, bcxexao, kvspfv
|fuopub (65) -> vqijdaj, mzfbeo
|wekwg (51)
|vuyxvq (55) -> rsaruxl, blukof
|awzuv (133) -> kxbjrca, drzukuh
|onrbqjg (314) -> qulqh, wekwg
|gefhbss (171) -> rhfpsr, oziwk
|gkcpihl (88)
|nwbomv (87)
|betaiu (82)
|wuhui (66)
|ocopf (53)
|jjceeu (65)
|gurmk (64)
|ymrkr (77)
|grupgc (24)
|ucqgh (75)
|ujdishy (60)
|mrwgq (85)
|buvuq (3294) -> usjpp, swqrnfi, oqdntf
|cqzvhh (9)
|ikhbgx (54)
|ddfnw (77) -> blhurw, qdeybxh, dehbyec, hkhvjq
|xnfjw (17)
|nfrbj (25)
|zdrbia (250) -> dpjpifo, rnsotgi
|wkennss (43) -> xcobqnc, lpogx, jjceeu
|njlyt (65)
|thnxnda (66)
|xkdua (12)
|frfkpn (9)
|uwlpeon (30)
|gwuxmq (89) -> rladyxh, mjaqsj, ozkrca
|lnxtx (91)
|djpkm (75)
|gbnmi (21) -> mviybt, umdhwh, nswhn
|nswhn (27)
|kkktvk (32)
|rgzkfeq (275)
|hcywt (26)
|hbjiz (129) -> ldkxt, tvshylj
|fkzwy (16)
|aztaw (10) -> yfrcezm, kqglah, ytkppl, puxzdr
|ocztn (95)
|jbsdgwa (34)
|fqwyfso (34) -> vuqlmx, hmroizo, fqhdfwi, ksvwst, hihvghh, dcaot
|urnycch (8)
|uyhqy (23)
|resill (127) -> uvptuv, luzuu
|udebyn (181)
|qetylot (82)
|hdjgig (51)
|jntmriy (90)
|rfvtvw (46)
|lsfjnsb (186) -> azmknz, qrriz
|vnantj (71) -> avxjqab, oxjor, dattu, nwbomv
|epxtul (12) -> aiyvkt, yhmavn
|ysqwf (161) -> mxumuj, zbjhd
|jieqymv (77)
|rqqirx (91)
|xoqqhw (346) -> uigna, qfequa
|qdrbdcf (59)
|uufted (217) -> megix, vewew, ovujcr
|frkzri (15)
|ddjyphd (66)
|modlepu (59)
|ynbhq (17)
|jsdqcw (7)
|dpevfm (7)
|tqmkur (63)
|bzhnu (150) -> qcpdn, ymjhqjw
|sbaeoqo (58)
|vtprv (39)
|cshts (7)
|tlitf (70)
|ynodbxy (58)
|arfft (259) -> eebqhug, jggld
|rxrayit (22)
|vdymnhw (37)
|uvptuv (72)
|fjueeps (17)
|tollmm (100) -> qjipfjv, glbhpwz, pkfyhk
|emwqaz (5)
|unehvbu (147) -> tjulok, fwapzg
|wlqagku (34)
|unikoz (47)
|vizehnk (97)
|lnotuxj (198) -> feyiw, vrcfi
|tkneufh (51)
|usfag (80)
|lgwut (308) -> ohdwce, uoewbgw
|hfpcxco (85)
|qddkwld (233) -> fnzboe, lbrknfc, plhno
|ksvwst (1053) -> gzwkbw, ihxixk, vxzowjy
|camosg (85)
|onbizml (64)
|rrlifdx (21)
|pzybx (22)
|mhbhg (50)
|upksvnf (8)
|utxkvw (52)
|mmhjhh (20)
|gjqcj (64)
|xljdooj (37)
|aejrdpp (201) -> zopkd, beoww
|fiutgke (17)
|qnmuc (202) -> mmhjhh, sfyps
|aqjrxbd (40) -> mrwgq, hfpcxco, kozlucm
|imtxkez (94) -> cwthmnc, mzvyddo, rmvgczw, jgtvhkv, hejlvq, ihxivjd
|daaexz (199)
|ghdgob (86)
|owqupte (43) -> vkuvc, ucwwc
|eztix (16)
|pudsuxc (20)
|vlwnw (90)
|nlotooe (89) -> azzfba, ghbfbn, ppdypq
|xqdpgzt (66)
|hzain (46)
|tfjzhz (88) -> mhpsnlv, kpjzc
|gihhi (20)
|gvuvmfz (5)
|hmpcc (38)
|lotngsa (12)
|rupou (1090) -> tcgqf, onbizml
|xxjcew (40)
|yxfyvw (26) -> nlotooe, kqcmyr, yzaveth, fsqkr, kryid
|xlyngh (132) -> qznfyv, lotngsa
|rjbaqwb (25)
|ibhzmtf (10)
|kqglah (95)
|hwmegb (845) -> xmlzuy, nehvflm, rnpwyut
|sfhrl (240)
|fbxcht (284)
|xmlzuy (90) -> tspxgun, ppgvqkj
|npsgry (85) -> pdttnl, aqzkz, negvvn, blivyc
|kxbjrca (55)
|jrtqzng (12)
|tcgqf (64)
|rcmogxy (169) -> xbxnqfz, lkipow
|gvfgvtd (124) -> vdymnhw, twyuae, fjhgrk
|brzgxi (588) -> untbk, nawhukx, pelersw
|cxfgjp (57)
|xxqaj (250) -> irsxut, hmdmy
|tldocc (42)
|icdcn (73)
|jtmhpm (44) -> cynginx, pjgwz
|tdtiqm (135) -> hymwone, oejnh
|qybpba (125) -> elknfln, ctmtk
|sozke (24)
|uvnmx (9)
|hcovonm (56)
|yzpxkx (62)
|jyfkl (89)
|kdhmnh (27) -> uljmqrb, ynxvst
|dajvk (245) -> abjhq, qkdikgs
|rwvvlbx (69) -> zligfrr, ttmotv
|skrlqr (217) -> ibhzmtf, xodpco
|ugpaod (27)
|gxtabbr (85)
|ipqome (26)
|dattu (87)
|zxozizh (96)
|hgtwnxu (12) -> mtkquru, qdzefux, wccvu, qrnztia, etblz
|zlkaugz (7) -> uyxisy, faifx, njiof, prkspdn, lovxjut, fatahc, kxxqxm
|auawgd (153) -> vnuwn, hugzzwo
|ehynzhf (99)
|kvrbtlv (1024) -> wkennss, lnotuxj, wbzccs, hlijr, gkvdu
|xyvst (196) -> upksvnf, rvdntii
|okzaj (208) -> rgyofuq, bdzqyu
|rsvtgxk (32)
|thzgmn (33)
|fxjooi (12)
|extfuy (291) -> tnvblm, ljxeb
|hazdl (58)
|zisnz (66)
|ukxuw (66)
|mllmqhl (90)
|hihvghh (48) -> kbyhru, xkyjdv, okzaj, dsqvto, sfhrl, trjerm, ocatfcc
|xodpco (10)
|fkqlr (94)
|anhrt (14) -> jntmriy, mllmqhl, rmdui, tuorl
|mytpi (432) -> inthrl, ffcivin, auijtpl
|zvctpo (45)
|ttmotv (84)
|hftkbw (281)
|zijedtv (86)
|sksjqz (277) -> zghku, skykdl
|vpvgnt (10)
|odqxcfl (93)
|qfequa (14)
|tnvblm (7)
|gkfxnzo (17)
|pkfyhk (58)
|kuypvuy (67)
|uhavg (1034) -> aqjrxbd, aafpdpe, eoluf, opbjmvf
|acxrgal (287) -> jholt, rqwnb
|scengkj (97)
|taausp (47)
|rxfnzf (18)
|uljmqrb (67)
|zbvvekj (67)
|zwzhv (270) -> yxpzp, pzwxz
|gelpv (17)
|kunxx (67)
|etblz (273) -> dpevfm, kojrycd, lhbuca, jsdqcw
|xqfwvbf (20)
|ghiqkm (192) -> onwpfb, amqvafo
|mfdhdz (99)
|fdztdbr (1063) -> sqzdg, hlcre, uyiaqu, usttmag
|opnqtf (10)
|fsqkr (165) -> jggsgh, xwtls
|qrriz (35)
|dtvjn (1287) -> gvfgvtd, khajtz, hkyiv
|xsyepmg (35) -> camosg, gxtabbr
|khykj (37) -> jfnfq, fkqlr
|pduyk (82)
|aqzkz (55)
|merswry (32)
|wevnd (64)
|blukof (37)
|fzhncm (327) -> qybpba, pwtlh, gbywwf, ymbtxzb, dwmkyes
|nbdewmj (22)
|hmdmy (13)
|slnbq (78)
|ozkrca (78)
|vnoztu (96)
|eksshr (914) -> chcsjda, udoabw, fuopub
|fnzboe (14)
|irsxut (13)
|qvyqnuk (132) -> wfmql, rxrayit
|ewgjf (39)
|kdcgzbw (75)
|bbytzn (1597) -> lqwwuqk, shypdye, javnv
|ljxeb (7)
|vkuvc (78)
|kbyhru (58) -> eidhz, lnxtx
|cigbnvp (37)
|nubyqxj (56)
|mtlapd (73) -> veeinqe, nlbnj, jadnvpr
|feiowiw (1956) -> zcibgd, chpsgen, slimx
|pdfjuw (71) -> fllyd, ghdqy, vzcvxt, keesuec
|vrcfi (20)
|jggld (83)
|wrsdsa (7)
|kmzeahn (178) -> gkfxnzo, fiutgke
|elknfln (6)
|kxbclr (30)
|wrrwam (180) -> scengkj, vizehnk
|hlfgoa (111) -> wfgammo, rolegtf
|uyxisy (566) -> vgicm, mnpow, urnnskw, rcmogxy
|brtvs (188) -> ftumhcp, xkdua
|jvyscs (126) -> smwdyt, ttegw
|jwenagh (25)
|hlijr (238)
|zghku (22)
|ykqcpiv (129)
|dpmsnm (971) -> mifrxb, fdpsrru, mqvstxt, rxarqvt, vbypq
|vgicm (113) -> rvwtrl, mhbhg
|izjxyb (37)
|bfanbgh (128) -> arfft, xfvfo, nitrl
|hkykap (26)
|cpbxfaf (11)
|wrbqnx (39)
|pwtlh (63) -> izjxyb, kzdxtck
|tfpqwb (48)
|htkhsaa (74)
|fvdsi (40)
|iwexk (50)
|mtkquru (70) -> mdcnazp, ymrkr, gehqj
|pxbjhvu (96) -> nubyqxj, bvxxoux, hcovonm, wxjuvo
|jeopi (71)
|oqdntf (335) -> ocwyg, afdox, axcgjhj
|bveca (138)
|bexmjvo (99) -> njlyt, uxupys
|xteuk (74)
|upllk (131) -> cigbnvp, pewlflc
|lahahn (2750) -> bbytzn, fzvctf, utnrb
|ycpff (564) -> qgyngw, hwhleil, obumrhe, rgzkfeq, qddkwld, nykzm
|usttmag (266)
|axcgjhj (291) -> ddroz, ilmvjcn
|tdmpe (77) -> buxlsok, ufense, klkyckz
|kchcxe (96)
|fkksmck (11)
|fzvctf (85) -> xgydg, hgyhzc, pqqxhy, qadkf, nsxfciq, gbuhi
|mqwdr (2656) -> kvrbtlv, uhavg, tsndvs, ycpff, yadfos
|pulsq (84)
|giugg (141) -> fieeic, uocco, msjyqjc, xrvdagj
|dgdeleb (35)
|qyixlaf (25)
|wrbrkm (193) -> hdjgig, brxrm, nkhiz
|ddpua (95) -> fspnagx, tqmkur, xwfnl
|eoluf (39) -> gjqcj, uxzazjg, wevnd, laepzgh
|kgfeyyg (45)
|ovqpta (602) -> hbjiz, wbrop, ihyawsa
|kqkyaey (25)
|uigna (14)
|qulqh (51)
|kdwsl (96)
|fkurfvl (15)
|auijtpl (44) -> kdtiuq, ijnvdm
|wzdgidb (10270) -> xqqgyu, osydb, mytpi
|ihyawsa (77) -> ocztn, eiacrfj
|bmiqc (9)
|urnnskw (5) -> zdsag, pntxt, hupbun, utxkvw
|gbhssic (63) -> smguzlg, mfkfr
|enxsaag (71)
|ysuhs (82)
|lxnqzpf (63)
|mjwsaam (311) -> rxfnzf, qxgwwc, flxoy
|ghbfbn (86)
|iyhde (95)
|clqri (96)
|eoyji (17)
|ciwjgw (95) -> fdztdbr, miymv, qwmvf, mzzmpgt
|motddh (44) -> ilmqyc, nmfdw
|glbhpwz (58)
|lpuutn (161) -> mruemdv, chlofj
|pcvfnve (58) -> ssneqxd, arizdt
|ucefyhu (53)
|hymwone (55)
|peoneex (89)
|mzzmpgt (1159) -> qnmuc, jtmhpm, gxrmso, gfsmrr
|mpesve (308) -> ipbhoko, ddivge, ihvae
|zwfoos (8)
|pewlflc (37)
|qxgwwc (18)
|kjibzax (32) -> aejrdpp, qgaohbj, oozzs, tdtiqm
|agifkpl (75) -> ucefyhu, jfccr
|tkhbr (104) -> ipqome, ohwwaa
|wcqwomp (34)
|vvxmua (54)
|zbcwm (124) -> dlsayg, wuhui
|avrjyy (25)
|hwhleil (86) -> lxnqzpf, nhgdduv, tpxrpfd
|eiacrfj (95)
|vdoqb (94)
|paokema (52)
|mhoofw (95)
|diovwj (29) -> hwmegb, bfanbgh, tawdmir, ovqpta, thfdorc
|inuxln (11)
|snllz (103) -> ykztsh, qmzcp
|kuvzyp (29)
|ocdsfd (59)
|qxwsk (320) -> kmwhbm, rsvtgxk, jkqnf
|rmvgczw (1744) -> nuqlt, qvyqnuk, ttdeu
|fdpsrru (24) -> ntzgern, kuypvuy
|kdgcv (96)
|iiropvx (6)
|uocco (45)
|prkspdn (380) -> lnpng, ghiqkm, wrbrkm
|txmua (78) -> zisnz, xqdpgzt, ddjyphd
|yswzfg (73)
|biydd (170) -> modlepu, ocdsfd
|clkduv (60)
|zligfrr (84)
|mdcnazp (77)
|cwluofv (52565) -> feiowiw, zlkaugz, smamg
|bavhyuz (7693) -> ijibo, ncpzhu, uqiwwa
|zscii (59)
|wtfjqnx (24)
|ucorqrv (122) -> didkxzb, gozty, ezimk
|yxpzp (73)
|lqmoz (232) -> qyixlaf, jwenagh, nfrbj, twsvvzh
|wqcpszg (99)
|yyqvf (220) -> irjtkb, mzsoo, rjbaqwb, mxigb
|dbtzr (34)
|lshcpil (52)
|bcxexao (81)
|osydb (930) -> htkhsaa, cfkcj, xteuk
|zskvah (84)
|rvwaido (283) -> oyxlg, uhbka
|wfoili (18)
|ptzanxy (113) -> uymxxd, vxcjbsi
|arizdt (22)
|bbupp (71)
|kkdvdz (97) -> baqqex, ikhbgx
|jniuewa (39)
|mdhduoi (262) -> zfnxo, mxaoa, zfrzbb, kkktvk
|tmtqgn (108) -> eztix, gufoi, fkzwy
|rsnptie (198) -> lausf, pcvok
|htwyil (133) -> ocopf, eddcns
|ttegw (22)
|ayloijg (188) -> pkwfv, merswry, klrrpn
|bylpn (93)
|jektxhw (456) -> lsfjnsb, cryxpp, ffvtymw, lncbnc, zbcwm, uufted
|hlcre (59) -> efszdn, adnrrap, koacic
|rvwtrl (50)
|lhbuca (7)
|xgydg (163) -> jgvzkp, dgwely
|ddivge (5)
|xkqsn (29) -> umdspul, japznn
|irjtkb (25)
|bfhoskf (69)
|ttdeu (88) -> hpovffo, ulzbyy
|utnrb (538) -> jmrywkk, skrlqr, gbhssic, bxbaua, rwvvlbx, fftxfs
|hkyiv (45) -> iyhde, mhoofw
|itfjcv (85)
|xfvfo (41) -> clqri, fdvpljm, kdgcv, kdwsl
|jkqnf (32)
|esxiq (174) -> gbziz, thzgmn
|nazoxxl (61)
|gkvdu (138) -> gicaag, iwexk
|hejlvq (346) -> sksjqz, lnrnk, pjegzrx, ovcgnvp, zjiaam, giugg
|azzfba (86)
|kosdbim (21)
|bjfmsgp (81)
|cyizx (90) -> kiflapm, fjbvj
|viockjp (9)
|nsxfciq (215) -> wfekn, cdnagg
|cxhms (103) -> iekhet, ljcnfds
|nmfdw (47)
|mxumuj (12)
|tawdmir (32) -> gnamu, ppptkjy, qnsnqy
|uhbka (11)
|vxzowjy (9) -> gfrqgpm, vfsdg, ltfanj, vvxmua
|rvdntii (8)
|xoseld (44)
|zjiaam (185) -> dbtzr, ortdyy, jbsdgwa, dtqejc
|qffvjvy (20)
|nhgdduv (63)
|ddroz (7)
|rghhbxs (58)
|mhzvara (240) -> rrizdbi, ebjqfgp, zvdii, vrfkca
|vnuwn (45)
|cdnagg (48)
|xbypzyz (354) -> wdvmq, bcqcl, biydd
|flxoy (18)
|miymv (47) -> qxwsk, onrbqjg, lgwut, zwzhv, kgsyd
|onbize (62) -> djpkm, ucqgh
|ymjhqjw (31)
|zcibgd (41) -> wrrwam, xoqqhw, izcxju, vqtknqo, anhrt, cswrj, blfzhbb
|rgyofuq (16)
|zbuar (48)
|amsxxe (220) -> plzvkk, ugpaod
|blfzhbb (254) -> clkduv, ujdishy
|vilcpj (17)
|smguzlg (87)
|qwmvf (870) -> vxzqqkt, vnantj, qrxvlk
|ygqyizj (17)
|aafpdpe (94) -> nbxepbg, atwwiy, pwzfoy
|ykztsh (89)
|bfrlxk (99)
|iabco (207) -> fqmjnw, tqjoo
|bktiekj (78)
|kwkcos (62)
|jggsgh (91)
|xrvdagj (45)
|bspsg (188) -> vzyut, fjueeps, vilcpj
|dqaum (33) -> ugjmo, nhpvc
|eujhcc (68)
|tqfnnek (60) -> gwuxmq, spjtt, rysldfw, aqdba, mpesve, iabco
|efszdn (69)
|uqzisq (10150) -> emqcvc, blnsa, wcehmi
|nynxxb (112)
|bkpka (85)
|sizgye (12)
|wgtdln (35)
|yzdou (21)
|ortdyy (34)
|gogsic (67) -> dfzlxba, gmrktc
|fspnagx (63)
|laxqy (45) -> nuoxnzw, ehynzhf
|sfmvh (72) -> jeylva, uicohi, pxbjhvu, mhzvara, irmjpg, yyqvf
|hlctdjw (53)
|ynxvst (67)
|aiyvkt (70)
|rsaruxl (37)
|mruemdv (14)
|riqqep (21)
|mnpow (162) -> eoyji, ayslth, ygqyizj
|iclynp (706) -> pcvfnve, gbnmi, cyizx
|tsndvs (79) -> rvwaido, npsgry, hlfgoa, criaedy, hohun, extfuy, acxrgal
|gmyydys (69)
|xbxnqfz (22)
|ujudb (77)
|vqpzey (1876) -> mjntxj, rupou, xbypzyz, brzgxi, toprb, gqmqt, psyroai
|ivlxyu (68)
|jeylva (148) -> ibzlhq, rahuwnt
|xpormy (97)
|zlffm (6)
|ulzbyy (44)
|trjerm (156) -> yzdou, riqqep, rrlifdx, kosdbim
|wbzccs (70) -> pulsq, zskvah
|xwfnl (63)
|nbxepbg (67)
|fatahc (851) -> lpuutn, aemnj, fpbxkb
|dzyvcxt (142) -> wrsdsa, zledwkk
|asafmi (51)
|puxzdr (95)
|skykdl (22)
|avxjqab (87)
|rowhly (47) -> kdcgzbw, fpzba
|lqwwuqk (118)
|rqpbxi (145) -> kmpdpy, kimfdue
|ffcivin (170) -> tlzng, fwfbtcw
|zoibnsq (8) -> wzdgidb, imtxkez, uqzisq, mqwdr, vcezyqj, usfiw
|xsiklw (38)
|ucwwc (78)
|opbjmvf (63) -> dbkzlc, sbaeoqo, hazdl, rghhbxs
|luzuu (72)
|dbkzlc (58)
|jgvzkp (74)
|kryid (199) -> tenjus, gocurcy
|hdahal (81)
|fjbvj (6)
|ajjyqz (14)
|fftxfs (155) -> wqljugh, sjlwjcc
|vkkwtq (61232) -> buvuq, diovwj, decklvy
|xqqgyu (16) -> fbxcht, uyxpx, ddpua, ayloijg
|hohun (305)
|cwthmnc (82) -> wmciqdi, tdmpe, wiqjl, gnmudrh, mjwsaam, fgqxuig
|veeinqe (13)
|gocurcy (74)
|uxupys (65)
|qjipfjv (58)
|wgarj (35)
|mceul (202) -> wtfjqnx, rpadzt, grupgc
|ohwwaa (26)
|fieeic (45)
|urawf (88)
|fjhgrk (37)
|axjaxn (78)
|gunuriu (73)
|uetcsjx (52)
|bwbufij (35) -> lshcpil, vzvwks, paokema, uetcsjx
|ppptkjy (97) -> vlwnw, ivksd, etzocl, akvov
|agiybx (257) -> dmyxvek, cshts
|oziwk (55)
|yvedw (88)
|gjlsrq (84)
|nehvflm (98) -> bhezu, plcqz
|rlvxk (53)
|eiysj (69)
|cynginx (99)
|lefse (51) -> jyfkl, peoneex
|qfabag (12)
|ffvtymw (204) -> hcywt, ttvyvv
|ayslth (17)
|rladyxh (78)
|rnpwyut (170) -> zwfoos, urnycch
|mxaoa (32)
|ufense (96)
|atfrn (35)
|qrmkrs (94)
|javnv (48) -> atfrn, wgarj
|inthrl (80) -> usfag, usvvacs
|ljcnfds (68)
|rmdui (90)
|njiof (743) -> zhqnj, ptzanxy, khykj
|zqqxw (17)
|zbjhd (12)
|kimfdue (42)
|vqtknqo (192) -> jqjyspz, dkxedzu
|gmrktc (57)
|lbroca (46)
|kdtiuq (98)
|hkhvjq (51)
|ohdwce (54)
|deusrct (41)
|urljsxt (64)
|mjesxf (74) -> zbuar, tfpqwb
|qdeybxh (51)
|kxxqxm (1330) -> xoseld, xpxbgh
|ivohs (91) -> hlctdjw, rlvxk, ovhxqx
|izcxju (176) -> ybwjsz, bfrlxk
|hdwpha (62)
|lnrnk (321)
|vybrd (42)
|kiflapm (6)
|icdyrl (39)
|fpbxkb (53) -> hxlve, ivlxyu
|qnsnqy (310) -> gddaubt, rnnmuk, kjauj
|zazlcg (68) -> nkgayde, eiysj, yheomy, xpbro
|inriw (99)
|jpsejb (26)
|gufoi (16)
|uicohi (296) -> frqiho, bnnfxqe
|rxarqvt (58) -> avrjyy, seeqovh, gmdwhcy, kqkyaey
|yadfos (1659) -> ysqwf, zkfwc, bqusn
|gozty (13)
|ocatfcc (240)
|vzcvxt (54)
|xochi (195) -> xdohu, lbroca
|lddqu (20)
|dmyxvek (7)
|didkxzb (13)
|hpdegx (99)
|tlbakdh (7) -> vnoztu, lkozg
|vvsgr (332) -> pulpbaj, mjesxf, jvyscs, pctst
|avufn (28) -> urljsxt, gurmk
|faifx (1004) -> rpywck, bveca, motddh
|chlofj (14)
|zygpcpd (39)
|msjyqjc (45)
|dhdhlmq (1181) -> jelwm, mtlapd, nynxxb
|knczsg (51)
|tenjus (74)
|ocwyg (217) -> cjgtcao, tiedml
|zzqwyx (62) -> vdoqb, qrmkrs
|zdsag (52)
|rysldfw (26) -> vyrwv, wqcpszg, mfdhdz
|vfsdg (54)
|pgigk (86)
|tytufo (67)
|bqusn (15) -> itfjcv, bkpka
|gmdwhcy (25)
|wqgini (563) -> xochi, xdfyw, pdfjuw, ujtmmb, dajvk
|iynmj (95)
|umdspul (71)
|qcpdn (31)
|gddaubt (49)
|colwnyd (141) -> fkurfvl, frkzri
|nuqlt (64) -> rfzyvg, dirdh
|qgaohbj (81) -> nfefd, ysuhs
|sxuafke (250)
|efvcgxy (51)
|kmpdpy (42)
|finmnfn (6)
|ohcob (901) -> rggrduc, fbnmdsm, xljdooj
|bxbaua (63) -> ynodbxy, tceqj, necuat
|lkozg (96)
|yzahca (62)
|vbypq (88) -> dgdeleb, wgtdln
|lkipow (22)
|mqruxqs (135) -> eujhcc, giuonbb
|nitrl (425)
|lnpng (70) -> pkhkeva, lzdzs, bfhoskf, vcdrqps
|nhuuo (70)
|nkvxvrf (12)
|beoww (22)
|atnshbm (58) -> taausp, unikoz
|ftumhcp (12)
|kojrycd (7)
|lyoaqtx (184) -> gbkfxbj, xxqaj, txmua
|ojwlkyk (23)
|untbk (28) -> rqqirx, ftlrjo
|bcqcl (278) -> emwqaz, zuruj
|tpxrpfd (63)
|vxqvj (58)
|zfnxo (32)
|klrrpn (32)
|mlzxc (51) -> qxqzzw, zxozizh
|porhb (240)
|pelersw (70) -> nhuuo, tlitf
|fpzba (75)
|qgyngw (121) -> jieqymv, ujudb
|negvvn (55)
|nhpvc (86)
|wbrop (233) -> xnfjw, ynbhq
|fgqxuig (275) -> qjknns, kxbclr, uwlpeon
|wmciqdi (335) -> opnqtf, ydzdome, gdjawl
|laydujd (99)
|vuqlmx (932) -> tlbakdh, daaexz, maokl, owqupte
|zopkd (22)
|azsiin (69)
|hgyhzc (311)
|nlbnj (13)
|ygukv (115) -> wacnhz, kgfeyyg
|gxrmso (242)
|jfccr (53)
|sfyps (20)
|deargsb (11)
|dqxvm (67)
|mqvstxt (134) -> jrtqzng, xgelkov
|twsvvzh (25)
|qrnztia (145) -> bktiekj, yagjnwy
|rnnmuk (49)
|qxqzzw (96)
|nawhukx (188) -> fkksmck, deargsb
|tiwaeim (98)
|iwrph (77)
|feyiw (20)
|akvov (90)
|wacnhz (45)
|mhpsnlv (93)
|yfrcezm (95)
|dsqvto (207) -> cpbxfaf, inuxln, bolsi
|rhfpsr (55)
|gnamu (397) -> pudsuxc, lddqu, qffvjvy
|buxlsok (96)
|ebjqfgp (20)
|vdabfab (73)
|memsb (10)
|nkotu (29)
|rctutb (98)
|dlsayg (66)
|megix (13)
|nkgayde (69)
|zfrzbb (32)
|whdgk (73)
|gnmudrh (331) -> zqqxw, uagtb
|chpsgen (2051) -> irckle, epxtul, atnshbm, ostpegy
|hyjba (82)
|mcsoi (10)
|uyiaqu (98) -> gjlsrq, ilrkhhd
|bdzqyu (16)
|necuat (58)
|uymxxd (56)
|qdzefux (139) -> hdahal, bjfmsgp
|zqega (18)
|jelwm (60) -> hkykap, jpsejb
|lcpbmc (212)
|nuoxnzw (99)
|lpogx (65)
|maokl (171) -> xdxiemt, ajjyqz
|fwfbtcw (35)
|ostpegy (60) -> rfvtvw, hzain
|uqfiwz (29)
|fllyd (54)
|ntzgern (67)
|wfmql (22)
|hugzzwo (45)
|oxjor (87)
|ncpzhu (83) -> loaex, qoamv, rnfox, xsyepmg
|gzwkbw (123) -> efvcgxy, knczsg
|usvvacs (80)
|cptmwf (75)
|xdfyw (104) -> yafzoj, nazoxxl, jnack
|ijibo (390) -> xkqsn, colwnyd, unehvbu
|nykzm (275)
|wxjuvo (56)
|obumrhe (275)
|fwapzg (12)
|uvprg (10) -> qhavltn, yswzfg, fjwfhq
|klkyckz (96)
|koacic (69)
|ihxivjd (902) -> rsnptie, tollmm, mceul, tfjzhz, amsxxe
|lausf (38)
|sakilbi (57)
|gdbapcx (25)
|wqljugh (41)
|zvdii (20)
|wdvmq (81) -> gkyvjtj, azsiin, gmyydys
|aemnj (107) -> pvthg, deusrct
|smamg (5382) -> hgtwnxu, eksshr, dhdhlmq
|tqjoo (58)
|abkzl (24)
|keesuec (54)
|soguk (98)
|rnfox (71) -> tytufo, qsoybe
|xdohu (46)
|bvxxoux (56)
|decklvy (1050) -> umnhed, wqgini, tqfnnek
|sakwdmk (138) -> xpormy, nhhvktp
|ezimk (13)
|bhezu (44)
|dfzlxba (57)
|xypefbg (73)
|tfkse (189) -> zbvvekj, kunxx, dqxvm
|vcdrqps (69)
|fmvna (260) -> sozke, pgarna, abkzl
|fyzadg (18)
|blhurw (51)
|rolegtf (97)
|jmrywkk (237)
|kqcmyr (301) -> uyhqy, ojwlkyk
|hpovffo (44)
|mzsoo (25)
|tuorl (90)
|bzlttq (73) -> hdwpha, yzpxkx
|uozna (81)
|qznfyv (12)
|xpxbgh (44)
|abjhq (21)
|criaedy (179) -> vybrd, jprgu, tldocc
|amqvafo (77)
|vckadf (8)
|schbl (6)
|veujpah (14)
|vrqgow (95)
|qoamv (165) -> xqfwvbf, gihhi
|tlzng (35)
|dkxedzu (91)
|vcezyqj (8443) -> luxlkxu, dpmsnm, yxfyvw
|ipbhoko (5)
|krhtjha (34)
|xktot (268) -> ewnboyh, sesui
|lscpgcs (296) -> fxjooi, qfabag, nkvxvrf, cjyrih
|kaursj (1519) -> kjibzax, lyoaqtx, iclynp, jsgvv, fzhncm, vvsgr, ohcob
|kswmjp (93)
|rpywck (36) -> asafmi, tkneufh
|wiqjl (209) -> zygpcpd, vtprv, wrbqnx, jniuewa
|wfekn (48)
|tvshylj (69)
|qkdikgs (21)
|plcqz (44)
|wccvu (169) -> ukxuw, thnxnda
|pdttnl (55)
|xkuubv (35)
|nhhvktp (97)
|qjknns (30)
|ltfanj (54)
|pulpbaj (28) -> bbupp, jeopi
|xcobqnc (65)
|aqdba (167) -> slnbq, axjaxn
|qadkf (32) -> odqxcfl, kswmjp, bylpn
|vrfkca (20)
|fdvpljm (96)
|qhavltn (73)
|niixavl (43) -> siyms, tiwaeim
|ieuus (79) -> jenzlcn, kchcxe
|mfkfr (87)
|etzocl (90)
|pgarna (24)
|cjgtcao (44)
|ctmtk (6)
|rrizdbi (20)
|bltjqky (8)
|ilmqyc (47)
|gfrqgpm (54)
|titde (75)
|jsgvv (368) -> btvxwyj, kdhmnh, ucorqrv, uoxqwap
|afdox (41) -> gkcpihl, yvedw, urawf
|pntxt (52)
|pzwxz (73)
|btvxwyj (81) -> xxjcew, fvdsi
|frqiho (12)
|xkyjdv (44) -> soguk, rctutb
|sqzdg (176) -> xrxabjj, zvctpo
|ymbtxzb (19) -> qdrbdcf, nhnwqgh
|slimx (1283) -> xktot, zazlcg, lscpgcs, zdrbia
|eebqhug (83)
|azmknz (35)
|fbnmdsm (37)
|laepzgh (64)
|yhmavn (70)
|japznn (71)
|xsjptl (75)
|pctst (154) -> bltjqky, vckadf
|khajtz (111) -> yzahca, kwkcos
|gbkfxbj (276)
|kozlucm (85)
|jprgu (42)
|rggrduc (37)
|oejnh (55)
|ugskjw (17)
|baqqex (54)
|vxzqqkt (419)
|mzvyddo (788) -> brtvs, kmzeahn, onbize, cuikvge, lcpbmc, bzhnu, xyvst
|eddcns (53)
|rfzyvg (56)
|ctnckd (10)
|kjauj (49)
|plzvkk (27)
|irmjpg (206) -> cxfgjp, sakilbi
|lozmiv (59)
|shypdye (118)
|pkhkeva (69)
|lbrknfc (14)
|dtqejc (34)
|jholt (9)
|kpjzc (93)
|xwtls (91)
|zhqnj (225)
|cjyrih (12)
|chcsjda (201)
|uagtb (17)
|uyxpx (166) -> zscii, lozmiv
|vewew (13)
|ivksd (90)
|yafzoj (61)
|ybwjsz (99)
|pwzfoy (67)
|ghdqy (54)
|sjlwjcc (41)
|iqwjlgh (6)
|gbuhi (243) -> wlqagku, wcqwomp
|bpbfd (25)
|mxigb (25)
|lzdzs (69)
|pyavtyz (239)
|xdxiemt (14)
|cryxpp (31) -> cptmwf, xsjptl, titde
|zkfwc (81) -> pvxvvv, fldjrj
|ujtmmb (141) -> xypefbg, vdabfab
|emqcvc (1138) -> wfoili, zqega, fyzadg
|gvupyd (129)
|twyuae (37)
|ddneaes (40) -> icdcn, gunuriu, whdgk, gkouyvq
|vqijdaj (68)
|ttvyvv (26)""".stripMargin
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.