repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
sehirsig/malefiz
src/test/scala/de/htwg/se/malefiz/aview/TUISpec.scala
<reponame>sehirsig/malefiz package de.htwg.se.malefiz.aview import org.scalatest.wordspec.AnyWordSpec import org.scalatest.matchers.should.Matchers import de.htwg.se.malefiz.controller.controllerComponent._ import de.htwg.se.malefiz.controller.controllerComponent.controllerBaseImpl import de.htwg.se.malefiz.model.gameboardComponent.gameboardBaseImpl.{Gameboard, Settings} /** Test class for the TUI. * * @author sehirsig & franzgajewski */ class TUISpec extends AnyWordSpec with Matchers { "A Malefiz Text-User-Interface" when { "A Malefiz Tui" should { val controller = controllerBaseImpl.Controller(new Gameboard(Settings().xDim, Settings().yDim)) val tui = TUI(controller) "should be initialy idle" in { tui.currentState should be(IdleTUIState) } "should process an input" in { tui.processing("remove") tui.processing("replace") tui.processing("p") tui.currentState should be(PlayerNameState) tui.processing("xy") tui.currentState should be(IdleTUIState) } "react on events" in { controller.publish(new RollDice) tui.currentState should be(PlayingTUIState) controller.publish(new Moving) tui.currentState should be(MovingTUIState) controller.publish(new ChooseFig) tui.currentState should be(ChooseGameFigTUIState) controller.publish(new SettingUp) tui.currentState should be(ChooseGameFigTUIState) controller.publish(new StartUp) tui.currentState should be(ChooseGameFigTUIState) controller.publish(new StartGame) tui.currentState should be(PlayingTUIState) controller.publish(new WonGame) tui.currentState should be(WinnerTUIState) controller.publish(new GameReset) tui.currentState should be(IdleTUIState) controller.publish(new GameSaved) tui.currentState should be(IdleTUIState) controller.publish(new GameLoaded) tui.currentState should be(IdleTUIState) } "do nothing on input 'welcomeMessage'" in { tui.processing("welcomeMessage") tui.currentState should be(IdleTUIState) } "do not start if < 2 players" in { tui.processing("s") tui.currentState should be(IdleTUIState) } "add players on input 'p'" in { tui.processing("p") tui.processing("xy") tui.processing("p") tui.processing("yz") tui.processing("pDEBUG") tui.processing("p") tui.processing("pDEBUG") tui.currentState should be(IdleTUIState) } "start the game on input 'start'" in { tui.processing("s") tui.currentState should be(PlayingTUIState) } "roll the dice on input 'r'" in { tui.processing("r") tui.currentState should be(ChooseGameFigTUIState) } "choose no Figure if invalid input" in { tui.processing("Invalid") tui.currentState should be(ChooseGameFigTUIState) } "choose Figure if valid input" in { tui.processing("1") tui.currentState should be(MovingTUIState) } "not move on invalid input" in { tui.processing("invalid") tui.currentState should be(MovingTUIState) } "move up on input 'w'" in { tui.controller.moveCounter = 5 tui.processing("w") } "move left on input 'a'" in { tui.processing("a") } "move undo on input 'undo'" in { tui.processing("undo") } "move redo on input 'redo'" in { /** Redo, then move the rest to get the top left Blocked Cell, to walk down the next time */ tui.processing("redo") tui.processing("a") tui.processing("w") tui.processing("w") /** Player 2 Rolls and chooses Gamefigure in Debug Mode */ tui.processing("rDEBUG") tui.processing("1") tui.currentState should be(MovingTUIState) } "skip round on input 'skip'" in { /** Player 2 Skips round */ tui.processing("skip") tui.currentState should be(PlayingTUIState) } "move down on input 's'" in { /** Player 1 rolls, chooses gamefig 1 to move down */ tui.processing("r") tui.controller.moveCounter = 5 tui.processing("1") tui.processing("s") tui.processing("s") tui.currentState should be(MovingTUIState) } "move right on input 'd'" in { tui.processing("d") tui.currentState should be(MovingTUIState) } "do use a on MovingTUI" in { tui.processing("a") tui.currentState should be(MovingTUIState) } "do use undo on MovingTUI" in { tui.processing("undo") tui.currentState should be(MovingTUIState) } "do use redo on MovingTUI" in { tui.processing("redo") tui.currentState should be(MovingTUIState) } "do nothing on invalid inputs" in { tui.processing("krgr") tui.currentState should be(MovingTUIState) } "save the game" in { tui.currentState = PlayingTUIState tui.processing("save") tui.currentState should be(PlayingTUIState) } "do nothing with the game" in { tui.processing("invalid") tui.currentState should be(PlayingTUIState) } "do correct on a win" in { tui.currentState = WinnerTUIState tui.currentState = WinnerTUIState.processing("") } "do nothing with Idle Invalid input" in { tui.currentState = IdleTUIState tui.processing("invalidinput") tui.currentState should be(IdleTUIState) } "do nothing on Reset Invalid input" in { tui.currentState = GameResetTUIState tui.processing("invalidinput") tui.currentState should be(GameResetTUIState) } "do correct on a Reset " in { tui.currentState = GameResetTUIState tui.processing("reset") tui.currentState should be(IdleTUIState) } "not load the game" in { tui.currentState = IdleTUIState tui.processing("pDEBUG") tui.processing("load") tui.currentState should be(IdleTUIState) } "load the game" in { tui.processing("pDEBUG") tui.processing("load") tui.currentState should be(PlayingTUIState) } "win the Game" in { tui.currentState = GameResetTUIState tui.processing("reset") tui.processing("pDEBUG") tui.processing("pDEBUG") tui.processing("s") tui.processing("rDEBUG") tui.processing("1") tui.processing("w") tui.currentState should be(GameResetTUIState) } } } }
sehirsig/malefiz
src/main/scala/de/htwg/se/malefiz/model/cellComponent/Cell.scala
<reponame>sehirsig/malefiz<filename>src/main/scala/de/htwg/se/malefiz/model/cellComponent/Cell.scala package de.htwg.se.malefiz.model.cellComponent /** All cells needed for the Malefiz game. * * @author sehirsig & franzgajewski */ trait Cell { val cellStatus:String def isWalkable: Boolean = cellStatus != " " && cellStatus != "T " override def toString(): String = { cellStatus } } object FreeCell extends Cell { override val cellStatus = "O " } object BlockedCell extends Cell { override val cellStatus = "X " } object Start1Cell extends Cell { override val cellStatus = "T " } object Start2Cell extends Cell { override val cellStatus = "T " } object Start3Cell extends Cell { override val cellStatus = "T " } object Start4Cell extends Cell { override val cellStatus = "T " } object SecureCell extends Cell { override val cellStatus = "O " } object GoalCell extends Cell { override val cellStatus = "G " } object InvalidCell extends Cell { override val cellStatus = " " } /** Players get cells by setting individual parameters. */ case class PlayerCell(num:Int) extends Cell { def getPlayer:Int = num override val cellStatus = num.toString + " " }
sehirsig/malefiz
src/main/scala/de/htwg/se/malefiz/model/gameboardComponent/gameboardAdvancedImpl/Gameboard.scala
package de.htwg.se.malefiz.model.gameboardComponent.gameboardAdvancedImpl import com.google.inject.Inject import com.google.inject.name.Named import de.htwg.se.malefiz.model.gameboardComponent.gameboardBaseImpl.{Gameboard => BaseGameboard} /** Extension of the base implementation of the game board. * Here the dimensions are written in the constructor. * * @author sehirsig & franzgajewski */ class Gameboard @Inject() (@Named("DefaultSizeX") sizex:Int, @Named("DefaultSizeY") sizey:Int) extends BaseGameboard(sizex,sizey){ }
sehirsig/malefiz
src/main/scala/de/htwg/se/malefiz/controller/controllerComponent/GameStatus.scala
<reponame>sehirsig/malefiz<gh_stars>1-10 package de.htwg.se.malefiz.controller.controllerComponent /** The status updates of the game. * * @author sehirsig & franzgajewski */ object GameStatus extends Enumeration { type GameStatus = Value type PlayerStatus = Value val WELCOME, LOADED, SAVED, GAMEWINNER, CHOOSEFIG, IDLE, READY1, READY2, PLAYER0, PLAYER1, PLAYER2, PLAYER3, PLAYER4, PLAYING, MOVING, ENTERNAME = Value val gameMap = Map[GameStatus, String]( WELCOME -> "Welcome to the Malefiz Game 2021!\n'p' to add players!", GAMEWINNER -> "We have a Winner! 'reset' to Reset and Play Again!", CHOOSEFIG -> "Choose a Figure (1-5)", IDLE -> "Press p to add players", READY1 -> "Type 's' to start or press p to add more players", READY2 -> "Type 's' to start to play the Game", PLAYING -> "Press r to roll dice", MOVING -> "Press a,w,s,d to move", ENTERNAME -> "Please enter your name", LOADED -> "Game loaded!", SAVED -> "Game saved!" ) val playerMap = Map[PlayerStatus, String]( PLAYER1 -> "Player 1 press r to roll dice", PLAYER2 -> "Player 2 press r to roll dice", PLAYER3 -> "Player 3 press r to roll dice", PLAYER4 -> "Player 4 press r to roll dice", PLAYER0 -> "Player -" ) def gameMessage(gameStatus: GameStatus): String = { gameMap(gameStatus) } }
sehirsig/malefiz
src/main/scala/de/htwg/se/malefiz/model/gamefigureComponent/Gamefigure.scala
<filename>src/main/scala/de/htwg/se/malefiz/model/gamefigureComponent/Gamefigure.scala<gh_stars>1-10 package de.htwg.se.malefiz.model.gamefigureComponent import de.htwg.se.malefiz.model.playerComponent.Player /** Declaration of the game figures for the game. * * @author sehirsig & franzgajewski */ case class Gamefigure(number: Int, id: Int, player: Player, pos: (Int, Int)) { def getNumber: Int = number def getPlayer: Player = player def updatePos(posNew: (Int, Int)): Gamefigure = { copy(pos = posNew) } override def toString: String = player.Playerid.toString + " " }
sehirsig/malefiz
src/test/scala/de/htwg/se/malefiz/MalefizSpec.scala
package de.htwg.se.malefiz import de.htwg.se.malefiz.aview.TUI import de.htwg.se.malefiz.controller.controllerComponent.controllerBaseImpl import de.htwg.se.malefiz.controller.controllerComponent.controllerBaseImpl.Controller import de.htwg.se.malefiz.model.gameboardComponent.gameboardBaseImpl.{Gameboard, Settings} import org.scalatest.wordspec.AnyWordSpec import org.scalatest.matchers.should.Matchers import java.io.ByteArrayInputStream /** Test class for the Malefiz main class. * * @author sehirsig & franzgajewski */ class MalefizSpec extends AnyWordSpec with Matchers { "The Malefiz main class" should { val controller = new Controller(new Gameboard(Settings().xDim, Settings().yDim)) val tui = new TUI(controller) "run normally and Quit" in { val in = new ByteArrayInputStream("Q".getBytes) Console.withIn(in) { Malefiz.main(Array()) } } "create the controller " in { controller should be (controllerBaseImpl.Controller(new Gameboard(Settings().xDim, Settings().yDim))) } "create the tui" in { tui should be (TUI(controllerBaseImpl.Controller(new Gameboard(Settings().xDim, Settings().yDim)))) } } }
sehirsig/malefiz
src/test/scala/de/htwg/se/malefiz/util/CommandSpec.scala
package de.htwg.se.malefiz.util import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec class testCommand extends Command { var saved:Int = 0 override def doStep: Unit = saved += 1 override def undoStep: Unit = saved -= 1 override def redoStep: Unit = doStep } /** Test class for the Command class. * * @author sehirsig & franzgajewski */ class CommandSpec extends AnyWordSpec with Matchers { "A Command " should { "do a step in doStep" in { val cmd = new testCommand cmd.doStep cmd.saved should be(1) } "do a undo in undoStep" in { val cmd = new testCommand cmd.doStep cmd.undoStep cmd.saved should be(0) } "do a redo in redoStep" in { val cmd = new testCommand cmd.doStep cmd.undoStep cmd.redoStep cmd.saved should be(1) } } }
sehirsig/malefiz
src/test/scala/de/htwg/se/malefiz/model/gameboardComponent/gameboardBaseImpl/moveTypesSpec.scala
package de.htwg.se.malefiz.model.gameboardComponent.gameboardBaseImpl import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec /** Test class for the base implementation of the moveTypes class. * * @author sehirsig & franzgajewski */ class moveTypesSpec extends AnyWordSpec with Matchers { "moveTypes Functions" when { "operate" should { "change up" in { moveTypes.goUp(1,1) should be (0,1) } "change down" in { moveTypes.goDown(1,1) should be (2,1) } "change left" in { moveTypes.goLeft(1,1) should be (1,0) } "change right" in { moveTypes.goRight(1,1) should be (1,2) } } } }
sehirsig/malefiz
src/main/scala/de/htwg/se/malefiz/util/UndoManager.scala
package de.htwg.se.malefiz.util /** Undo manager class. * * @author sehirsig & franzgajewski */ class UndoManager { /** List of all doable steps. */ private var undoStack: List[Command]= Nil /** List of all redoable steps. */ private var redoStack: List[Command]= Nil /** Do one step. * * @param command Command */ def doStep(command: Command): Unit = { undoStack = command::undoStack command.doStep } /** Undo one step. */ def undoStep: Unit = { undoStack match { case Nil => case head::stack => { head.undoStep undoStack=stack redoStack= head::redoStack } } } /** Redo one step. */ def redoStep: Unit = { redoStack match { case Nil => case head::stack => { head.redoStep redoStack=stack undoStack=head::undoStack } } } /** Empty steps entirely. */ def emptyStacks: Unit = { undoStack = Nil redoStack = Nil } /** Execute all undos at once. */ def undoAll: Unit = { while(undoStack != Nil) { undoStep } } }
sehirsig/malefiz
src/test/scala/de/htwg/se/malefiz/model/gameboardComponent/gameboardBaseImpl/SettingsSpec.scala
<gh_stars>1-10 package de.htwg.se.malefiz.model.gameboardComponent.gameboardBaseImpl import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec /** Test class for the base implementation of the Settings class. * * @author sehirsig & franzgajewski */ class SettingsSpec extends AnyWordSpec with Matchers { "The Settings should" when { "have the right dimension" should { val set = Settings() "be displayed as \" \"" in { set.yDim should be(Settings().yDim) set.xDim should be(Settings().xDim) } } "be initialized right" should { val set = Settings() "with the right path" in { set.walkableCells.contains(Settings().freeCells) } } } }
sehirsig/malefiz
src/main/scala/de/htwg/se/malefiz/aview/TUIState.scala
package de.htwg.se.malefiz.aview import de.htwg.se.malefiz.Malefiz.controller /** State pattern for TUI.scala. * Main interface for our states. * * @author sehirsig & franzgajewski */ trait TUIState { def processing(input: String): TUIState } /** Initial state. Used to add players and start the game. */ object IdleTUIState extends TUIState { def processing(input: String): TUIState = { input match { case "p" => { if(controller.game.getPlayerNumber() < 4) { controller.addPlayer() PlayerNameState } else { println("game full");IdleTUIState } } case "s" => { if(controller.game.getPlayerNumber() > 1) { controller.startGame() PlayingTUIState } else { println("not enough players");IdleTUIState } } /** A debug-player that starts in front of the goal. */ case "pDEBUG" => { if(controller.game.getPlayerNumber() < 4) { controller.addPlayerDEBUGWINTEST("debug") IdleTUIState } else { println("game full");IdleTUIState } } case "load" => { if(controller.game.getPlayerNumber() > 1) { controller.load PlayingTUIState } else { println("This game has " + controller.game.getPlayerNumber().toString + " Player/s. You need to add atleast 2 players to load a game!");IdleTUIState } } case "remove" => controller.setBlockStrategy(input);IdleTUIState case "replace" => controller.setBlockStrategy(input);IdleTUIState case "welcomeMessage" => println("Welcome to Malefiz");IdleTUIState case _ => println("invalid input");IdleTUIState } } } /** State for entering player names. */ object PlayerNameState extends TUIState { def processing(input: String): TUIState = { controller.addPlayerName(input) IdleTUIState } } /** State for running the game. */ object PlayingTUIState extends TUIState { def processing(input: String): TUIState = { input match { /** Current state of the board gets saved to file. */ case "save" => controller.save;PlayingTUIState /** Die roll. */ case "r" => controller.rollDice();println("You have rolled a: " + controller.moveCounter);ChooseGameFigTUIState /** Die roll for debug. Always rolls a 1. */ case "rDEBUG" => controller.debugDice();println("You have rolled a: " + controller.moveCounter);ChooseGameFigTUIState case _ => println("invalid input");PlayingTUIState } } } /** State for selecting a game figure. */ object ChooseGameFigTUIState extends TUIState { def processing(input: String): TUIState = { input match { case "1" | "2" | "3" | "4" | "5" => controller.selectFigure(input.toInt);MovingTUIState case _ => println("invalid input");ChooseGameFigTUIState } } } /** State for winning the game. */ object WinnerTUIState extends TUIState { def processing(input: String): TUIState = { input match { case _ => println("Winner: " + controller.gameWon._2 + "\n");GameResetTUIState } } } /** State for reset after the game was won. */ object GameResetTUIState extends TUIState { def processing(input: String): TUIState = { input match { case "reset" => controller.resetGame();IdleTUIState case _ => println("Invalid Input! Enter 'reset' to start a new Game!");GameResetTUIState } } } /** State for moving of game figures. */ object MovingTUIState extends TUIState { def processing(input: String): TUIState = { input match { case "w" => controller.move(input, controller.selectedFigNum); MovingTUIState case "a" => controller.move(input, controller.selectedFigNum); MovingTUIState case "s" => controller.move(input, controller.selectedFigNum); MovingTUIState case "d" => controller.move(input, controller.selectedFigNum); MovingTUIState case "undo" => controller.move(input, controller.selectedFigNum); MovingTUIState case "redo" => controller.move(input, controller.selectedFigNum); MovingTUIState case "skip" => controller.move(input, controller.selectedFigNum); MovingTUIState case _ => println("invalid input"); MovingTUIState } if (controller.moveCounter == 0) { if (controller.gameWon._1){ GameResetTUIState } else { PlayingTUIState } } else { println("Moves remaining:" + controller.moveCounter) MovingTUIState } } }
sehirsig/malefiz
src/main/scala/de/htwg/se/malefiz/util/BlockStrategy.scala
package de.htwg.se.malefiz.util import de.htwg.se.malefiz.model.gameboardComponent.GameboardInterface /** BlockStrategy pattern interface. * * @author sehirsig & franzgajewski */ trait BlockStrategy { /** Replace block * * @param spielbrett old game board * @return new game board */ def replaceBlock(spielbrett:GameboardInterface): GameboardInterface }
sehirsig/malefiz
src/test/scala/de/htwg/se/malefiz/util/BlockStrategySpec.scala
package de.htwg.se.malefiz.util import de.htwg.se.malefiz.model.gameboardComponent.gameboardBaseImpl.checkCell._ import de.htwg.se.malefiz.model.gameboardComponent.gameboardBaseImpl.{Gameboard, Settings} import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec /** Test class for BlockStrategy class. * * @author sehirsig & franzgajewski */ class BlockStrategySpec extends AnyWordSpec with Matchers { "A BlockStrategy " should { val settings = new Settings val spielbrett = new Gameboard(settings.yDim, settings.xDim) "replace a Block with Replace Strategy" in { spielbrett.setBlockStrategy("replace") val newspielbrett = replaceBlock(spielbrett) newspielbrett should not be (spielbrett) } "remove a Block with Remove Strategy" in { spielbrett.setBlockStrategy("remove") val newspielbrett = replaceBlock(spielbrett) newspielbrett should be (spielbrett) } } }
sehirsig/malefiz
src/test/scala/de/htwg/se/malefiz/model/gameboardComponent/gameboardBaseImpl/DiceSpec.scala
<reponame>sehirsig/malefiz package de.htwg.se.malefiz.model.gameboardComponent.gameboardBaseImpl import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec /** Test class of the base implementation of the Dice class. * * @author sehirsig & franzgajewski */ case class DiceSpec() extends AnyWordSpec with Matchers { "A Dice" when { "used" should { "should have value between 1 - 6" in { Dice.diceRoll.isInstanceOf[Double] Dice.diceRoll should (be(1) or be(2) or be(3) or be(4) or be(5) or be(6)) } } } }
sehirsig/malefiz
src/main/scala/de/htwg/se/malefiz/model/playerComponent/PlayerBuilder.scala
<reponame>sehirsig/malefiz<gh_stars>1-10 package de.htwg.se.malefiz.model.playerComponent /** Builder pattern for player class. * * @author sehirsig & franzgajewski */ trait PlayerBuilder { def setName(name: String): PlayerBuilder def setID(id: Int): PlayerBuilder def setStartingPos(pos: (Int, Int)): PlayerBuilder def build(): Player } /** Implement of the interface. */ case class PlayerBuilderImp() extends PlayerBuilder { var name: String = "" var id: Int = 0 var pos:(Int, Int) = (0,0) /** Set player name. */ override def setName(nameNew: String): PlayerBuilder = { this.name = nameNew this } /** Set player ID. */ override def setID(idNew: Int): PlayerBuilder = { this.id = idNew this } /** Set starting position for game figures of the player. */ override def setStartingPos(posNew: (Int, Int)): PlayerBuilder = { this.pos = posNew this } /** Build player. */ override def build(): Player = Player(name, id, pos) }
sehirsig/malefiz
src/main/scala/de/htwg/se/malefiz/controller/controllerComponent/controllerBaseImpl/Controller.scala
<gh_stars>1-10 package de.htwg.se.malefiz.controller.controllerComponent.controllerBaseImpl import com.google.inject.{Guice, Inject} import de.htwg.se.malefiz.MalefizModule import de.htwg.se.malefiz.controller.controllerComponent.GameStatus._ import de.htwg.se.malefiz.controller.controllerComponent._ import de.htwg.se.malefiz.model.cellComponent._ import de.htwg.se.malefiz.model.fileIoComponent.FileIOInterface import de.htwg.se.malefiz.model.gameComponent.Game import de.htwg.se.malefiz.model.gameboardComponent.{GameboardInterface, lastSaveInterface} import de.htwg.se.malefiz.model.playerComponent._ import de.htwg.se.malefiz.util.UndoManager import net.codingwell.scalaguice.InjectorExtensions.ScalaInjector import scala.swing.Publisher /** Base implementation of the controller of the Malefiz game. * * @author sehirsig & franzgajewski */ case class Controller @Inject() (var gameboard: GameboardInterface) extends ControllerInterface with Publisher { /** Injector for the dependency injection. */ val injector = Guice.createInjector(new MalefizModule) /** Dependency injection for fileIO. */ val fileIo = injector.instance[FileIOInterface] /** Initialization of the game state. */ override var gameStatus: GameStatus = WELCOME /** Initialization of the player state (to determine the next player). */ override var playerStatus: PlayerState = PlayerState1 /** Indicates remaining moves. */ override var moveCounter: Int = 0 /** Builder pattern for players. */ override val builder: PlayerBuilder = new PlayerBuilderImp() /** Saving of players and figures. */ override var game: Game = Game(Vector[Player]()) /** Initialization of the UndoManager */ private val undoManager = new UndoManager /** Boolean indicates, whether there is a winner and who. */ override var gameWon: (Boolean, String) = (false, "") /** Dependency injection of the state of the last move. */ override var savedGame = injector.instance[lastSaveInterface] override var selectedFigNum: Int = 0; publish(new StartUp) /** Game reset for restart after a game was won. */ override def resetGame(): Unit = { gameStatus = WELCOME game = new Game(Vector[Player]()) emptyMan savedGame = injector.instance[lastSaveInterface] playerStatus = PlayerState1 moveCounter = 0 gameWon = (false, "") selectedFigNum = 0; this.gameboard = gameboard.newGBStandardSize publish(new GameReset) } /** Selection of game figure. */ override def selectFigure(x: Int): Unit = { selectedFigNum = x gameStatus = MOVING publish(new Moving) } /** Retrieve cell from string descriptor. */ override def getpureCell(name: String): Cell = { gameboard.getCell(name) } /** Add a player. */ override def addPlayer(): Unit = { gameWon = (false, "") gameStatus = ENTERNAME publish(new SettingUp) } /** Add player name and initialize 5 game figures. */ override def addPlayerName(name: String): Unit = { builder.setName(name) val newplayernum = game.players.length + 1 builder.setID(newplayernum) newplayernum match { case 1 => builder.setStartingPos(gameboard.getP1Base._1, gameboard.getP1Base._2) case 2 => builder.setStartingPos(gameboard.getP2Base._1, gameboard.getP2Base._2) case 3 => builder.setStartingPos(gameboard.getP3Base._1, gameboard.getP3Base._2) case 4 => builder.setStartingPos(gameboard.getP4Base._1, gameboard.getP4Base._2) } val player = builder.build() (1 to 5).map(x => player.addFigure(x)) game = game.addPlayer(player) if (game.getPlayerNumber() > 3) { gameStatus = READY2 } else if (game.getPlayerNumber() < 2) { gameStatus = IDLE } else { gameStatus = READY1 } publish(new StartUp) } /** Start game. */ override def startGame(): Unit = { gameStatus = PLAYING publish(new StartGame) } /** Setup game at start of the application. */ override def setupGame(): Unit = { publish(new SettingUp) } /** String representation of the game board. */ override def boardToString(): String = gameboard.toString() /** Die roll. */ override def rollDice(): Int = { moveCounter = gameboard.diceRoll gameStatus = CHOOSEFIG savedGame = savedGame.updateLastFullDice(moveCounter) publish(new ChooseFig) moveCounter } /** Check for a winner. */ override def checkWin(): Unit = { if (gameboard.checkPlayerOnGoal) { gameStatus = GAMEWINNER val winner = gameboard.cell(gameboard.getGoalBase._1, gameboard.getGoalBase._2).toString().replace(" ", "").toInt - 1 gameWon = (true, game.players(winner).name.replace("Some", "")) publish(new WonGame) } } /** Choose block strategy. This determines what happens to blocks, after they are captured. */ override def setBlockStrategy(blockStrategy: String): Unit = { blockStrategy match { case "replace" => gameboard.setBlockStrategy(blockStrategy) case "remove" => gameboard.setBlockStrategy(blockStrategy) } } /** Move. */ override def move(input: String, figurenum: Int): Unit = { input match { case "skip" => moveCounter = 1; undoManager.doStep(new MoveCommand(input, figurenum, this)) case "undo" => undo case "redo" => redo case _ => if (input != savedGame.lastDirectionOpposite) undoManager.doStep(new MoveCommand(input, figurenum, this)); } if (moveCounter == 0) { /** Checks if the goal cell is occupied. */ checkWin() /** Continues if game has not been won. */ if (!gameWon._1) { gameStatus = PLAYING publish(new RollDice) } } else { publish(new Moving) } } /** Empties undo stack to reset the undo manager for the next player. */ override def emptyMan: Unit = { undoManager.emptyStacks } /** Executes all undo steps on the undo stack. */ override def undoAll: Unit = { undoManager.undoAll } /** Undo. */ override def undo: Unit = { undoManager.undoStep } /** Redo. */ override def redo: Unit = { undoManager.redoStep } /** Save game state to file. */ override def save: Unit = { fileIo.save(gameboard) gameStatus = SAVED publish(new RollDice) } /** Load game state from file. */ override def load: Unit = { /** Loaded file gets split to relevant variables, so that game figures can be handled correctly. */ val temp = fileIo.load(game) gameboard = temp._1 game = temp._2 gameStatus = LOADED publish(new RollDice) } /** Debug for testing purposes. Here the starting position is set directly in front of the goal. * With a move counter of 1 the game can be won immediately. * * @param name name of the debug player */ override def addPlayerDEBUGWINTEST(name: String): Unit = { builder.setName(name) val newplayernum = game.players.length + 1 builder.setID(newplayernum) newplayernum match { case 1 => builder.setStartingPos(gameboard.getGoalBase._1 + 1, gameboard.getGoalBase._2) case 2 => builder.setStartingPos(gameboard.getGoalBase._1 + 1, gameboard.getGoalBase._2) case 3 => builder.setStartingPos(gameboard.getGoalBase._1 + 1, gameboard.getGoalBase._2) case 4 => builder.setStartingPos(gameboard.getGoalBase._1 + 1, gameboard.getGoalBase._2) } val player = builder.build() (1 to 5).map(x => player.addFigure(x)) game = game.addPlayer(player) if (game.getPlayerNumber() > 3) { gameStatus = READY2 } else if (game.getPlayerNumber() < 2) { gameStatus = IDLE } else { gameStatus = READY1 } publish(new StartUp) } /** Debug for testing purposes. This will always roll a 1 so that the game can be won immediately. */ override def debugDice(): Unit = { moveCounter = 1 gameStatus = CHOOSEFIG savedGame = savedGame.updateLastFullDice(moveCounter) publish(new ChooseFig) } }
sehirsig/malefiz
src/main/scala/de/htwg/se/malefiz/model/gameComponent/Game.scala
package de.htwg.se.malefiz.model.gameComponent import de.htwg.se.malefiz.model.playerComponent.Player /** Game class. Here the players are stored. * * @author sehirsig & franzgajewski */ case class Game(var players: Vector[Player]) { def addPlayer(player: Player): Game = { val newPlayer = Vector(player) copy(players ++ newPlayer) } def getPlayerNumber(): Int = players.size }
sehirsig/malefiz
src/test/scala/de/htwg/se/malefiz/model/cellComponent/CellSpec.scala
package de.htwg.se.malefiz.model.cellComponent import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec /** Test class for the Cell class. * * @author sehirsig & franzgajewski */ class CellSpec extends AnyWordSpec with Matchers { "A Cell" when { "Free" should { "be displayed as \" \"" in { FreeCell.toString should be("O ") } "be walkable" in { FreeCell.isWalkable should be (true) } } "empty" should { "be displayed as \" \"" in { InvalidCell.toString should be(" ") } "not be walkable" in { InvalidCell.isWalkable should be (false) } } "Secure" should { "be displayed as \"O \"" in { SecureCell.toString should be("O ") } "be walkable" in { SecureCell.isWalkable should be (true) } } "blocked" should { "be displayed as \"X \"" in { BlockedCell.toString should be("X ") } } "the goal" should { "be displayed as \"G \"" in { GoalCell.toString should be("G ") } } "the playercell" should { "be displayed as \"1 \"" in { PlayerCell(1).toString should be("1 ") } "return the Players Number" in { PlayerCell(1).getPlayer should be (1) } } } }
sehirsig/malefiz
src/main/scala/de/htwg/se/malefiz/model/gameboardComponent/gameboardBaseImpl/moveTypes.scala
<gh_stars>1-10 package de.htwg.se.malefiz.model.gameboardComponent.gameboardBaseImpl /** Class to overwrite coordinates of a cell quickly to those of the next cell. * * @author sehirsig & franzgajewski */ object moveTypes { def goDown(oldcord: (Int, Int)): (Int, Int) = { (oldcord._1 + 1, oldcord._2) } def goUp(oldcord: (Int, Int)): (Int, Int) = { (oldcord._1 - 1, oldcord._2) } def goRight(oldcord: (Int, Int)): (Int, Int) = { (oldcord._1, oldcord._2 + 1) } def goLeft(oldcord: (Int, Int)): (Int, Int) = { (oldcord._1, oldcord._2 - 1) } }
sehirsig/malefiz
src/main/scala/de/htwg/se/malefiz/MalefizModule.scala
package de.htwg.se.malefiz import com.google.inject.AbstractModule import com.google.inject.name.Names import net.codingwell.scalaguice.ScalaModule import de.htwg.se.malefiz.controller.controllerComponent._ import de.htwg.se.malefiz.model.cellComponent.InvalidCell import de.htwg.se.malefiz.model.gameboardComponent.{GameboardInterface, lastSave, lastSaveInterface} import de.htwg.se.malefiz.model.gameboardComponent.gameboardBaseImpl.Gameboard import de.htwg.se.malefiz.model.fileIoComponent._ /** Dependency injection for our components. * * @author sehirsig & franzgajewski */ class MalefizModule extends AbstractModule with ScalaModule { val defaultSizeX:Int = 18 val defaultSizeY:Int = 19 val defaultLastDice = 0 val defaultLastWay = "" val defaultCell = InvalidCell override def configure():Unit = { bindConstant().annotatedWith(Names.named("DefaultSizeX")).to(defaultSizeX) bindConstant().annotatedWith(Names.named("DefaultSizeY")).to(defaultSizeY) bind[ControllerInterface].to[controllerBaseImpl.Controller] bind[GameboardInterface].toInstance(new Gameboard(defaultSizeX,defaultSizeY)) bind[lastSaveInterface].toInstance(new lastSave(defaultLastDice, defaultLastWay, defaultCell)) bind[FileIOInterface].to[fileIoJsonImpl.FileIO] } }
sehirsig/malefiz
src/main/scala/de/htwg/se/malefiz/model/gameboardComponent/gameboardBaseImpl/Gameboard.scala
package de.htwg.se.malefiz.model.gameboardComponent.gameboardBaseImpl import com.google.inject.Inject import de.htwg.se.malefiz.model.cellComponent._ import de.htwg.se.malefiz.model.gameboardComponent.GameboardInterface import de.htwg.se.malefiz.model.playerComponent.Player import de.htwg.se.malefiz.util.BlockStrategy import scala.util.{Failure, Success, Try} /** Base implementation of the game board. * * @author sehirsig & franzgajewski */ case class Gameboard(rows: Vector[Vector[Cell]]) extends GameboardInterface { /** Replace all cells according the the settings class. */ @Inject def this(sizex: Int, sizey: Int) = this(Vector.tabulate(sizex, sizey) { (row, col) => { if (Settings().blockedCells.contains(row, col)) { BlockedCell } else if (Settings().freeCells.contains(row, col)) { FreeCell } else if (Settings().secureCells.contains(row, col)) { SecureCell } else if (Settings().goalCell == (row, col)) { GoalCell } else if (Settings().start1.contains(row, col)) { Start1Cell } else if (Settings().start2.contains(row, col)) { Start2Cell } else if (Settings().start3.contains(row, col)) { Start3Cell } else if (Settings().start4.contains(row, col)) { Start4Cell } else { InvalidCell } } }) /** Initialization of the block strategy. */ var blockStrategy: BlockStrategy = BlockReplaceStrategy() /** Change of the block strategy. * * @param blockstrategy "remove" or "replace" */ override def setBlockStrategy(blockstrategy: String): Unit = { blockstrategy match { case "remove" => this.blockStrategy = BlockRemoveStrategy() case "replace" => this.blockStrategy = BlockReplaceStrategy() } } /** Function for handling barricades according to the block strategy. * * @param spielbrett old game board * @return new game board with changed blocking */ override def replaceBlocks(spielbrett: GameboardInterface): GameboardInterface = { blockStrategy.replaceBlock(spielbrett) } /** New game board in the dimensions given in the settings class. * * @return new game board */ override def newGBStandardSize: Gameboard = { new Gameboard(Settings().xDim, Settings().yDim) } /** Retrieve default size from the settings class. * * @return tupel of the default x and y dimensions of the game board */ override def getStandardXYsize: (Int,Int) = { (Settings().xDim, Settings().yDim) } /** Get name of cell (e.g. for JSON/XMY storage). * @param cell * * @return string representation of cell */ override def getStringOfCell(cell:Cell): String = { cell match { case FreeCell => "FreeCell" case BlockedCell => "BlockedCell" case Start1Cell => "Start1Cell" case Start2Cell =>"Start2Cell" case Start3Cell =>"Start3Cell" case Start4Cell =>"Start4Cell" case SecureCell =>"SecureCell" case GoalCell =>"GoalCell" case InvalidCell =>"InvalidCell" case PlayerCell(1) =>"PlayerCell1" case PlayerCell(2) =>"PlayerCell2" case PlayerCell(3) =>"PlayerCell3" case PlayerCell(4) =>"PlayerCell4" case _ => "InvalidCell" } } /** Returns a cell as coordinates of the game board. * * @param row x-coordinate of the matrix * @param col y-coordinate of the matric * @return cell at the given coordinates */ override def cell(row: Int, col: Int): Cell = rows(row)(col) /** Takes cell coordinates and returns corresponding string representation. * * @param row x coordinate * @param col y coordinate * * @return string representation of cell */ override def cellString(row: Int, col: Int): String = getStringOfCell(rows(row)(col)) //Bekomme die Stringdarstellung aus den Koordinaten. /** Change a cell on the game board. * * @param row x-coordinate of the matrix * @param col y-coordinate of the matric * @param cell cell to be replaced * @return new game board */ override def replaceCell(row: Int, col: Int, cell: Cell): Try[Gameboard] = { //Eine Zelle ersetzen mit Fehlerbehandlung. Try-Monade. Für Falsche Indexierung. val tmp = Try(copy(rows.updated(row, rows(row).updated(col, cell)))) tmp match { case Success(v) => Success(v) case Failure(e) => Failure(e) } } /** Move a player. * * @param coord coordinate as an int-tupel of the matrix * @param cell cell to be replaced * @return new game board */ override def movePlayer(coord: (Int, Int), cell: Cell): Gameboard = { copy(rows.updated(coord._1, rows(coord._1).updated(coord._2, cell))) } /** Move a cell. * * @param coord x and y coordinates * @param cell cell to be moved * @return new game board */ def moveCell(coord: (Int, Int), cell: Cell): Gameboard = { copy(rows.updated(coord._1, rows(coord._1).updated(coord._2, cell))) } /** Check, if walking up is legal and do so if possible. * * @param spielbrett old game board * @param player current player * @param currentCoord coordinates of current figure * @param figurenum number of figure * @param walksLeft number of remaining movements * * @return tuple of boolean to indicate whether the move was successful and the new game board */ override def walkUp(spielbrett: GameboardInterface, player: Player, currentCoord: (Int, Int), figurenum: Int, walksLeft: Int): (Boolean, GameboardInterface) = { checkCell.walkUp(spielbrett, player, currentCoord, figurenum, walksLeft) } /** Check, if walking down is legal and do so if possible. * * @param spielbrett old game board * @param player current player * @param currentCoord coordinates of current figure * @param figurenum number of figure * @param walksLeft number of remaining movements * * @return tuple of boolean to indicate whether the move was successful and the new game board */ override def walkDown(spielbrett: GameboardInterface, player: Player, currentCoord: (Int, Int), figurenum: Int, walksLeft: Int): (Boolean, GameboardInterface) = { checkCell.walkDown(spielbrett, player, currentCoord, figurenum, walksLeft) } /** Check, if walking left is legal and do so if possible. * * @param spielbrett old game board * @param player current player * @param currentCoord coordinates of current figure * @param figurenum number of figure * @param walksLeft number of remaining movements * * @return tuple of boolean to indicate whether the move was successful and the new game board */ override def walkLeft(spielbrett: GameboardInterface, player: Player, currentCoord: (Int, Int), figurenum: Int, walksLeft: Int): (Boolean, GameboardInterface) = { checkCell.walkLeft(spielbrett, player, currentCoord, figurenum, walksLeft) } /** Check, if walking right is legal and do so if possible. * * @param spielbrett old game board * @param player current player * @param currentCoord coordinates of current figure * @param figurenum number of figure * @param walksLeft number of remaining movements * * @return tuple of boolean to indicate whether the move was successful and the new game board */ override def walkRight(spielbrett: GameboardInterface, player: Player, currentCoord: (Int, Int), figurenum: Int, walksLeft: Int): (Boolean, GameboardInterface) = { checkCell.walkRight(spielbrett, player, currentCoord, figurenum, walksLeft) } /** Die roll. * * @return number from 1 to 6 */ override def diceRoll: Int = { Dice.diceRoll } /** Changes coordinates of a tupel as to go down one cell. * * @param oldcord tupel of old x and y coordinates * * @return tupel of new x and y coordinates */ override def goDown(oldcord: (Int, Int)): (Int, Int) = { moveTypes.goDown(oldcord) } /** Changes coordinates of a tupel as to go up one cell. * * @param oldcord tupel of old x and y coordinates * * @return tupel of new x and y coordinates */ override def goUp(oldcord: (Int, Int)): (Int, Int) = { moveTypes.goUp(oldcord) } /** Changes coordinates of a tupel as to go right one cell. * * @param oldcord tupel of old x and y coordinates * * @return tupel of new x and y coordinates */ override def goRight(oldcord: (Int, Int)): (Int, Int) = { moveTypes.goRight(oldcord) } /** Changes coordinates of a tupel as to go left one cell. * * @param oldcord tupel of old x and y coordinates * * @return tupel of new x and y coordinates */ override def goLeft(oldcord: (Int, Int)): (Int, Int) = { moveTypes.goLeft(oldcord) } /** Takes a string and returns the corresponding cell. * * @param name string representation of cell * * @return cell */ override def getCell(name: String): Cell = { name match { case "FreeCell" => FreeCell case "BlockedCell" => BlockedCell case "Start1Cell" => Start1Cell case "Start2Cell" => Start2Cell case "Start3Cell" => Start3Cell case "Start4Cell" => Start4Cell case "SecureCell" => SecureCell case "GoalCell" => GoalCell case "InvalidCell" => InvalidCell case "PlayerCell1" => PlayerCell(1) case "PlayerCell2" => PlayerCell(2) case "PlayerCell3" => PlayerCell(3) case "PlayerCell4" => PlayerCell(4) } } /** Checks if a player is on the goal. * * @return boolean */ def checkPlayerOnGoal: Boolean = { cell(Settings().goalCell._1, Settings().goalCell._2).isInstanceOf[PlayerCell] } /** Get coordinates of the base of the 1. player. * * @return tupel of x and y coordinates */ override def getP1Base: (Int,Int) = { Settings().start1.head } /** Get coordinates of the base of the 2. player. * * @return tupel of x and y coordinates */ override def getP2Base: (Int,Int) = { Settings().start2.head } /** Get coordinates of the base of the 3. player. * * @return tupel of x and y coordinates */ override def getP3Base: (Int,Int) = { Settings().start3.head } /** Get coordinates of the base of the 4. player. * * @return tupel of x and y coordinates */ override def getP4Base: (Int,Int) = { Settings().start4.head } /** Get coordinates of the goal cell. * * @return tupel of x and y coordinates */ override def getGoalBase: (Int,Int) = { Settings().goalCell } /** String representation of the game board. * * @return game board string */ override def toString: String = { val buf = new StringBuilder rows.foreach(x => buf ++= x.mkString + "\n") buf.toString } }
sehirsig/malefiz
src/test/scala/de/htwg/se/malefiz/model/gamefigureComponent/GamefigureSpec.scala
package de.htwg.se.malefiz.model.gamefigureComponent import de.htwg.se.malefiz.model.playerComponent.Player import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec /** Test class for the Gamefigure class. * * @author sehirsig & franzgajewski */ class GamefigureSpec extends AnyWordSpec with Matchers { "A Gamefigure" when { "new Player 1" should { val player = Player("<NAME>", 1, (1,1)) val figur = Gamefigure(1, 1, player, player.startingPos) "should unapply" in { Gamefigure.unapply(figur).get should be(1, 1, Player("Your Name", 1, (1,1)), player.startingPos) } "have a nice String representation" in { figur.toString should be("1 ") } "should return the Player" in { figur.getPlayer should be(player) } "should return the number" in { figur.getNumber should be(1) } "should give position" in { figur.pos should be((1,1)) } "should update position" in { val figur2 = figur.updatePos((2,2)) figur2.pos should be ((2,2)) } } } }
sehirsig/malefiz
src/test/scala/de/htwg/se/malefiz/model/playerComponent/PlayerSpec.scala
<reponame>sehirsig/malefiz package de.htwg.se.malefiz.model.playerComponent import de.htwg.se.malefiz.model.gamefigureComponent.Gamefigure import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec /** Test class for the Player class. * * @author sehirsig & franzgajewski */ class PlayerSpec extends AnyWordSpec with Matchers { "A Player 1" when { "new" should { val player = Player("Your Name", 1, (14,7)) "have a name" in { player.name should be("<NAME>") } "should unapply" in { Player.unapply(player).get should be("Your Name", 1, (14,7)) } "have a nice String representation" in { player.toString should be("1 Your Name") } "have a starting position" in { player.startingPos should be((14,7)) } "have no figure" in { player.figures should be(Array[Gamefigure]()) player.figures.length should be(0) } "have a figure" in { player.addFigure(1) player.figures.length should be(1) player.figures(0).pos should be((14,7)) } "should update figure position" in { player.figures(0) = player.figures(0).updatePos(15,7) player.figures(0).pos should be((15,7)) } } } }
sehirsig/malefiz
src/test/scala/de/htwg/se/malefiz/util/UndoManagerSpec.scala
package de.htwg.se.malefiz.util import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec /** Test class for the UndoManager class. * * @author sehirsig & franzgajewski */ class UndoManagerSpec extends AnyWordSpec with Matchers { "A UndoManager " should { val undoManager = new UndoManager "do a step in doStep" in { val cmd = new testCommand undoManager.doStep(cmd) cmd.saved should be(1) } "do a undo in undoStep" in { val cmd = new testCommand undoManager.doStep(cmd) undoManager.undoStep cmd.saved should be(0) } "do a redo in redoStep" in { val cmd = new testCommand undoManager.doStep(cmd) undoManager.undoStep undoManager.redoStep cmd.saved should be(1) } "has working Stacks" in { val cmd = new testCommand undoManager.doStep(cmd) undoManager.doStep(cmd) undoManager.doStep(cmd) undoManager.doStep(cmd) undoManager.doStep(cmd) undoManager.doStep(cmd) undoManager.undoStep undoManager.undoStep undoManager.undoStep undoManager.undoStep undoManager.undoStep undoManager.undoStep undoManager.undoStep undoManager.undoStep undoManager.undoStep undoManager.redoStep undoManager.redoStep undoManager.redoStep undoManager.redoStep undoManager.redoStep undoManager.redoStep undoManager.redoStep undoManager.redoStep undoManager.redoStep undoManager.redoStep undoManager.redoStep undoManager.redoStep undoManager.redoStep undoManager.redoStep undoManager.redoStep undoManager.redoStep cmd.saved should be(6) } } }
sehirsig/malefiz
src/test/scala/de/htwg/se/malefiz/model/gameboardComponent/gameboardBaseImpl/GameboardSpec.scala
package de.htwg.se.malefiz.model.gameboardComponent.gameboardBaseImpl import de.htwg.se.malefiz.model.cellComponent._ import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec import scala.util.{Failure, Success} /** Test class for the base implementation of the Gameboard class. * * @author sehirsig & franzgajewski */ class GameboardSpec extends AnyWordSpec with Matchers { "A Gameboard is the playingfield of Malefiz. A Gamebeoard" when { val settings = new Settings val spielbrett = new Gameboard(settings.yDim, settings.xDim) "created properly" should { val freeCells = Vector((2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (2, 10), (2, 11), (2, 12), (2, 13), (2, 14), (2, 15), (2, 16), (2, 17), (3, 1), (3, 17), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6), (4, 7), (4, 8), (4, 10), (4, 11), (4, 12), (4, 13), (4, 14), (4, 15), (4, 16), (4, 17), (6, 7), (6, 8), (6, 10), (6, 11), (7, 7), (7, 11), (8, 5), (8, 6), (8, 8), (8, 9), (8, 10), (8, 12), (8, 13), (9, 5), (9, 13), (10, 3), (10, 4), (10, 5), (10, 6), (10, 7), (10, 8), (10, 9), (10, 10), (10, 11), (10, 12), (10, 13), (10, 14), (10, 15), (11, 3), (11, 7), (11, 11), (11, 15), (12, 2), (12, 3), (12, 4), (12, 6), (12, 7), (12, 8), (12, 10), (12, 11), (12, 12), (12, 14), (12, 15), (12, 16)) val blockedCells = Vector((2, 9), (4, 9), (5, 9), (6, 9), (8, 7), (8, 11), (12, 1), (12, 5), (12, 9), (12, 13), (12, 17)) val secureCells = Vector((13, 1), (13, 5), (13, 9), (13, 13), (13, 17), (14, 1), (14, 2), (14, 3), (14, 4), (14, 5), (14, 6), (14, 7), (14, 8), (14, 9), (14, 10), (14, 11), (14, 12), (14, 13), (14, 14), (14, 15), (14, 16), (14, 17)) val goalCell = (1, 9) "should unapply" in { Gameboard.unapply(spielbrett).get should be(Vector.tabulate(Settings().yDim, Settings().xDim) { (row, col) => { if(Settings().blockedCells.contains(row, col)) { BlockedCell } else if (Settings().freeCells.contains(row, col)) { FreeCell } else if(Settings().secureCells.contains(row, col)) { SecureCell } else if((Settings().goalCell == (row, col))) { GoalCell } else if((Settings().start1.contains(row, col))) { Start1Cell } else if((Settings().start2.contains(row, col))) { Start2Cell } else if((Settings().start3.contains(row, col))) { Start3Cell } else if((Settings().start4.contains(row, col))) { Start4Cell } else { InvalidCell } } }) } "read the Cells with our String method" in { spielbrett.cell(1, 1) should be(InvalidCell) spielbrett.cell(2, 2) should be(FreeCell) spielbrett.cell(2, 9) should be(BlockedCell) spielbrett.cell(13, 1) should be(SecureCell) spielbrett.cell(1, 9) should be(GoalCell) spielbrett.cell(15, 15) should be(Start4Cell) spielbrett.cell(15, 11) should be(Start3Cell) spielbrett.cell(15, 7) should be(Start2Cell) spielbrett.cell(15, 3) should be(Start1Cell) } "read the Cells with Cells to String method" in { spielbrett.rows(1)(1).toString() should be(" ") spielbrett.rows(2)(2).toString() should be("O ") spielbrett.rows(2)(9).toString() should be("X ") spielbrett.rows(13)(1).toString() should be("O ") spielbrett.rows(1)(9).toString() should be("G ") spielbrett.rows(15)(15).toString() should be("T ") } "replace a Cell correctly and return a new Board" in { var newboard = spielbrett val returnedBoard = spielbrett.replaceCell(0, 0, BlockedCell) returnedBoard match { case Success(v) => newboard = v case Failure(f) => newboard } spielbrett.cell(0, 0) should be(InvalidCell) newboard.cell(0, 0) should be(BlockedCell) } "replace a Cell correctly with Tuple Coordinatesand return a new Board" in { val returnedBoard = spielbrett.movePlayer((0,0), BlockedCell) spielbrett.cell(0, 0) should be(InvalidCell) returnedBoard.cell(0, 0) should be(BlockedCell) } "build the exact String" in { spielbrett.toString should be (""" | G | O O O O O O O O X O O O O O O O O | O O | O O O O O O O O X O O O O O O O O | X | O O X O O | O O | O O X O O O X O O | O O | O O O O O O O O O O O O O | O O O O | X O O O X O O O X O O O X O O O X | O O O O O | O O O O O O O O O O O O O O O O O | T T T T | T T T T | T T T T T T T T T T T T | |""".stripMargin) } } "used in getStringOfCell Function" should { "return FreeCell" in { spielbrett.getStringOfCell(FreeCell) should be ("FreeCell") } "return BlockedCell" in { spielbrett.getStringOfCell(BlockedCell) should be ("BlockedCell") } "return Start1Cell" in { spielbrett.getStringOfCell(Start1Cell) should be ("Start1Cell") } "return Start2Cell" in { spielbrett.getStringOfCell(Start2Cell) should be ("Start2Cell") } "return Start3Cell" in { spielbrett.getStringOfCell(Start3Cell) should be ("Start3Cell") } "return Start4Cell" in { spielbrett.getStringOfCell(Start4Cell) should be ("Start4Cell") } "return SecureCell" in { spielbrett.getStringOfCell(SecureCell) should be ("SecureCell") } "return GoalCell" in { spielbrett.getStringOfCell(GoalCell) should be ("GoalCell") } "return InvalidCell" in { spielbrett.getStringOfCell(InvalidCell) should be ("InvalidCell") } "return PlayerCell1" in { spielbrett.getStringOfCell(PlayerCell(1)) should be ("PlayerCell1") } "return PlayerCell2" in { spielbrett.getStringOfCell(PlayerCell(2)) should be ("PlayerCell2") } "return PlayerCell3" in { spielbrett.getStringOfCell(PlayerCell(3)) should be ("PlayerCell3") } "return PlayerCell4" in { spielbrett.getStringOfCell(PlayerCell(4)) should be ("PlayerCell4") } "return Broke InvalidCell" in { spielbrett.getStringOfCell(PlayerCell(5)) should be ("InvalidCell") } } "used in other Functions" should { "cellString()" in { spielbrett.cellString(0,0) should be ("InvalidCell") } "replaceCell()" in { spielbrett.replaceCell(43,44, InvalidCell) should not be (spielbrett) } "moveCell()" in { spielbrett.moveCell((0,0), InvalidCell) should be (spielbrett) } "newGBStandardSize()" in { spielbrett.newGBStandardSize should be (new Gameboard(18,19)) } "in getP1Base" in { spielbrett.getP1Base should be (Settings().start1.head) } "in getP2Base" in { spielbrett.getP2Base should be (Settings().start2.head) } "in getP3Base" in { spielbrett.getP3Base should be (Settings().start3.head) } "in getP4Base" in { spielbrett.getP4Base should be (Settings().start4.head) } "in getGoalBase" in { spielbrett.getGoalBase should be (Settings().goalCell) } "in getCell(P1)" in { spielbrett.getCell("PlayerCell1") should be (PlayerCell(1)) } "in getCell(P2)" in { spielbrett.getCell("PlayerCell2") should be (PlayerCell(2)) } "in getCell(P3)" in { spielbrett.getCell("PlayerCell3") should be (PlayerCell(3)) } "in getCell(P4)" in { spielbrett.getCell("PlayerCell4") should be (PlayerCell(4)) } "in getCell(FreeCell)" in { spielbrett.getCell("FreeCell") should be (FreeCell) } "in getCell(BlockedCell)" in { spielbrett.getCell("BlockedCell") should be (BlockedCell) } "in getCell(SecureCell)" in { spielbrett.getCell("SecureCell") should be (SecureCell) } "in getCell(GoalCell)" in { spielbrett.getCell("GoalCell") should be (GoalCell) } "in getCell(InvalidCell)" in { spielbrett.getCell("InvalidCell") should be (InvalidCell) } } } }
sehirsig/malefiz
src/main/scala/de/htwg/se/malefiz/model/fileIoComponent/fileIoXmlImpl/FileIO.scala
<filename>src/main/scala/de/htwg/se/malefiz/model/fileIoComponent/fileIoXmlImpl/FileIO.scala package de.htwg.se.malefiz.model.fileIoComponent.fileIoXmlImpl import com.google.inject.Guice import net.codingwell.scalaguice.InjectorExtensions._ import de.htwg.se.malefiz.MalefizModule import de.htwg.se.malefiz.model.cellComponent.PlayerCell import de.htwg.se.malefiz.model.fileIoComponent.FileIOInterface import de.htwg.se.malefiz.model.gameComponent.Game import de.htwg.se.malefiz.model.gameboardComponent.GameboardInterface import scala.xml.{Elem, PrettyPrinter} /** XML implementation of the file IO. Saves current game state for later use. * Saves x and y dimension and all cells as well as their content. * The content is stored as a string and later recovered by Gameboard functions. * * @author sehirsig & franzgajewski */ class FileIO extends FileIOInterface{ override def load(game:Game): (GameboardInterface,Game) = { var gameboard: GameboardInterface = null val file = scala.xml.XML.loadFile("gameboard.xml") val injector = Guice.createInjector(new MalefizModule) gameboard = injector.instance[GameboardInterface] /** Game figure counter. */ var player1Fig = 0 var player2Fig = 0 var player3Fig = 0 var player4Fig = 0 val cellNodes = (file \\ "cell") for (cell <- cellNodes) { val row: Int = (cell \ "@row").text.toInt val col: Int = (cell \ "@col").text.toInt val value: String = cell.text.trim val endzelle = gameboard.getCell(value) gameboard = gameboard.movePlayer((row, col), endzelle) if (endzelle.isInstanceOf[PlayerCell]) { endzelle.cellStatus match { case "1 " => game.players(0).figures(player1Fig) = game.players(0).figures(player1Fig).updatePos(row,col); player1Fig += 1; case "2 " => game.players(1).figures(player2Fig) = game.players(1).figures(player2Fig).updatePos(row,col); player2Fig += 1; case "3 " => if (game.players.length > 2) { game.players(2).figures(player3Fig) = game.players(2).figures(player3Fig).updatePos(row,col); player3Fig += 1; } case "4 " => if (game.players.length > 3) { game.players(3).figures(player4Fig) = game.players(3).figures(player4Fig).updatePos(row,col); player4Fig += 1; } } } } (gameboard,game) } override def save(gameboard: GameboardInterface): Unit = saveString(gameboard) def saveXML(gameboard: GameboardInterface): Unit = { scala.xml.XML.save("gameboard.xml", gameboardToXml(gameboard)) } def saveString(gameboard: GameboardInterface): Unit = { import java.io._ val pw = new PrintWriter(new File("gameboard.xml")) val prettyPrinter = new PrettyPrinter(120, 4) val xml = prettyPrinter.format(gameboardToXml(gameboard)) pw.write(xml) pw.close } def gameboardToXml(gameboard: GameboardInterface): Elem = { <gameboard sizex={ gameboard.getStandardXYsize._1.toString } sizey={ gameboard.getStandardXYsize._2.toString }> { for { row <- 0 until gameboard.getStandardXYsize._1 col <- 0 until gameboard.getStandardXYsize._2 } yield cellToXml(gameboard, row, col) } </gameboard> } def cellToXml(gameboard: GameboardInterface, row: Int, col: Int): Elem = { <cell row={ row.toString } col={ col.toString }> { gameboard.cellString(row, col) } </cell> } }
sehirsig/malefiz
src/test/scala/de/htwg/se/malefiz/model/gameboardComponent/gameboardBaseImpl/checkCellSpec.scala
package de.htwg.se.malefiz.model.gameboardComponent.gameboardBaseImpl import de.htwg.se.malefiz.model.cellComponent.PlayerCell import de.htwg.se.malefiz.model.playerComponent.Player import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec /** Test class for base implementation of the checkCell class. * * @author sehirsig & franzgajewski */ class checkCellSpec extends AnyWordSpec with Matchers { "checkShell" when { var gb = new Gameboard(Settings().xDim, Settings().yDim) var player1 = Player("Erster", 1, (15, 3)) var player2 = Player("Zweiter", 2, (14, 5)) var player3 = Player("Dritter", 3, (14, 6)) var player4 = Player("Vierter", 4, (14, 7)) player1.addFigure(1) player1.addFigure(2) player1.addFigure(3) player1.addFigure(4) player1.addFigure(5) player2.addFigure(1) player3.addFigure(1) player4.addFigure(1) "walking up" should { "be true " in { checkCell.walkUp(gb, player1, (15, 3), 1, 2) should not be ((false, gb)) } "be false " in { checkCell.walkUp(gb, player1, (14, 3), 1, 2) should be ((false, gb)) } } "walking left" should { "be true " in { checkCell.walkLeft(gb, player1, (14, 3), 1, 2) should not be ((false, gb)) } "be false " in { checkCell.walkLeft(gb, player1, (1, 1), 1, 2) should be ((false, gb)) } } "walking right" should { "be true " in { checkCell.walkRight(gb, player1, (14, 3), 1, 2) should not be ((false, gb)) } "be false " in { checkCell.walkRight(gb, player1, (0, 0), 1, 2) should be ((false, gb)) } } "walking down" should { "be true " in { checkCell.walkDown(gb, player1, (12, 5), 1, 2) should not be ((false, gb)) } "be false " in { checkCell.walkDown(gb, player1, (0, 0), 1, 2) should be ((false, gb)) } } "is walkable" should { "be true " in { checkCell.isWalkable(gb, (2,2), 1, 1) should be (true) checkCell.isWalkable(gb, (14,3), 1, 1) should be (true) checkCell.isWalkable(checkCell.walkUp(gb, player1, (15,3), 1, 1)._2, (14,3), 1, 2) should be (true) checkCell.isWalkable(gb, (14,5), 1, 1) should be (true) checkCell.isWalkable(gb, (14,6), 1, 1) should be (true) checkCell.isWalkable(gb, (14,7), 1, 1) should be (true) /** auf Blocked Cell laufen (mit 1 Move Left) */ checkCell.isWalkable(gb, (2,9), 1, 1) should be (true) /** Ins Ziel laufen (mit 1 Move Left) */ checkCell.isWalkable(gb, (1,9), 1, 1) should be (true) gb = gb.moveCell((14,3), PlayerCell(2)) /** Spieler 1 läuft über Spieler 2 seine Figur */ checkCell.isWalkable(gb, (14,3), 2, 1) should be (true) /** Spieler 2 läuft über seine Figur */ checkCell.isWalkable(gb, (14,3), 2, 2) should be (true) gb = gb.moveCell((14,3), PlayerCell(3)) /** Spieler 3 läuft über seine Figur */ checkCell.isWalkable(gb, (14,3), 2, 2) should be (true) gb = gb.moveCell((14,3), PlayerCell(4)) /** Spieler 4 läuft über seine Figur */ checkCell.isWalkable(gb, (14,3), 2, 2) should be (true) } "be false " in { /** In Basis reinlaufen */ checkCell.isWalkable(gb, (15,3), 1, 1) should be (false) /** Nurnoch 1 zug und du würdest auf deiner eigenen Figur landen */ gb = gb.moveCell((14,3), PlayerCell(1)) checkCell.isWalkable(gb, (14,3), 1, 1) should be (false) } } "is getnextcell" should { "return the old gameboard" in { checkCell.getNextCell(gb, gb, (15,3), 1) should be (gb) checkCell.getNextCell(gb, gb, (15,3), 1) should be (gb) checkCell.getNextCell(gb, gb, (14,5), 2) should be (gb) checkCell.getNextCell(gb, gb, (14,6), 2) should be (gb) checkCell.getNextCell(gb, gb, (14,7), 2) should be (gb) checkCell.getNextCell(gb, gb, (2,9), 2) should be (gb) } } "replace the gameboard" should { "replace it" in { checkCell.replaceIt(gb,1,1) should not be (gb) } } } }
sehirsig/malefiz
src/main/scala/de/htwg/se/malefiz/model/playerComponent/Player.scala
package de.htwg.se.malefiz.model.playerComponent import de.htwg.se.malefiz.model.cellComponent.PlayerCell import de.htwg.se.malefiz.model.gamefigureComponent.Gamefigure /** Player class. * * @author sehirsig & franzgajewski */ case class Player(name: String, Playerid: Int, startingPos: (Int, Int)) { /** Define player's cell. */ val cell = PlayerCell(Playerid) var figures = Array[Gamefigure]() def addFigure(id: Int): Unit = { val figure = Gamefigure(figures.length, id, Player.this, startingPos) figures = figures :+ figure } override def toString: String = Playerid + " " + name }
sehirsig/malefiz
src/main/scala/de/htwg/se/malefiz/model/gameboardComponent/gameboardBaseImpl/BlockReplaceStrategy.scala
<gh_stars>1-10 package de.htwg.se.malefiz.model.gameboardComponent.gameboardBaseImpl import de.htwg.se.malefiz.model.cellComponent._ import de.htwg.se.malefiz.model.gameboardComponent.GameboardInterface import de.htwg.se.malefiz.util.BlockStrategy import scala.util.Random /** Blocked cell replace strategy of the strategy pattern. * Move barricade to a random legal location, when captured. * * @author sehirsig & franzgajewski */ case class BlockReplaceStrategy() extends BlockStrategy { override def replaceBlock(spielbrett: GameboardInterface): GameboardInterface = { val b = searchVectors(FreeCell, spielbrett.rows) val rnd = new Random() val randomNumber = rnd.nextInt(b.size - 1) val replace = b(randomNumber) spielbrett.movePlayer(replace, BlockedCell) } /** Determines legal cells to place a barricade. * * @param x legal cell type (FreeCell) * @param vec game board matrix * @return coordinates of legal cells */ private def searchVectors(x: Cell, vec: Vector[Vector[Cell]]): IndexedSeq[(Int,Int)] = for { i <- 0 until vec.size j <- 0 until vec(i).size if vec(i)(j) == x } yield (i, j) }
sehirsig/malefiz
src/main/scala/de/htwg/se/malefiz/model/gameboardComponent/gameboardStubImpl/Gameboard.scala
package de.htwg.se.malefiz.model.gameboardComponent.gameboardStubImpl import de.htwg.se.malefiz.model.cellComponent._ import de.htwg.se.malefiz.model.gameboardComponent.GameboardInterface import de.htwg.se.malefiz.model.playerComponent.Player import scala.util.{Failure, Success, Try} /** Stub implementation of the game board. * * @author sehirsig & franzgajewski */ case class Gameboard(rows: Vector[Vector[Cell]]) extends GameboardInterface { def this(sizex: Int, sizey: Int) = this(Vector.tabulate(sizex, sizey) { (row, col) => { FreeCell } }) override def setBlockStrategy(blockstrategy: String): Unit = {} override def movePlayer(coord: (Int, Int), cell: Cell): GameboardInterface = this override def cell(row: Int, col: Int): Cell = InvalidCell override def newGBStandardSize: GameboardInterface = this override def getStandardXYsize: (Int,Int) = (0,0) override def replaceBlocks(spielbrett: GameboardInterface): GameboardInterface = this override def walkUp(spielbrett: GameboardInterface, player: Player, currentCoord: (Int, Int), figurenum: Int, walksLeft: Int): (Boolean, GameboardInterface) = (false, this) override def walkDown(spielbrett: GameboardInterface, player: Player, currentCoord: (Int, Int), figurenum: Int, walksLeft: Int): (Boolean, GameboardInterface) = (false, this) override def walkLeft(spielbrett: GameboardInterface, player: Player, currentCoord: (Int, Int), figurenum: Int, walksLeft: Int): (Boolean, GameboardInterface) = (false, this) override def walkRight(spielbrett: GameboardInterface, player: Player, currentCoord: (Int, Int), figurenum: Int, walksLeft: Int): (Boolean, GameboardInterface) = (false, this) override def diceRoll: Int = 0 override def goDown(oldcord: (Int, Int)): (Int, Int) = (0,0) override def goUp(oldcord: (Int, Int)): (Int, Int) = (0,0) override def goRight(oldcord: (Int, Int)): (Int, Int) = (0,0) override def goLeft(oldcord: (Int, Int)): (Int, Int) = (0,0) override def getCell(name:String): Cell = InvalidCell override def checkPlayerOnGoal: Boolean = false override def cellString(row: Int, col: Int): String = "" override def getP1Base: (Int,Int) = (0,0) override def getP2Base: (Int,Int) = (0,0) override def getP3Base: (Int,Int) = (0,0) override def getP4Base: (Int,Int) = (0,0) override def getGoalBase: (Int,Int) = (0,0) def replaceCell(row: Int, col: Int, cell: Cell): Try[Gameboard] = { val tmp = Try(copy(rows.updated(row, rows(row).updated(col, cell)))) tmp match { case Success(v) => Success(v) case Failure(e) => Failure(e) } } override def getStringOfCell(cell:Cell): String = "" }
sehirsig/malefiz
src/test/scala/de/htwg/se/malefiz/controller/controllerComponent/controllerStubImpl/ControllerSpec.scala
package de.htwg.se.malefiz.controller.controllerComponent.controllerStubImpl import de.htwg.se.malefiz.model.cellComponent.InvalidCell import de.htwg.se.malefiz.model.gameboardComponent.gameboardStubImpl.Gameboard import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec /** Test class for the stub implementation of the controller. * * @author sehirsig & franzgajewski */ class ControllerSpec extends AnyWordSpec with Matchers { "A Mock Controller" when { var con = new Controller(new Gameboard(2, 2)) "should do nothing" should { "in gameStatus" in { con.gameStatus = con.gameStatus } "in playerStatus" in { con.playerStatus = con.playerStatus } "in moveCounter" in { con.moveCounter = 1 } "in builder" in { con.builder } "in game" in { con.game = con.game } "in gameWon" in { con.gameWon = (true,"") } "in savedGame" in { con.savedGame = con.savedGame } "in selectedFigNum" in { con.selectedFigNum = 1 } "in resetGame" in { con.resetGame() } "in selectFigure" in { con.selectFigure(0) } "in addPlayer" in { con.addPlayer() } "in addPlayerName" in { con.addPlayerName("") } "in startGame" in { con.startGame() } "in boardToString" in { con.boardToString() } "in rollDice" in { con.rollDice() } "in checkWin" in { con.checkWin() } "in setBlockStrategy" in { con.setBlockStrategy("") } "in emptyMan" in { con.emptyMan } "in undoAll" in { con.undoAll } "in undo" in { con.undo } "in redo" in { con.redo } "in move" in { con.move("",0) } "in getpureCell" in { con.getpureCell("") should be (InvalidCell) } "in setupGame" in { con.setupGame() } "in save" in { con.save } "in load" in { con.load } "in addPlayerDEBUGWINTEST" in { con.addPlayerDEBUGWINTEST("") } "in debugDice" in { con.debugDice } } } }
sehirsig/malefiz
src/main/scala/de/htwg/se/malefiz/model/gameboardComponent/gameboardBaseImpl/settings.scala
package de.htwg.se.malefiz.model.gameboardComponent.gameboardBaseImpl /** Settings class of the base implementation. Many default settings are stored here. * * @author sehirsig & franzgajewski */ case class Settings() { val xDim = 18 val yDim = 19 val freeCells = Vector((2,1),(2,2),(2,3),(2,4),(2,5),(2,6),(2,7),(2,8),(2,10),(2,11),(2,12),(2,13),(2,14),(2,15), (2,16),(2,17),(3,1),(3,17),(4,1),(4,2),(4,3),(4,4),(4,5),(4,6),(4,7),(4,8),(4,10),(4,11),(4,12),(4,13),(4,14), (4,15),(4,16),(4,17),(6,7),(6,8),(6,10),(6,11),(7,7),(7,11),(8,5),(8,6),(8,8),(8,9),(8,10),(8,12),(8,13),(9,5), (9,13),(10,3),(10,4),(10,5),(10,6),(10,7),(10,8),(10,9),(10,10),(10,11),(10,12),(10,13),(10,14),(10,15),(11,3), (11,7),(11,11),(11,15),(12,2),(12,3),(12,4),(12,6),(12,7),(12,8),(12,10),(12,11),(12,12),(12,14),(12,15),(12,16)) val start1 = Vector((15, 3),(16, 3), (17, 3), (17, 2), (17, 4)) val start2 = Vector((15, 7),(16, 7), (17, 7),(17, 6),(17, 8)) val start3 = Vector((15, 11),(16, 11),(17, 11),(17, 10),(17, 12)) val start4 = Vector((15, 15),(16, 15),(17, 15),(17, 14),(17, 16)) val blockedCells = Vector((2,9),(4,9),(5,9),(6,9),(8,7),(8,11),(12,1),(12,5),(12,9),(12,13),(12,17)) val secureCells = Vector((13,1),(13,5),(13,9),(13,13),(13,17),(14,1),(14,2),(14,3),(14,4),(14,5),(14,6),(14,7), (14,8),(14,9),(14,10),(14,11),(14,12),(14,13),(14,14),(14,15),(14,16),(14,17)) val goalCell = (1,9) val walkableCells = freeCells :: blockedCells :: secureCells :: goalCell :: Nil }
sehirsig/malefiz
src/main/scala/de/htwg/se/malefiz/model/gameboardComponent/gameboardBaseImpl/Dice.scala
package de.htwg.se.malefiz.model.gameboardComponent.gameboardBaseImpl import scala.util.Random /** Die for the base implementation. * Returns a number from 1 to 6. Returns -1 in case of an error. * Implemented as an option monad. * * @author sehirsig & franzgajewski */ object Dice { def diceRoll: Int = { val rnd: Option[Random] = Some(new Random()) rnd match { case Some(x) => x.nextInt(6) + 1 case None => -1 } } }
sehirsig/malefiz
src/main/scala/de/htwg/se/malefiz/model/gameboardComponent/lastSave.scala
<filename>src/main/scala/de/htwg/se/malefiz/model/gameboardComponent/lastSave.scala package de.htwg.se.malefiz.model.gameboardComponent import com.google.inject.Inject import de.htwg.se.malefiz.model.cellComponent.Cell /** The Information of the last move from the same player get saved here. * * @author sehirsig & franzgajewski */ case class lastSave @Inject()(lastFullDice: Int, lastDirectionOpposite: String, lastCell: Cell) extends lastSaveInterface { def updateLastFullDice(newNum: Int): lastSave = copy(newNum, lastDirectionOpposite, lastCell) def updateLastDirection(newDic: String): lastSave = copy(lastFullDice, newDic, lastCell) def updatelastCell(newCel: Cell): lastSave = copy(lastFullDice, lastDirectionOpposite, newCel) }
sehirsig/malefiz
src/test/scala/de/htwg/se/malefiz/controller/controllerComponent/controllerBaseImpl/ControllerSpec.scala
<filename>src/test/scala/de/htwg/se/malefiz/controller/controllerComponent/controllerBaseImpl/ControllerSpec.scala package de.htwg.se.malefiz.controller.controllerComponent.controllerBaseImpl import com.google.inject.Guice import de.htwg.se.malefiz.MalefizModule import de.htwg.se.malefiz.aview.{GameResetTUIState, MovingTUIState, TUI} import de.htwg.se.malefiz.controller.controllerComponent.GameStatus._ import de.htwg.se.malefiz.controller.controllerComponent.{PlayerState1, PlayerState2, PlayerState3, PlayerState4} import de.htwg.se.malefiz.model.cellComponent.{BlockedCell, PlayerCell} import de.htwg.se.malefiz.model.gameboardComponent.gameboardBaseImpl.{Gameboard, Settings} import de.htwg.se.malefiz.model.gameboardComponent.lastSaveInterface import net.codingwell.scalaguice.InjectorExtensions.ScalaInjector import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec /** Test class for the base implementation of the controller. * * @author sehirsig & franzgajewski */ class ControllerSpec extends AnyWordSpec with Matchers { "A Controller" when { "observed by an Observer with 4 Players" should { val set = Settings() val gameboard = new Gameboard(set.xDim, set.yDim) val controller = Controller(gameboard) "from the offset" in { controller.gameStatus should be(WELCOME) controller.playerStatus should be(PlayerState1) controller.moveCounter should be(0) } "get the pure Cell" in { controller.getpureCell("BlockedCell") should be (BlockedCell) } "change blockStrategy to replace" in { controller.setBlockStrategy("replace") controller.gameStatus should be(WELCOME) } "change blockStrategy to remove" in { controller.setBlockStrategy("remove") controller.gameStatus should be(WELCOME) } "when adding player" in { controller.addPlayerName("Eins") controller.game.getPlayerNumber() should be(1) controller.gameStatus should be(IDLE) } "when adding another player" in { controller.addPlayerName("Zwei") controller.game.getPlayerNumber() should be(2) controller.gameStatus should be(READY1) } "when adding 4 players" in { controller.addPlayerName("Drei") controller.addPlayerName("Vier") controller.game.getPlayerNumber() should be(4) controller.gameStatus should be(READY2) } "when adding more than 4 players" in { controller.addPlayer() controller.game.getPlayerNumber() should be(4) } "when starting game" in { controller.startGame() controller.gameStatus should be(PLAYING) controller.playerStatus should be(PlayerState1) } "when rolling dice" in { controller.rollDice() should (be(1) or be(2) or be(3) or be(4) or be(5) or be(6)) } "when as Player 1" in { controller.selectFigure(1) controller.moveCounter = 5 controller.move("w", 1) controller.move("w", 1) controller.move("w", 1) controller.move("d", 1) controller.move("undo", 1) controller.move("redo", 1) controller.move("undo", 1) controller.move("a", 1) controller.move("a", 1) controller.move("w", 1) controller.move("w", 1) controller.playerStatus should be(PlayerState2) } "when as Player 2" in { controller.rollDice() controller.selectFigure(1) controller.moveCounter = 5 controller.move("w", 1) controller.move("d", 1) controller.move("undo", 1) controller.move("redo", 1) controller.move("undo", 1) controller.move("a", 1) controller.move("a", 1) controller.move("w", 1) controller.move("w", 1) controller.playerStatus should be(PlayerState3) } "when as Player 3" in { controller.rollDice() controller.selectFigure(1) controller.moveCounter = 5 controller.move("w", 1) controller.move("d", 1) controller.move("undo", 1) controller.move("redo", 1) controller.move("undo", 1) controller.move("a", 1) controller.move("a", 1) controller.move("w", 1) controller.move("w", 1) controller.playerStatus should be(PlayerState4) } "when as Player 4" in { controller.rollDice() controller.selectFigure(1) controller.moveCounter = 5 controller.move("w", 1) controller.move("d", 1) controller.move("undo", 1) controller.move("redo", 1) controller.move("undo", 1) controller.move("a", 1) controller.move("a", 1) controller.move("w", 1) controller.move("w", 1) controller.playerStatus should be(PlayerState1) } "when as Player 1 2nd Move" in { controller.rollDice() controller.selectFigure(1) controller.moveCounter = 5 controller.move("s", 1) controller.move("skip", 1) controller.playerStatus should be(PlayerState2) } "when as Player 2 2nd Move" in { controller.rollDice() controller.selectFigure(1) controller.moveCounter = 5 controller.move("s", 1) controller.move("skip", 1) controller.playerStatus should be(PlayerState3) } "when as Player 3 2nd Move" in { controller.rollDice() controller.selectFigure(1) controller.moveCounter = 5 controller.move("s", 1) controller.move("skip", 1) controller.playerStatus should be(PlayerState4) } "when as Player 4 2nd Move" in { controller.rollDice() controller.selectFigure(1) controller.moveCounter = 5 controller.move("s", 1) controller.move("skip", 1) controller.playerStatus should be(PlayerState1) } "when as Player 1 3rd Move" in { controller.rollDice() controller.selectFigure(1) controller.moveCounter = 6 controller.move("s", 1) controller.move("s", 1) controller.move("d", 1) controller.move("d", 1) controller.move("d", 1) controller.move("d", 1) controller.playerStatus should be(PlayerState2) } "when as Player 2 3rd Move" in { controller.rollDice() controller.selectFigure(1) controller.moveCounter = 1 controller.move("s", 1) controller.playerStatus should be(PlayerState3) } } "observed by an Observer with 3 Players" should { val set = Settings() val gameboard = new Gameboard(set.xDim, set.yDim) val controller = Controller(gameboard) "from the offset" in { controller.gameStatus should be(WELCOME) controller.playerStatus should be(PlayerState1) controller.moveCounter should be(0) } "change blockStrategy to replace" in { controller.setBlockStrategy("replace") controller.gameStatus should be(WELCOME) } "change blockStrategy to remove" in { controller.setBlockStrategy("remove") controller.gameStatus should be(WELCOME) } "when adding player" in { controller.addPlayerName("Eins") controller.game.getPlayerNumber() should be(1) controller.gameStatus should be(IDLE) } "when adding another player" in { controller.addPlayerName("Zwei") controller.game.getPlayerNumber() should be(2) controller.gameStatus should be(READY1) } "when adding 3 players" in { controller.addPlayerName("Drei") controller.game.getPlayerNumber() should be(3) controller.gameStatus should be(READY1) } "when starting game" in { controller.startGame() controller.gameStatus should be(PLAYING) controller.playerStatus should be(PlayerState1) } "when rolling dice" in { controller.rollDice() should (be(1) or be(2) or be(3) or be(4) or be(5) or be(6)) } "when as Player 1" in { controller.selectFigure(1) controller.moveCounter = 5 controller.move("w", 1) controller.move("w", 1) controller.move("w", 1) controller.move("d", 1) controller.move("undo", 1) controller.move("redo", 1) controller.move("undo", 1) controller.move("a", 1) controller.move("a", 1) controller.move("w", 1) controller.move("w", 1) controller.playerStatus should be(PlayerState2) } "when as Player 2" in { controller.rollDice() controller.selectFigure(1) controller.moveCounter = 5 controller.move("w", 1) controller.move("d", 1) controller.move("undo", 1) controller.move("redo", 1) controller.move("undo", 1) controller.move("a", 1) controller.move("a", 1) controller.move("w", 1) controller.move("w", 1) controller.playerStatus should be(PlayerState3) } "when as Player 3" in { controller.rollDice() controller.selectFigure(1) controller.moveCounter = 5 controller.move("w", 1) controller.move("d", 1) controller.move("undo", 1) controller.move("redo", 1) controller.move("undo", 1) controller.move("a", 1) controller.move("a", 1) controller.move("w", 1) controller.move("w", 1) controller.playerStatus should be(PlayerState1) } "when as Player 1 2nd Move" in { controller.rollDice() controller.selectFigure(1) controller.moveCounter = 5 controller.move("s", 1) controller.move("skip", 1) controller.playerStatus should be(PlayerState2) } "when as Player 2 2nd Move" in { controller.rollDice() controller.selectFigure(1) controller.moveCounter = 5 controller.move("s", 1) controller.move("skip", 1) controller.playerStatus should be(PlayerState3) } "when as Player 3 2nd Move" in { controller.rollDice() controller.selectFigure(1) controller.moveCounter = 5 controller.move("s", 1) controller.move("skip", 1) controller.playerStatus should be(PlayerState1) } "when as Player 1 3rd Move" in { controller.rollDice() controller.selectFigure(1) controller.moveCounter = 6 controller.move("s", 1) controller.move("s", 1) controller.move("d", 1) controller.move("d", 1) controller.move("d", 1) controller.move("d", 1) controller.playerStatus should be(PlayerState2) } "when as Player 2 3rd Move" in { controller.rollDice() controller.selectFigure(1) controller.moveCounter = 1 controller.move("s", 1) controller.playerStatus should be(PlayerState3) } } "observed by an Observer with 2 Players" should { val set = Settings() val gameboard = new Gameboard(set.xDim, set.yDim) val controller = Controller(gameboard) "from the offset" in { controller.gameStatus should be(WELCOME) controller.playerStatus should be(PlayerState1) controller.moveCounter should be(0) } "change blockStrategy to replace" in { controller.setBlockStrategy("replace") controller.gameStatus should be(WELCOME) } "change blockStrategy to remove" in { controller.setBlockStrategy("remove") controller.gameStatus should be(WELCOME) } "when adding player" in { controller.addPlayerName("Eins") controller.game.getPlayerNumber() should be(1) controller.gameStatus should be(IDLE) } "when adding another player" in { controller.addPlayerName("Zwei") controller.game.getPlayerNumber() should be(2) controller.gameStatus should be(READY1) } "when starting game" in { controller.startGame() controller.gameStatus should be(PLAYING) controller.playerStatus should be(PlayerState1) } "when rolling dice" in { controller.rollDice() should (be(1) or be(2) or be(3) or be(4) or be(5) or be(6)) } "when as Player 1" in { controller.selectFigure(1) controller.moveCounter = 4 controller.move("w", 1) controller.move("w", 1) controller.move("w", 1) controller.move("a", 1) controller.move("undo", 1) controller.move("redo", 1) controller.move("undo", 1) controller.move("d", 1) controller.move("d", 1) controller.move("w", 1) controller.playerStatus should be(PlayerState2) } "when as Player 2" in { controller.rollDice() controller.selectFigure(1) controller.moveCounter = 5 controller.move("w", 1) controller.move("d", 1) controller.move("undo", 1) controller.move("redo", 1) controller.move("undo", 1) controller.move("a", 1) controller.move("a", 1) controller.move("w", 1) controller.move("w", 1) controller.playerStatus should be(PlayerState1) } "when as Player 1 2nd Move kick" in { controller.rollDice() controller.selectFigure(1) controller.moveCounter = 1 controller.move("w", 1) controller.playerStatus should be(PlayerState2) } "when as Player 2 2nd Move" in { controller.rollDice() controller.selectFigure(1) controller.moveCounter = 5 controller.move("w", 1) controller.move("skip", 1) controller.playerStatus should be(PlayerState1) } "when as Player 1 3rd Move" in { controller.rollDice() controller.selectFigure(1) controller.moveCounter = 6 controller.move("s", 1) controller.move("s", 1) controller.move("d", 1) controller.move("d", 1) controller.move("d", 1) controller.move("d", 1) controller.playerStatus should be(PlayerState2) } "when as Player 2 3rd Move" in { controller.rollDice() controller.selectFigure(1) controller.moveCounter = 1 controller.move("w", 1) controller.playerStatus should be(PlayerState1) } "when Player 2 Wins" in { controller.gameboard = controller.gameboard.movePlayer((1,9), PlayerCell(2)) controller.checkWin() controller.gameWon should be (true,"Zwei") } "when Player 2 Fin but not Won" in { controller.gameWon = (false, "") controller.moveCounter = 0 controller.move("p", 1) } "save a gameboard" in { controller.save } "load a gameboard" in { controller.load } "reset a game" in { val injector = Guice.createInjector(new MalefizModule) val saGe = injector.instance[lastSaveInterface] controller.resetGame() controller.gameStatus should be (WELCOME) controller.savedGame should be (saGe) controller.gameWon should be (false,"") controller.selectedFigNum should be (0) controller.playerStatus should be (PlayerState1) } "create Debug Player 1" in { controller.addPlayerDEBUGWINTEST("Eins") } "create Debug Player 2" in { controller.addPlayerDEBUGWINTEST("Zwei") } "create Debug Player 3" in { controller.addPlayerDEBUGWINTEST("Drei") } "create Debug Player 4" in { controller.addPlayerDEBUGWINTEST("Vier") } "Use the debugDice" in { controller.debugDice() controller.moveCounter should be (1) } } } }
sehirsig/malefiz
src/main/scala/de/htwg/se/malefiz/util/Command.scala
<reponame>sehirsig/malefiz package de.htwg.se.malefiz.util /** Command pattern interface. * * @author sehirsig & franzgajewski */ trait Command { /** Do one step. */ def doStep:Unit /** Undo one step. */ def undoStep:Unit /** Redo one step. */ def redoStep:Unit }
sehirsig/malefiz
src/main/scala/de/htwg/se/malefiz/controller/controllerComponent/PlayerState.scala
<filename>src/main/scala/de/htwg/se/malefiz/controller/controllerComponent/PlayerState.scala package de.htwg.se.malefiz.controller.controllerComponent /** State pattern for the management of which players turn is next. * * @author sehirsig & franzgajewski */ trait PlayerState { def nextPlayer(playerCount:Int): PlayerState def getCurrentPlayer: Int } object PlayerState1 extends PlayerState { override def nextPlayer(playerCount:Int): PlayerState = PlayerState2 override def getCurrentPlayer: Int = 1 } object PlayerState2 extends PlayerState { override def nextPlayer(playerCount:Int): PlayerState = { if(playerCount < 3) { PlayerState1 } else { PlayerState3 } } override def getCurrentPlayer: Int = 2 } object PlayerState3 extends PlayerState { override def nextPlayer(playerCount:Int): PlayerState = { if(playerCount < 4) { PlayerState1 } else { PlayerState4 } } override def getCurrentPlayer: Int = 3 } object PlayerState4 extends PlayerState { override def nextPlayer(playerCount:Int): PlayerState = PlayerState1 override def getCurrentPlayer: Int = 4 }
sehirsig/malefiz
src/main/scala/de/htwg/se/malefiz/aview/TUI.scala
<reponame>sehirsig/malefiz package de.htwg.se.malefiz.aview import de.htwg.se.malefiz.controller.controllerComponent._ import scala.swing.Reactor /** Malefiz as text-based user interface. Game gets displayed in the console. * * @author sehirsig & franzgajewski */ case class TUI(controller: ControllerInterface) extends Reactor { listenTo(controller) /** Initialising of the current state. */ var currentState:TUIState = IdleTUIState def processing(input: String): Unit = { currentState = currentState.processing(input: String) } reactions += { case event: RollDice => printTui; currentState = PlayingTUIState case event: Moving => printTui;currentState = MovingTUIState case event: ChooseFig => printStatus;currentState = ChooseGameFigTUIState case event: SettingUp => printStatus case event: StartUp => printStatus case event: StartGame => printStatus; currentState = PlayingTUIState case event: WonGame => printTui; currentState = WinnerTUIState; currentState.processing("") case event: GameReset => printStatus; currentState = IdleTUIState case event: GameSaved => printStatus; case event: GameLoaded => printStatus } /** Prints the game board. */ def printTui: Unit = { println(controller.boardToString()) println(GameStatus.gameMessage(controller.gameStatus)) } /** Prints the game state. */ def printStatus: Unit = { println(GameStatus.gameMessage(controller.gameStatus)) } }
sehirsig/malefiz
src/main/scala/de/htwg/se/malefiz/controller/controllerComponent/controllerBaseImpl/MoveCommand.scala
package de.htwg.se.malefiz.controller.controllerComponent.controllerBaseImpl import de.htwg.se.malefiz.model.cellComponent._ import de.htwg.se.malefiz.util.Command /** Manages each individual movement. * Via the command pattern moves can be undone and redone. * * @author sehirsig & franzgajewski */ class MoveCommand(direction:String, figurenum:Int, controllerH: Controller) extends Command { /** Saves game board. */ var savedG = controllerH.gameboard /** Counts remaining turns. */ var savedMC = controllerH.moveCounter /** Game state. */ var savedSt = controllerH.gameStatus /** Information on the last move. */ var savedSG = controllerH.savedGame /** "Game" saves the players. */ var savedGM = controllerH.game //Saving game figures //<editor-fold desc="Gamefigure Saves"> var savedF1 = controllerH.game.players(0).figures(0) var savedF2 = controllerH.game.players(0).figures(1) var savedF3 = controllerH.game.players(0).figures(2) var savedF4 = controllerH.game.players(0).figures(3) var savedF5 = controllerH.game.players(0).figures(4) var savedF6 = controllerH.game.players(1).figures(0) var savedF7 = controllerH.game.players(1).figures(1) var savedF8 = controllerH.game.players(1).figures(2) var savedF9 = controllerH.game.players(1).figures(3) var savedF10 = controllerH.game.players(1).figures(4) var savedF11 = controllerH.game.players(0).figures(0) var savedF12 = controllerH.game.players(0).figures(1) var savedF13 = controllerH.game.players(0).figures(2) var savedF14 = controllerH.game.players(0).figures(3) var savedF15 = controllerH.game.players(0).figures(4) var savedF16 = controllerH.game.players(1).figures(0) var savedF17 = controllerH.game.players(1).figures(1) var savedF18 = controllerH.game.players(1).figures(2) var savedF19 = controllerH.game.players(1).figures(3) var savedF20 = controllerH.game.players(1).figures(4) controllerH.game.players.length match { case 2 => {} case 3 => { savedF11 = controllerH.game.players(2).figures(0) savedF12 = controllerH.game.players(2).figures(1) savedF13 = controllerH.game.players(2).figures(2) savedF14 = controllerH.game.players(2).figures(3) savedF15 = controllerH.game.players(2).figures(4) } case 4 => { savedF11 = controllerH.game.players(2).figures(0) savedF12 = controllerH.game.players(2).figures(1) savedF13 = controllerH.game.players(2).figures(2) savedF14 = controllerH.game.players(2).figures(3) savedF15 = controllerH.game.players(2).figures(4) savedF16 = controllerH.game.players(3).figures(0) savedF18 = controllerH.game.players(3).figures(1) savedF17 = controllerH.game.players(3).figures(2) savedF19 = controllerH.game.players(3).figures(3) savedF20 = controllerH.game.players(3).figures(4) } } //</editor-fold> override def doStep: Unit = { /** Boolean indicates whether move was legal and successful. */ var sucInp:Boolean = false /** Select current player. */ val currentplayer = controllerH.game.players(controllerH.playerStatus.getCurrentPlayer - 1) /** Select current game figure. */ val currentfigure = currentplayer.figures(figurenum-1) /** Coordinates of the current game figure. */ val fig_coord = (currentfigure.pos._1, currentfigure.pos._2) /** Initialization of the last cell (which will be replaced in the next step). */ var lastCell:Cell = InvalidCell /** Tupel the Boolean and the new game board. */ var savetuple = (sucInp, controllerH.gameboard) /** New position of the game figure. */ var newpos = fig_coord direction match { case "w" => { /** Returns TRUE, if walking worked and saves game board. */ savetuple = savedG.walkUp(controllerH.gameboard, currentplayer, fig_coord, figurenum-1, controllerH.moveCounter)} /** Saves last cell to replace it afterwards. */ lastCell = savedG.cell(savedG.goUp(fig_coord)._1, savedG.goUp(fig_coord)._2) /** Saves newposition to look for player kick. */ newpos = savedG.goUp(fig_coord) case "a" => { savetuple = savedG.walkLeft(controllerH.gameboard, currentplayer, fig_coord, figurenum-1, controllerH.moveCounter)} lastCell = savedG.cell(savedG.goLeft(fig_coord)._1, savedG.goLeft(fig_coord)._2) newpos = savedG.goLeft(fig_coord) case "s" => { savetuple = savedG.walkDown(controllerH.gameboard, currentplayer, fig_coord, figurenum-1, controllerH.moveCounter)} lastCell = savedG.cell(savedG.goDown(fig_coord)._1, savedG.goDown(fig_coord)._2) newpos = savedG.goDown(fig_coord) case "d" => { savetuple = savedG.walkRight(controllerH.gameboard, currentplayer, fig_coord, figurenum-1, controllerH.moveCounter)} lastCell = savedG.cell(savedG.goRight(fig_coord)._1, savedG.goRight(fig_coord)._2) newpos = savedG.goRight(fig_coord) case _ => } /** If 0, kick player. */ if ((controllerH.moveCounter - 1) == 0) { controllerH.game.players.map(b => b.figures.map(k => { /** Reset position of the figure of the kicked player to starting position. */ if (((k.pos._1, k.pos._2) == newpos) && (k.player != currentplayer)) { k.player.figures(k.getNumber) = k.player.figures(k.getNumber).updatePos(k.player.startingPos) controllerH.gameboard = controllerH.gameboard.movePlayer(k.player.startingPos, k.player.cell) } })) } /** Boolean indicates if move was successful. */ sucInp = savetuple._1 /** Newgame board. */ controllerH.gameboard = savetuple._2 if(sucInp) { controllerH.moveCounter -= 1 /** Lock the reverse direction to avoid players shuffling between two cells. */ direction match { case "w" => controllerH.savedGame = controllerH.savedGame.updateLastDirection("s") case "s" => controllerH.savedGame = controllerH.savedGame.updateLastDirection("w") case "a" => controllerH.savedGame = controllerH.savedGame.updateLastDirection("d") case "d" => controllerH.savedGame = controllerH.savedGame.updateLastDirection("a") } /** If traversing over another game figure, repaint that one. */ if (controllerH.savedGame.lastCell.isInstanceOf[PlayerCell]) { controllerH.gameboard = controllerH.gameboard.movePlayer(fig_coord, controllerH.savedGame.lastCell) } controllerH.savedGame = controllerH.savedGame.updatelastCell(lastCell) } else { /** When illegal move, reset turn and start over. */ controllerH.undoAll direction match { case "skip" => controllerH.moveCounter = 0 case _ => } } /** When last move, initiate next player's turn. */ if(controllerH.moveCounter < 1) { controllerH.playerStatus = controllerH.playerStatus.nextPlayer(controllerH.game.getPlayerNumber()) /** Empty the undo manager to be able to completetly reset it when moved into wrong direction. */ controllerH.emptyMan controllerH.savedGame = controllerH.savedGame.updateLastDirection("") controllerH.savedGame = controllerH.savedGame.updatelastCell(InvalidCell) } } override def undoStep: Unit = { val newsavedG = controllerH.gameboard val newsavedMC = controllerH.moveCounter val newsavedSt = controllerH.gameStatus val newsavedSG = controllerH.savedGame val newsavedGM = controllerH.game //Saving game figures //<editor-fold desc="Gamefigure Saves"> var newsavedF1 = controllerH.game.players(0).figures(0) var newsavedF2 = controllerH.game.players(0).figures(1) var newsavedF3 = controllerH.game.players(0).figures(2) var newsavedF4 = controllerH.game.players(0).figures(3) var newsavedF5 = controllerH.game.players(0).figures(4) var newsavedF6 = controllerH.game.players(1).figures(0) var newsavedF7 = controllerH.game.players(1).figures(1) var newsavedF8 = controllerH.game.players(1).figures(2) var newsavedF9 = controllerH.game.players(1).figures(3) var newsavedF10 = controllerH.game.players(1).figures(4) var newsavedF11 = controllerH.game.players(0).figures(0) var newsavedF12 = controllerH.game.players(0).figures(1) var newsavedF13 = controllerH.game.players(0).figures(2) var newsavedF14 = controllerH.game.players(0).figures(3) var newsavedF15 = controllerH.game.players(0).figures(4) var newsavedF16 = controllerH.game.players(1).figures(0) var newsavedF17 = controllerH.game.players(1).figures(1) var newsavedF18 = controllerH.game.players(1).figures(2) var newsavedF19 = controllerH.game.players(1).figures(3) var newsavedF20 = controllerH.game.players(1).figures(4) controllerH.game.players.length match { case 2 => {} case 3 => { newsavedF11 = controllerH.game.players(2).figures(0) newsavedF12 = controllerH.game.players(2).figures(1) newsavedF13 = controllerH.game.players(2).figures(2) newsavedF14 = controllerH.game.players(2).figures(3) newsavedF15 = controllerH.game.players(2).figures(4) } case 4 => { newsavedF11 = controllerH.game.players(2).figures(0) newsavedF12 = controllerH.game.players(2).figures(1) newsavedF13 = controllerH.game.players(2).figures(2) newsavedF14 = controllerH.game.players(2).figures(3) newsavedF15 = controllerH.game.players(2).figures(4) newsavedF16 = controllerH.game.players(3).figures(0) newsavedF18 = controllerH.game.players(3).figures(1) newsavedF17 = controllerH.game.players(3).figures(2) newsavedF19 = controllerH.game.players(3).figures(3) newsavedF20 = controllerH.game.players(3).figures(4) } } //</editor-fold> controllerH.gameboard = savedG controllerH.moveCounter = savedMC controllerH.gameStatus = savedSt controllerH.savedGame = savedSG controllerH.game = savedGM //Loading game figures //<editor-fold desc="Gamefigure Loads"> controllerH.game.players(0).figures(0) = savedF1 controllerH.game.players(0).figures(1) = savedF2 controllerH.game.players(0).figures(2) = savedF3 controllerH.game.players(0).figures(3) = savedF4 controllerH.game.players(0).figures(4) = savedF5 controllerH.game.players(1).figures(0) = savedF6 controllerH.game.players(1).figures(1) = savedF7 controllerH.game.players(1).figures(2) = savedF8 controllerH.game.players(1).figures(3) = savedF9 controllerH.game.players(1).figures(4) = savedF10 controllerH.game.players.length match { case 2 => {} case 3 => { controllerH.game.players(2).figures(0) = savedF11 controllerH.game.players(2).figures(1) = savedF12 controllerH.game.players(2).figures(2) = savedF13 controllerH.game.players(2).figures(3) = savedF14 controllerH.game.players(2).figures(4) = savedF15 } case 4 => { controllerH.game.players(2).figures(0) = savedF11 controllerH.game.players(2).figures(1) = savedF12 controllerH.game.players(2).figures(2) = savedF13 controllerH.game.players(2).figures(3) = savedF14 controllerH.game.players(2).figures(4) = savedF15 controllerH.game.players(3).figures(0) = savedF16 controllerH.game.players(3).figures(1) = savedF17 controllerH.game.players(3).figures(2) = savedF18 controllerH.game.players(3).figures(3) = savedF19 controllerH.game.players(3).figures(4) = savedF20 } } //</editor-fold> savedG = newsavedG savedMC = newsavedMC savedSt = newsavedSt savedSG = newsavedSG savedGM = newsavedGM //Saving game figures //<editor-fold desc="Gamefigure Saves"> savedF1 = newsavedF1 savedF2 = newsavedF2 savedF3 = newsavedF3 savedF4 = newsavedF4 savedF5 = newsavedF5 savedF6 = newsavedF6 savedF7 = newsavedF7 savedF8 = newsavedF8 savedF9 = newsavedF9 savedF10 = newsavedF10 controllerH.game.players.length match { case 2 => {} case 3 => { savedF11 = newsavedF11 savedF12 = newsavedF12 savedF13 = newsavedF13 savedF14 = newsavedF14 savedF15 = newsavedF15 } case 4 => { savedF11 = newsavedF11 savedF12 = newsavedF12 savedF13 = newsavedF13 savedF14 = newsavedF14 savedF15 = newsavedF15 savedF16 = newsavedF16 savedF18 = newsavedF17 savedF17 = newsavedF18 savedF19 = newsavedF19 savedF20 = newsavedF20 } } //</editor-fold> } override def redoStep: Unit = { val newsavedG = controllerH.gameboard val newsavedMC = controllerH.moveCounter val newsavedSt = controllerH.gameStatus val newsavedSG = controllerH.savedGame val newsavedGM = controllerH.game //Saving game figures //<editor-fold desc="Gamefigure Saves"> var newsavedF1 = controllerH.game.players(0).figures(0) var newsavedF2 = controllerH.game.players(0).figures(1) var newsavedF3 = controllerH.game.players(0).figures(2) var newsavedF4 = controllerH.game.players(0).figures(3) var newsavedF5 = controllerH.game.players(0).figures(4) var newsavedF6 = controllerH.game.players(1).figures(0) var newsavedF7 = controllerH.game.players(1).figures(1) var newsavedF8 = controllerH.game.players(1).figures(2) var newsavedF9 = controllerH.game.players(1).figures(3) var newsavedF10 = controllerH.game.players(1).figures(4) var newsavedF11 = controllerH.game.players(0).figures(0) var newsavedF12 = controllerH.game.players(0).figures(1) var newsavedF13 = controllerH.game.players(0).figures(2) var newsavedF14 = controllerH.game.players(0).figures(3) var newsavedF15 = controllerH.game.players(0).figures(4) var newsavedF16 = controllerH.game.players(1).figures(0) var newsavedF17 = controllerH.game.players(1).figures(1) var newsavedF18 = controllerH.game.players(1).figures(2) var newsavedF19 = controllerH.game.players(1).figures(3) var newsavedF20 = controllerH.game.players(1).figures(4) controllerH.game.players.length match { case 2 => {} case 3 => { newsavedF11 = controllerH.game.players(2).figures(0) newsavedF12 = controllerH.game.players(2).figures(1) newsavedF13 = controllerH.game.players(2).figures(2) newsavedF14 = controllerH.game.players(2).figures(3) newsavedF15 = controllerH.game.players(2).figures(4) } case 4 => { newsavedF11 = controllerH.game.players(2).figures(0) newsavedF12 = controllerH.game.players(2).figures(1) newsavedF13 = controllerH.game.players(2).figures(2) newsavedF14 = controllerH.game.players(2).figures(3) newsavedF15 = controllerH.game.players(2).figures(4) newsavedF16 = controllerH.game.players(3).figures(0) newsavedF18 = controllerH.game.players(3).figures(1) newsavedF17 = controllerH.game.players(3).figures(2) newsavedF19 = controllerH.game.players(3).figures(3) newsavedF20 = controllerH.game.players(3).figures(4) } } //</editor-fold> controllerH.gameboard = savedG controllerH.moveCounter = savedMC controllerH.gameStatus = savedSt controllerH.savedGame = savedSG controllerH.game = savedGM //Loading game figures //<editor-fold desc="Gamefigure Loads"> controllerH.game.players(0).figures(0) = savedF1 controllerH.game.players(0).figures(1) = savedF2 controllerH.game.players(0).figures(2) = savedF3 controllerH.game.players(0).figures(3) = savedF4 controllerH.game.players(0).figures(4) = savedF5 controllerH.game.players(1).figures(0) = savedF6 controllerH.game.players(1).figures(1) = savedF7 controllerH.game.players(1).figures(2) = savedF8 controllerH.game.players(1).figures(3) = savedF9 controllerH.game.players(1).figures(4) = savedF10 controllerH.game.players.length match { case 2 => {} case 3 => { controllerH.game.players(2).figures(0) = savedF11 controllerH.game.players(2).figures(1) = savedF12 controllerH.game.players(2).figures(2) = savedF13 controllerH.game.players(2).figures(3) = savedF14 controllerH.game.players(2).figures(4) = savedF15 } case 4 => { controllerH.game.players(2).figures(0) = savedF11 controllerH.game.players(2).figures(1) = savedF12 controllerH.game.players(2).figures(2) = savedF13 controllerH.game.players(2).figures(3) = savedF14 controllerH.game.players(2).figures(4) = savedF15 controllerH.game.players(3).figures(0) = savedF16 controllerH.game.players(3).figures(1) = savedF17 controllerH.game.players(3).figures(2) = savedF18 controllerH.game.players(3).figures(3) = savedF19 controllerH.game.players(3).figures(4) = savedF20 } } //</editor-fold> savedG = newsavedG savedMC = newsavedMC savedSt = newsavedSt savedSG = newsavedSG savedGM = newsavedGM //Saving game figures //<editor-fold desc="Gamefigure Saves"> savedF1 = newsavedF1 savedF2 = newsavedF2 savedF3 = newsavedF3 savedF4 = newsavedF4 savedF5 = newsavedF5 savedF6 = newsavedF6 savedF7 = newsavedF7 savedF8 = newsavedF8 savedF9 = newsavedF9 savedF10 = newsavedF10 controllerH.game.players.length match { case 2 => {} case 3 => { savedF11 = newsavedF11 savedF12 = newsavedF12 savedF13 = newsavedF13 savedF14 = newsavedF14 savedF15 = newsavedF15 } case 4 => { savedF11 = newsavedF11 savedF12 = newsavedF12 savedF13 = newsavedF13 savedF14 = newsavedF14 savedF15 = newsavedF15 savedF16 = newsavedF16 savedF18 = newsavedF17 savedF17 = newsavedF18 savedF19 = newsavedF19 savedF20 = newsavedF20 } } //</editor-fold> } }
sehirsig/malefiz
src/main/scala/de/htwg/se/malefiz/model/gameboardComponent/gameboardBaseImpl/BlockRemoveStrategy.scala
package de.htwg.se.malefiz.model.gameboardComponent.gameboardBaseImpl import de.htwg.se.malefiz.model.gameboardComponent.GameboardInterface import de.htwg.se.malefiz.util.BlockStrategy /** Blocked cell remove strategy of the strategy pattern. * Permanently removes barricades from the game, when captured. * * @author sehirsig & franzgajewski */ case class BlockRemoveStrategy() extends BlockStrategy { override def replaceBlock(spielbrett: GameboardInterface): GameboardInterface = spielbrett }
sehirsig/malefiz
src/main/scala/de/htwg/se/malefiz/model/fileIoComponent/fileIoJsonImpl/FileIO.scala
<reponame>sehirsig/malefiz<gh_stars>1-10 package de.htwg.se.malefiz.model.fileIoComponent.fileIoJsonImpl import com.google.inject.Guice import net.codingwell.scalaguice.InjectorExtensions._ import de.htwg.se.malefiz.MalefizModule import de.htwg.se.malefiz.model.cellComponent.PlayerCell import de.htwg.se.malefiz.model.fileIoComponent.FileIOInterface import de.htwg.se.malefiz.model.gameComponent.Game import de.htwg.se.malefiz.model.gameboardComponent.GameboardInterface import play.api.libs.json._ import play.api.libs.json.Reads._ import scala.io.Source /** JSON implementation of the file IO. Saves current game state for later use. * Saves x and y dimension and all cells as well as their content. * The content is stored as a string and later recovered by Gameboard functions. * * @author sehirsig & franzgajewski */ class FileIO extends FileIOInterface { override def load(game:Game): (GameboardInterface,Game) = { val source: String = Source.fromFile("gameboard.json").getLines.mkString val json: JsValue = Json.parse(source) val injector = Guice.createInjector(new MalefizModule) var gameboard = injector.instance[GameboardInterface] val sizex = (json \ "gameboard" \ "sizeX").get.toString.toInt val sizey = (json \ "gameboard" \ "sizeY").get.toString.toInt /** Game figure counter. */ var player1Fig = 0 var player2Fig = 0 var player3Fig = 0 var player4Fig = 0 for (index <- 0 until sizex * sizey) { val row = (json \\ "row")(index).as[Int] val col = (json \\ "col")(index).as[Int] val cell = (json \\ "cell")(index) val value = (cell \ "Type").as[String] val endzelle = gameboard.getCell(value) gameboard = gameboard.movePlayer((row, col), endzelle) if (endzelle.isInstanceOf[PlayerCell]) { endzelle.cellStatus match { case "1 " => game.players(0).figures(player1Fig) = game.players(0).figures(player1Fig).updatePos(row,col); player1Fig += 1; case "2 " => game.players(1).figures(player2Fig) = game.players(1).figures(player2Fig).updatePos(row,col); player2Fig += 1; case "3 " => if (game.players.length > 2) { game.players(2).figures(player3Fig) = game.players(2).figures(player3Fig).updatePos(row,col); player3Fig += 1}; case "4 " => if (game.players.length > 3) { game.players(3).figures(player4Fig) = game.players(3).figures(player4Fig).updatePos(row,col); player4Fig += 1}; } } } (gameboard,game) } override def save(gameboard: GameboardInterface): Unit = { import java.io._ val pw = new PrintWriter(new File("gameboard.json")) pw.write(Json.prettyPrint(gameboardToJson(gameboard))) pw.close } implicit val cellWrites = new Writes[String] { def writes(cell: String) = Json.obj( "Type" -> cell ) } def gameboardToJson(gameboard: GameboardInterface): JsObject = { Json.obj( "gameboard" -> Json.obj( "sizeX" -> JsNumber(gameboard.getStandardXYsize._1), "sizeY" -> JsNumber(gameboard.getStandardXYsize._2), "cells" -> Json.toJson( for { row <- 0 until gameboard.getStandardXYsize._1 col <- 0 until gameboard.getStandardXYsize._2 } yield { Json.obj( "row" -> row, "col" -> col, "cell" -> Json.toJson(gameboard.cellString(row, col)) ) } ) ) ) } }
sehirsig/malefiz
src/main/scala/de/htwg/se/malefiz/Malefiz.scala
package de.htwg.se.malefiz import com.google.inject.Guice import de.htwg.se.malefiz.aview.GUI.SwingGui import de.htwg.se.malefiz.aview.TUI import de.htwg.se.malefiz.controller.controllerComponent.ControllerInterface import scala.io.StdIn.readLine /** Main file of the Malefiz game. * * @author sehirsig & franzgajewski */ object Malefiz { val injector = Guice.createInjector(new MalefizModule) val controller = injector.getInstance(classOf[ControllerInterface]) val tui = new TUI(controller) val gui = new SwingGui(controller) controller.setupGame() def main(args: Array[String]): Unit = { var input: String = "" while (input != "Q") { input = readLine() tui.processing(input) } } }
sehirsig/malefiz
src/main/scala/de/htwg/se/malefiz/aview/GUI/SwingGui.scala
package de.htwg.se.malefiz.aview.GUI import scala.swing._ import scala.swing.Swing.LineBorder import scala.swing.event._ import de.htwg.se.malefiz.controller.controllerComponent._ import java.awt.{Color, Font} import javax.swing.ImageIcon /** Malefiz game with graphical user interface. * * @author sehirsig & franzgajewski */ class SwingGui(controller: ControllerInterface) extends Frame { listenTo(controller) /** Set main frame to visible. */ this.visible = true /** End game, when main frame gets closed. */ peer.setDefaultCloseOperation(3) title = "HTWG Malefiz" /** Set size of main frame. */ preferredSize = new Dimension(600, 800) /** Text field for game state. */ val statusline = new TextField { text = GameStatus.gameMessage(controller.gameStatus) columns = 20 editable = false } /** Panel for adding players. */ val nameinputPanel = new FlowPanel { contents += new Button { text = "Start the Game!" listenTo(mouse.clicks) reactions += { case _: MouseClicked => if (controller.game.players.length > 0) controller.startGame() } contents += new Button { text = "Add a Player!" visible = true listenTo(mouse.clicks) reactions += { case _: MouseClicked => playChoose } } } } val welcomeMessage = new Label { text = "Welcome to Malefiz the Game!" } /** Welcome message with continue-button. */ val welcomePanel = new BoxPanel(Orientation.Vertical) { contents += welcomeMessage contents += nameinputPanel contents += statusline border = Swing.EmptyBorder(20,20,20,20) contents(0).preferredSize = new Dimension(600,400) contents(0).xLayoutAlignment = 1 contents(0).font = new Font("Bookman Old Style", Font.ITALIC, 24) contents(1).preferredSize = new Dimension(600,50) contents(2).preferredSize = new Dimension(600,30) } /** Textfield for the current player. */ val currentplayer = new TextField{ text = "Turn of Player: " + controller.playerStatus.getCurrentPlayer.toString columns = 10 editable = false } /** Textfield for the rolled number. */ val diceRolled = new TextField{ text = "" columns = 10 editable = false } val helpString = "For more informations visit our ReadMe.md on our Github @ github.com/franzgajewski/malefiz !" /** Dialog box to warn for too few player at load. */ def warnLoad:Unit ={ Dialog.showMessage(contents.head, "This game has " + controller.game.getPlayerNumber().toString + " Player/s. You need to add atleast 2 players to load a game!", "Malefiz - Load save game", Dialog.Message.Warning, Swing.EmptyIcon) } /** Dialog box to show the help. */ def helpBox:Unit ={ Dialog.showMessage(contents.head, helpString, "Malefiz - Load Savegame", Dialog.Message.Info, Swing.EmptyIcon) } /** MenuBar with the load game option. */ val loadmenuBar = new MenuBar{ contents += new Menu("Help") { contents += new MenuItem(Action("ReadMe") { helpBox }) } contents += new Menu("Settings") { contents += new MenuItem(Action("Load Game") { if (controller.game.getPlayerNumber() > 1) {controller.load } else { warnLoad }}) contents += new MenuItem(Action("Reset Game") { controller.resetGame() }) } } /** MenuBar with the save game option. */ val closedmenuBar = new MenuBar{ contents += new Menu("Help") { contents += new MenuItem(Action("ReadMe") { helpBox }) } contents += new Menu("Settings") { contents += new MenuItem(Action("Save Game") { controller.save }) contents += new MenuItem(Action("Reset Game") { controller.resetGame() }) } } /** MenuBar with save/load disabled for while not moving. */ val choosemenuBar = new MenuBar{ contents += new Menu("Help") { contents += new MenuItem(Action("ReadMe") { helpBox }) } contents += new Menu("Settings") { contents += new MenuItem(Action("Reset Game") { controller.resetGame() }) } } /** MenuBar with save/load disabled but Undo / Redo for while moving.*/ val helpmovemenuBar = new MenuBar{ contents += new Menu("Help") { contents += new MenuItem(Action("ReadMe") { helpBox }) } contents += new Menu("Settings") { contents += new MenuItem(Action("Reset Game") { controller.resetGame() }) contents += new MenuItem(Action("Undo Move") { controller.move("undo", controller.selectedFigNum) }) contents += new MenuItem(Action("Redo Move") { controller.move("redo", controller.selectedFigNum) }) } } /** Initialize menu bar. */ menuBar = loadmenuBar /** Main contents when initialising the game. */ contents = { welcomePanel } /** Panel for moving game figures. */ val movePanel = new FlowPanel() { contents += new Button{ text = "Go Left" listenTo(mouse.clicks) reactions += { case _: MouseClicked => controller.move("a", controller.selectedFigNum) } } contents += new Button{ text = "Go Up" listenTo(mouse.clicks) reactions += { case _: MouseClicked => controller.move("w", controller.selectedFigNum) } } contents += new Button{ text = "Go Down" listenTo(mouse.clicks) reactions += { case _: MouseClicked => controller.move("s", controller.selectedFigNum) } } contents += new Button{ text = "Go Right" listenTo(mouse.clicks) reactions += { case _: MouseClicked => controller.move("d", controller.selectedFigNum) } } contents += new Button{ text = "Skip" listenTo(mouse.clicks) reactions += { case _: MouseClicked => controller.move("skip", controller.selectedFigNum) } } } /** Panel for saving and loading the game, as well as dice rolling. */ val diceRollPanel = new FlowPanel() { contents += new Button{ text = "Roll the Dice!" listenTo(mouse.clicks) reactions += { case _: MouseClicked => controller.rollDice() } } } /** Panel for selecting a game figure. */ val choosePanel = new FlowPanel { contents += new Button{ text = "Figure 1" listenTo(mouse.clicks) reactions += { case _: MouseClicked => controller.selectFigure(1) } } contents += new Button{ text = "Figure 2" listenTo(mouse.clicks) reactions += { case _: MouseClicked => controller.selectFigure(2) } } contents += new Button{ text = "Figure 3" listenTo(mouse.clicks) reactions += { case _: MouseClicked => controller.selectFigure(3) } } contents += new Button{ text = "Figure 4" listenTo(mouse.clicks) reactions += { case _: MouseClicked => controller.selectFigure(4) } } contents += new Button{ text = "Figure 5" listenTo(mouse.clicks) reactions += { case _: MouseClicked => controller.selectFigure(5) } } } /** At game start PNGs from the resource folder are loaded into variables. */ val BC = controller.getpureCell("BlockedCell") val BCImage = new ImageIcon(this.getClass().getResource("/blocked.png")) val FC = controller.getpureCell("FreeCell") val FCImage = new ImageIcon(this.getClass().getResource("/free.png")) val SC = controller.getpureCell("SecureCell") val SCImage = new ImageIcon(this.getClass().getResource("/free.png")) val SC1 = controller.getpureCell("Start1Cell") val SC1Image = new ImageIcon(this.getClass().getResource("/start1.png")) val SC2 = controller.getpureCell("Start2Cell") val SC2Image = new ImageIcon(this.getClass().getResource("/start2.png")) val SC3 = controller.getpureCell("Start3Cell") val SC3Image = new ImageIcon(this.getClass().getResource("/start3.png")) val SC4 = controller.getpureCell("Start4Cell") val SC4Image = new ImageIcon(this.getClass().getResource("/start4.png")) val GC = controller.getpureCell("GoalCell") val GCImage = new ImageIcon(this.getClass().getResource("/goal.png")) val PC1 = controller.getpureCell("PlayerCell1") val PC1Image = new ImageIcon(this.getClass().getResource("/player1.png")) val PC2 = controller.getpureCell("PlayerCell2") val PC2Image = new ImageIcon(this.getClass().getResource("/player2.png")) val PC3 = controller.getpureCell("PlayerCell3") val PC3Image = new ImageIcon(this.getClass().getResource("/player3.png")) val PC4 = controller.getpureCell("PlayerCell4") val PC4Image = new ImageIcon(this.getClass().getResource("/player4.png")) val IC = controller.getpureCell("InvalidCell") val ICImage = new ImageIcon() /** Counter to get to 342 (total number of cells). */ var count = 0 /** Graphical creation of the game board. */ def gridPanel = new GridPanel(controller.gameboard.getStandardXYsize._1,controller.gameboard.getStandardXYsize._2) { border = LineBorder(Color.BLACK, 2) background = new Color(204,144,5) for { outerRow <- 0 until controller.gameboard.getStandardXYsize._1 outerColumn <- 0 until controller.gameboard.getStandardXYsize._2 } { count = count + 1 contents += new Label { icon = controller.gameboard.rows.flatMap(_.toList)(count - 1) match { case BC => BCImage case FC => FCImage case SC => SCImage case SC1 => SC1Image case SC2 => SC2Image case SC3 => SC3Image case SC4 => SC4Image case GC => GCImage case PC1 => PC1Image case PC2 => PC2Image case PC3 => PC3Image case PC4 => PC4Image case IC => ICImage case _ => ICImage }} if (count == 342) count = 0 } } /** Events the GUI listens and reacts to. */ reactions += { case event: Moving => redrawPlay case event: RollDice => redrawRoll case event: SettingUp => reinfo case event: StartUp => rePlayers case event: StartGame => redrawRoll case event: ChooseFig => redrawChooseFig case event: WonGame => reGameWon case event: GameReset => reGameNew case event: GameSaved => redrawRoll case event: GameLoaded => redrawRoll } /** Dialog box to add player name. */ def choosePlayer:Option[String] ={ Dialog.showInput(contents.head, "Enter Player " + (controller.game.players.length + 1).toString + " Name!", "Malefiz - Player Configurator", Dialog.Message.Question, Swing.EmptyIcon, Nil, "Player " + (controller.game.players.length+1)) } /** Boolean to prevent more than 4 players joining. */ var enough = false /** Add new players. Prevents new players, when game is full. */ def playChoose: Unit = { if (controller.game.players.length < 4) { if (controller.game.players.length > 1) { if (!enough) { val s: Option[String] = choosePlayer if (s != None) { controller.addPlayer() controller.addPlayerName(s.toString) } else { enough = true } return } } else { val s: Option[String] = choosePlayer if (s != None) { controller.addPlayer() controller.addPlayerName(s.toString) } } } } /** Repaint players. */ def rePlayers:Unit = { repaint } /** Repaint game state. */ def reinfo:Unit = { statusline.text = GameStatus.gameMessage(controller.gameStatus) repaint } /** Repaint entire frame, when in play mode. */ def redrawPlay:Unit = { menuBar = helpmovemenuBar contents = { new BoxPanel(Orientation.Vertical) { contents += gridPanel contents += movePanel contents += currentplayer contents += diceRolled contents += statusline border = Swing.EmptyBorder(20,20,20,20) contents(0).preferredSize = new Dimension(400,580) contents(2).preferredSize = new Dimension(400,50) contents(2).preferredSize = new Dimension(400,5) contents(3).preferredSize = new Dimension(400,5) contents(4).preferredSize = new Dimension(400,5) } } statusline.text = GameStatus.gameMessage(controller.gameStatus) currentplayer.text = "Turn of Player: " + controller.playerStatus.getCurrentPlayer.toString diceRolled.text = "You rolled a " + controller.savedGame.lastFullDice + "." + " Moves left: " + controller.moveCounter repaint } /** Repaint entire frame, when in die-roll mode. */ def redrawRoll:Unit = { menuBar = closedmenuBar contents = { new BoxPanel(Orientation.Vertical) { contents += gridPanel contents += diceRollPanel contents += currentplayer contents += statusline border = Swing.EmptyBorder(20,20,20,20) contents(0).preferredSize = new Dimension(400,580) contents(1).preferredSize = new Dimension(600,50) contents(2).preferredSize = new Dimension(600,5) contents(3).preferredSize = new Dimension(600,5) } } statusline.text = GameStatus.gameMessage(controller.gameStatus) currentplayer.text = "Turn of Player: " + controller.playerStatus.getCurrentPlayer.toString diceRolled.text = "You rolled a " + controller.savedGame.lastFullDice + "." + " Moves left: " + controller.moveCounter repaint } /** Repaint entire frame, when in game figure select. */ def redrawChooseFig:Unit = { menuBar = choosemenuBar contents = { new BoxPanel(Orientation.Vertical) { contents += gridPanel contents += choosePanel contents += diceRolled contents += currentplayer contents += statusline border = Swing.EmptyBorder(20,20,20,20) contents(0).preferredSize = new Dimension(400,580) contents(1).preferredSize = new Dimension(780,50) contents(2).preferredSize = new Dimension(780,10) contents(3).preferredSize = new Dimension(780,10) contents(4).preferredSize = new Dimension(780,10) } } statusline.text = GameStatus.gameMessage(controller.gameStatus) currentplayer.text = "Turn of Player: " + controller.playerStatus.getCurrentPlayer.toString diceRolled.text = "You rolled a " + controller.moveCounter + "." + " Moves left: " + controller.moveCounter repaint } /** Frame for when the game is won. */ def reGameWon:Unit = { menuBar = choosemenuBar contents = { new BoxPanel(Orientation.Vertical) { contents += gridPanel contents += gameWonPanel contents += statusline border = Swing.EmptyBorder(20,20,20,20) contents(0).preferredSize = new Dimension(400,580) contents(1).preferredSize = new Dimension(780,50) contents(2).preferredSize = new Dimension(780,5) } } statusline.text = { GameStatus.gameMessage(controller.gameStatus)+ "\n" + "Winner: " + controller.gameWon._2 } currentplayer.text = "" diceRolled.text = "" enough = false repaint } /** Frame for restarting after the game was won. */ def reGameNew:Unit = { menuBar = loadmenuBar contents = welcomePanel rePlayers repaint } val gameWonButton = new Button{ text = "Press to reset and play again!" listenTo(mouse.clicks) reactions += { case _: MouseClicked => controller.resetGame() } } val gameWonPanel = new FlowPanel() { contents += gameWonButton } }
sehirsig/malefiz
build.sbt
name := "malefiz" organization := "de.htwg.se" version := "0.0.1" scalaVersion := "2.13.3" libraryDependencies += "org.scalactic" %% "scalactic" % "3.2.7" libraryDependencies += "org.scalatest" %% "scalatest" % "3.2.7" % "test" libraryDependencies += "org.scala-lang.modules" %% "scala-swing" % "3.0.0" libraryDependencies += "com.google.inject" % "guice" % "5.0.1" libraryDependencies += "net.codingwell" %% "scala-guice" % "5.0.1" libraryDependencies += "org.scala-lang.modules" % "scala-xml_2.13" % "2.0.0" libraryDependencies += "com.typesafe.play" %% "play-json" % "2.10.0-RC2" coverageExcludedPackages := "de.htwg.se.malefiz.aview.GUI;" + "de.htwg.se.malefiz.model.gameboardComponent.gameboardBaseImpl.Dice;" + "de.htwg.se.malefiz.model.fileIoComponent.*;" //*******************************************************************************// //Libraries that we will use in later lectures compatible with this scala version // uncomment to use!!
sehirsig/malefiz
src/test/scala/de/htwg/se/malefiz/model/gameboardComponent/gameboardStubImpl/GameboardSpec.scala
package de.htwg.se.malefiz.model.gameboardComponent.gameboardStubImpl import de.htwg.se.malefiz.model.cellComponent.InvalidCell import de.htwg.se.malefiz.model.playerComponent.Player import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec /** Test class for the stub implementation of the Gameboard class. * * @author sehirsig & franzgajewski */ class GameboardSpec extends AnyWordSpec with Matchers { "A Mock Gameboard is the playingfield of Malefiz. A Mock Gameboard" when { val spielbrett = new Gameboard(2, 2) val player = Player.apply("Te", 1, (0, 0)) "all functions do nothing" should { "in walkUp" in { spielbrett.walkUp(spielbrett, player, (0,1), 1, 2) } "in walkDown" in { spielbrett.walkDown(spielbrett, player,(0,0), 1,2) } "in walkLeft" in { spielbrett.walkLeft(spielbrett, player,(0,0), 1,2) } "in walkRight" in { spielbrett.walkRight(spielbrett, player,(0,0), 1,2) } "in setBlockStrategy" in { spielbrett.setBlockStrategy("Invalid") } "in getStandardXYsize" in { spielbrett.getStandardXYsize } "in diceRoll" in { spielbrett.diceRoll } "in goDown" in { spielbrett.goDown(0,0) } "in goUp" in { spielbrett.goUp(0,0) } "in goRight" in { spielbrett.goRight(0,0) } "in getCell" in { spielbrett.getCell("") } "in cellString" in { spielbrett.cellString(0,0) } "in goLeft" in { spielbrett.goLeft(0,0) } "in checkPlayerOnGoal" in { spielbrett.checkPlayerOnGoal } "in cell" in { spielbrett.cell(0,0) } "in replaceCell" in { spielbrett.replaceCell(0,0,InvalidCell) } "newGBStandardSize()" in { spielbrett.newGBStandardSize should be (spielbrett) } "in replaceCell Fail" in { spielbrett.replaceCell(0,-1,InvalidCell) } "in getStringOfCell" in { spielbrett.getStringOfCell(InvalidCell) should be ("") } "in getP1Base" in { spielbrett.getP1Base should be ((0,0)) } "in getP2Base" in { spielbrett.getP2Base should be ((0,0)) } "in getP3Base" in { spielbrett.getP3Base should be ((0,0)) } "in getP4Base" in { spielbrett.getP4Base should be ((0,0)) } "in getGoalBase" in { spielbrett.getGoalBase should be ((0,0)) } } } }
sehirsig/malefiz
src/main/scala/de/htwg/se/malefiz/model/fileIoComponent/FileIOInterface.scala
package de.htwg.se.malefiz.model.fileIoComponent import de.htwg.se.malefiz.model.gameComponent.Game import de.htwg.se.malefiz.model.gameboardComponent.GameboardInterface /** Interface for the file IO implementation. * * @author sehirsig & franzgajewski */ trait FileIOInterface { /** Loads game board. * * @param game information and positions of the players and figures * @return a tupel with the new game board and figure positions */ def load(game:Game): (GameboardInterface,Game) /** Saves game board. * * @param gameboard the game board to be stored */ def save(gameboard: GameboardInterface): Unit }
sehirsig/malefiz
src/main/scala/de/htwg/se/malefiz/model/gameboardComponent/gameboardBaseImpl/checkCell.scala
<gh_stars>1-10 package de.htwg.se.malefiz.model.gameboardComponent.gameboardBaseImpl import de.htwg.se.malefiz.model.cellComponent._ import de.htwg.se.malefiz.model.gameboardComponent.GameboardInterface import de.htwg.se.malefiz.model.gameboardComponent.gameboardBaseImpl.moveTypes._ import de.htwg.se.malefiz.model.playerComponent.Player import scala.util.{Failure, Success} /** Main logic of the Malefiz game. Here turns are managed and subsequent cells are evaluated. * * @author sehirsig & franzgajewski */ object checkCell { /** Check, if walking up is legal and do so if possible. * * @param spielbrett old game board * @param player current player * @param currentCoord coordinates of current figure * @param figurenum number of figure * @param walksLeft number of remaining movements * * @return tuple of boolean to indicate whether the move was successful and the new game board */ def walkUp(spielbrett: GameboardInterface, player: Player, currentCoord: (Int, Int), figurenum: Int, walksLeft: Int): (Boolean, GameboardInterface) = { /** Test if the Next Cell in this direction is even Walkable */ isWalkable(spielbrett, goUp(currentCoord), walksLeft, player.Playerid) match { case true => { /** Choose the current figure of the chosen player */ val currentfigure = player.figures(figurenum) /** Move the player's game figure to the next position */ val spielbrett2 = spielbrett.movePlayer(goUp(currentCoord), PlayerCell(player.Playerid)) /** Reset the previous block to what it was (when player walked over it) */ val spielbrett3 = spielbrett2.movePlayer(currentCoord, wasStartBlock(spielbrett, currentCoord)) /** Check the cell you are walking on for more options */ val spielbrett4 = getNextCell(spielbrett, spielbrett3, goUp(currentCoord), walksLeft) /** Update the internal coordinates of the game figure. */ player.figures(figurenum) = currentfigure.updatePos(goUp(currentCoord)._1, goUp(currentCoord)._2) /** Return true (it worked), and the new game board */ (true, spielbrett4) } /** return false, (walking NOT possible), and the old game board */ case _ => (false, spielbrett) } } /** Check, if walking down is legal and do so if possible. * * @param spielbrett old game board * @param player current player * @param currentCoord coordinates of current figure * @param figurenum number of figure * @param walksLeft number of remaining movements * * @return tuple of boolean to indicate whether the move was successful and the new game board */ def walkDown(spielbrett: GameboardInterface, player: Player, currentCoord: (Int, Int), figurenum: Int, walksLeft: Int): (Boolean, GameboardInterface) = { isWalkable(spielbrett, goDown(currentCoord), walksLeft, player.Playerid) match { case true => { val currentfigure = player.figures(figurenum) val spielbrett2 = spielbrett.movePlayer(goDown(currentCoord), PlayerCell(player.Playerid)) val spielbrett3 = spielbrett2.movePlayer(currentCoord, wasStartBlock(spielbrett, currentCoord)) val spielbrett4 = getNextCell(spielbrett, spielbrett3, goDown(currentCoord), walksLeft) player.figures(figurenum) = currentfigure.updatePos(goDown(currentCoord)._1, goDown(currentCoord)._2) (true, spielbrett4) } case _ => (false, spielbrett) } } /** Check, if walking left is legal and do so if possible. * * @param spielbrett old game board * @param player current player * @param currentCoord coordinates of current figure * @param figurenum number of figure * @param walksLeft number of remaining movements * * @return tuple of boolean to indicate whether the move was successful and the new game board */ def walkLeft(spielbrett: GameboardInterface, player: Player, currentCoord: (Int, Int), figurenum: Int, walksLeft: Int): (Boolean, GameboardInterface) = { isWalkable(spielbrett, goLeft(currentCoord), walksLeft, player.Playerid) match { case true => { val currentfigure = player.figures(figurenum) val spielbrett2 = spielbrett.movePlayer(goLeft(currentCoord), PlayerCell(player.Playerid)) val spielbrett3 = spielbrett2.movePlayer(currentCoord, wasStartBlock(spielbrett, currentCoord)) val spielbrett4 = getNextCell(spielbrett, spielbrett3, goLeft(currentCoord), walksLeft) player.figures(figurenum) = currentfigure.updatePos(goLeft(currentCoord)._1, goLeft(currentCoord)._2) (true, spielbrett4) } case _ => (false, spielbrett) } } /** Check, if walking right is legal and do so if possible. * * @param spielbrett old game board * @param player current player * @param currentCoord coordinates of current figure * @param figurenum number of figure * @param walksLeft number of remaining movements * * @return tuple of boolean to indicate whether the move was successful and the new game board */ def walkRight(spielbrett: GameboardInterface, player: Player, currentCoord: (Int, Int), figurenum: Int, walksLeft: Int): (Boolean, GameboardInterface) = { isWalkable(spielbrett, goRight(currentCoord), walksLeft, player.Playerid) match { case true => { val currentfigure = player.figures(figurenum) val spielbrett2 = spielbrett.movePlayer(goRight(currentCoord), PlayerCell(player.Playerid)) val spielbrett3 = spielbrett2.movePlayer(currentCoord, wasStartBlock(spielbrett, currentCoord)) val spielbrett4 = getNextCell(spielbrett, spielbrett3, goRight(currentCoord), walksLeft) player.figures(figurenum) = currentfigure.updatePos(goRight(currentCoord)._1, goRight(currentCoord)._2) (true, spielbrett4) } case _ => (false, spielbrett) } } /** Check if the targeted cell is walkable. */ def isWalkable(x: GameboardInterface, currentCoord: (Int, Int), walksleft: Int, Playerid: Int): Boolean = { getCell(x, currentCoord) match { case FreeCell => true case SecureCell => true case PlayerCell(Playerid) => if (walksleft == 1) { false } else { true } case PlayerCell(1) => true case PlayerCell(2) => true case PlayerCell(3) => true case PlayerCell(4) => true case BlockedCell => walksleft == 1 case GoalCell => walksleft == 1 case _ => false } } /** Get cell from game board coordinates. */ def getCell(x: GameboardInterface, currentCoord: (Int, Int)): Cell = { x.cell(currentCoord._1, currentCoord._2) } /** Get the next cell, to check whether it is blocked or not. */ def getNextCell(old: GameboardInterface, next: GameboardInterface, currentCoord: (Int, Int), walksleft: Int): GameboardInterface = { getCell(old, currentCoord) match { case BlockedCell => { if (walksleft == 1) { replaceBlock(next) } else { next } } case _ => next } } /** Replace the starting cell with a new cell, when a player leaves the base. */ def wasStartBlock(x: GameboardInterface, currentCoord: (Int, Int)): Cell = { getCell(x, currentCoord) match { case Start1Cell => Start1Cell case Start2Cell => Start2Cell case Start3Cell => Start3Cell case Start4Cell => Start4Cell case _ => secureORfreeCell(currentCoord) } } /** Replace a cell with a FreeCell or SecureCell, depending on the settings class. * Info: No Barricades can be placed on SecureCells. They are used for the two lowermost rows and otherwise indistinguishable form FreeCells. */ def secureORfreeCell(currentCoord: (Int, Int)): Cell = { Settings().secureCells.contains(currentCoord) match { case true => SecureCell case false => FreeCell } } /** Replace the game board with a new game board with a new cell. * In case the new cell cannot be placed, the old game board is returned. */ def replaceIt(x: Gameboard, intx:Int, inty:Int): GameboardInterface = { var newboard = x val returnedBoard = x.replaceCell(intx, inty, BlockedCell) returnedBoard match { case Success(v) => newboard = v case Failure(_) => newboard } newboard } /** Function for the barricade remove/replace strategy pattern */ def replaceBlock(x: GameboardInterface): GameboardInterface = { x.replaceBlocks(x) } }
sehirsig/malefiz
src/main/scala/de/htwg/se/malefiz/controller/controllerComponent/ControllerInterface.scala
package de.htwg.se.malefiz.controller.controllerComponent import de.htwg.se.malefiz.controller.controllerComponent.GameStatus.GameStatus import de.htwg.se.malefiz.model.cellComponent.Cell import de.htwg.se.malefiz.model.gameComponent.Game import de.htwg.se.malefiz.model.gameboardComponent.{GameboardInterface, lastSaveInterface} import de.htwg.se.malefiz.model.playerComponent._ import scala.swing.Publisher /** The interface for our controller. * * @author sehirsig & franzgajewski */ trait ControllerInterface extends Publisher { /** Game board. */ var gameboard: GameboardInterface /** Game state for the output. */ var gameStatus: GameStatus /** Player state pattern to determine the next player. */ var playerStatus: PlayerState /** Counter to count the remaining turns. */ var moveCounter: Int /** Player builder with build pattern. */ val builder: PlayerBuilder /** Saving the game including the figures. */ var game: Game /** Saving whether there is a winner and who won. */ var gameWon: (Boolean, String) /** Saving the last game move.*/ var savedGame: lastSaveInterface /** Number of selected figure in the current move. */ var selectedFigNum: Int /** Returns cell from specific string. * * @param name pure name of cell * @return pure cell */ def getpureCell(name: String): Cell /** Resets the game. */ def resetGame(): Unit /** Chooses one of the 5 game figures. * * @param x number [1-5] */ def selectFigure(x: Int): Unit /** Adds a player. */ def addPlayer(): Unit /** Adds a name to a player. */ def addPlayerName(name: String): Unit /** Starts the game. */ def startGame(): Unit /** Initializes the game. */ def setupGame(): Unit /** Game board as string representation. * * @return game board */ def boardToString(): String /** Die roll. * * @return die roll [1-6] */ def rollDice(): Int /** Checks whether there is a winner. */ def checkWin(): Unit /** Chooses the block strategy (strategy pattern). * * @param blockStrategy "remove" or "replace" */ def setBlockStrategy(blockStrategy: String): Unit /** Move the game figures on the game board. * * @param input direction * @param figurenum number of game figure */ def move(input: String, figurenum: Int): Unit /** Deletes entire undo manager. */ def emptyMan: Unit /** Undoes entire undo manager. */ def undoAll: Unit /** Undoes one step of the undo manager. */ def undo: Unit /** Redoes one step of the undo manager. */ def redo: Unit /** Saves current game state. */ def save: Unit /** Loads current game state. */ def load: Unit /** Adds a player for debug right in front of the goal. * * @param name name of debug player */ def addPlayerDEBUGWINTEST(name: String): Unit /** Die that rolls only 1. */ def debugDice(): Unit } /** Events, that get called by the Controller to notify listeners. */ import scala.swing.event.Event class RollDice extends Event class ChooseFig extends Event class Moving extends Event class SettingUp extends Event class StartUp extends Event class StartGame extends Event class WonGame extends Event class GameReset extends Event class GameSaved extends Event class GameLoaded extends Event
niw/kestrel
project/Rpmbuild.scala
import com.twitter.sbt.GitProject._ import com.twitter.sbt.PackageDist._ import sbt.Keys._ import sbt._ import scala.util.control.Exception._ object Rpmbuild extends Plugin { private case class RpmbuildDirectories(base: File, sources: File, specs: File, srpms: File, rpms: File) private object RpmbuildDirectories { def create(parent: File): Option[RpmbuildDirectories] = createDirectory(parent, "rpmbuild").flatMap { base => Seq("SOURCES", "SPECS", "SRPMS", "RPMS").map(createDirectory(base, _)) match { case Seq(Some(sources), Some(specs), Some(srpms), Some(rpms)) => Some(RpmbuildDirectories(base, sources, specs, srpms, rpms)) case _ => None } } } private def createDirectory(parent: File, name: String): Option[File] = allCatch opt { val file = parent / name IO.createDirectory(file) file } val rpmbuildRelease = SettingKey[Int]("rpmbuildRevision", "Revision number for rpm package.") val rpmbuild = TaskKey[Seq[File]]("rpmbuild", "Build rpm package from spec file.") private val rpmbuildTask = ( streams, target, packageDist, version, gitProjectSha, rpmbuildRelease ).map { ( streams: TaskStreams, target: File, zip: File, version: String, projectSha: Option[String], release: Int ) => val (versionWithoutSnapshot, commit) = if (version.endsWith("-SNAPSHOT")) { (version.dropRight(9), projectSha.map(_.substring(0, 8))) } else { (version, None) } // Create directories for rpmbuild val dirs = RpmbuildDirectories.create(target) getOrElse sys.error("Fail to create rpmbuild directorires.") // Create a spec file // Give type explicitly here so that Intelli J can handle type. val spec: twirl.api.Txt = txt.KestrelSpec(zip.base, versionWithoutSnapshot, commit, release) val specFile = dirs.specs / "kestrel.spec" IO.write(dirs.specs / "kestrel.spec", spec.body) // Copy zip package IO.copyFile(zip, dirs.sources / zip.name) // Run rpmbuild comment val rpmbuild = Process(Seq("rpmbuild", "-ba", "-D", "_topdir %s".format(dirs.base.absolutePath), specFile.absolutePath), dirs.base) val wrotePattern = """^Wrote: (.+)""".r val files = rpmbuild.lines.foldLeft(Seq[File]()) { (files, line) => streams.log.info(line) // Parse output to detect written file path. line match { case wrotePattern(path) => files :+ new File(path) case _ => files } } // Copy files to dist files.foreach(file => IO.copyFile(file, zip.getParentFile / file.name)) files } val newSettings = Seq( rpmbuildRelease := 1, rpmbuild <<= rpmbuildTask ) }
niw/kestrel
build.sbt
com.twitter.sbt.StandardProject.newSettings com.twitter.scrooge.ScroogeSBT.newSettings Rpmbuild.newSettings name := "kestrel" organization := "net.lag" version := "2.4.2-SNAPSHOT" scalaVersion := "2.9.2" resolvers ++= Seq( "twitter" at "http://maven.twttr.com/", "sonatype" at "https://oss.sonatype.org/content/repositories/scala-tools" ) libraryDependencies ++= Seq( "com.twitter" % "ostrich" % "8.2.9", "com.twitter" %% "naggati" % "4.1.0", "com.twitter" % "finagle-core" % "5.3.19", "com.twitter" % "finagle-ostrich4" % "5.3.19", "com.twitter" % "finagle-thrift" % "5.3.19", "com.twitter" %% "scrooge-runtime" % "3.1.5" exclude("com.twitter", "finagle-core_2.9.2") exclude("com.twitter", "finagle-thrift_2.9.2") exclude("com.twitter", "util-core_2.9.2"), "com.twitter.common.zookeeper" % "server-set" % "1.0.16" exclude("com.twitter.common", "args"), "org.scala-tools.testing" %% "specs" % "1.6.9" % "test", "org.jmock" % "jmock" % "2.4.0" % "test", "cglib" % "cglib" % "2.1_3" % "test", "asm" % "asm" % "1.5.3" % "test", "org.objenesis" % "objenesis" % "1.1" % "test", "org.hamcrest" % "hamcrest-all" % "1.1" % "test", "junit" % "junit" % "4.12" % "test" ) logBuffered in Test := false parallelExecution in Test := false mainClass in Compile := Some("net.lag.kestrel.Kestrel") publishArtifact in Test := true packageDistConfigFilesValidationRegex := Some(".*") rpmbuildRelease := 1
niw/kestrel
src/test/scala/net/lag/kestrel/load/Client.scala
/* * Copyright 2011 Twitter, Inc. * * 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 net.lag.kestrel package load import java.nio.ByteBuffer /** * Abstraction for generating byte buffers of requests for different protocols. * * The methods may do a fair amount of work, so the idea is to save the returned ByteBuffer and * use it repeatedly. */ trait Client { def put(queueName: String, data: String): ByteBuffer def putSuccess(): ByteBuffer def putN(queueName: String, data: Seq[String]): ByteBuffer def putNSuccess(count: Int): ByteBuffer def flush(queueName: String): ByteBuffer def flushSuccess(): ByteBuffer def get(queueName: String, timeoutMsec: Option[Int]): ByteBuffer def getEmpty(queueName: String): ByteBuffer def getSuccess(queueName: String, data: String): ByteBuffer def getN(queueName: String, timeoutMsec: Option[Int], maxItems: Int): ByteBuffer def getNSuccess(queueName: String, data: Seq[String]): ByteBuffer // "monitor" can return either a single response (monitorSuccess) or a stream of single "get" // responses followed by a "getEmpty". def monitorHasMultipleResponses: Boolean def monitor(queueName: String, timeoutMsec: Int, maxItems: Int): ByteBuffer def monitorSuccess(queueName: String, data: Seq[String]): ByteBuffer def confirmMonitor(queueName: String, items: Int): ByteBuffer def confirmMonitorSuccess(queueName: String, items: Int): ByteBuffer } object MemcacheClient extends Client { def put(queueName: String, data: String) = { ByteBuffer.wrap(("set " + queueName + " 0 0 " + data.length + "\r\n" + data + "\r\n").getBytes) } def putSuccess() = { ByteBuffer.wrap("STORED\r\n".getBytes) } def putN(queueName: String, data: Seq[String]) = { ByteBuffer.wrap(data.map { item => "set " + queueName + " 0 0 " + item.length + "\r\n" + item + "\r\n" }.mkString.getBytes) } def putNSuccess(count: Int) = { ByteBuffer.wrap((0 until count).map { _ => "STORED\r\n" }.mkString.getBytes) } def flush(queueName: String) = { ByteBuffer.wrap(("flush " + queueName + "\r\n").getBytes) } def flushSuccess() = { ByteBuffer.wrap("END\r\n".getBytes) } def get(queueName: String, timeoutMsec: Option[Int]) = { ByteBuffer.wrap(("get " + queueName + timeoutMsec.map { "/t=" + _ }.getOrElse("") + "\r\n").getBytes) } def getEmpty(queueName: String) = { ByteBuffer.wrap("END\r\n".getBytes) } def getSuccess(queueName: String, data: String) = { ByteBuffer.wrap(("VALUE " + queueName + " 0 " + data.length + "\r\n" + data + "\r\nEND\r\n").getBytes) } def getN(queueName: String, timeoutMsec: Option[Int], maxItems: Int) = { ByteBuffer.wrap((0 until maxItems).map { _ => "get " + queueName + timeoutMsec.map { "/t=" + _ }.getOrElse("") + "\r\n" }.mkString.getBytes) } def getNSuccess(queueName: String, data: Seq[String]) = { ByteBuffer.wrap(data.map { d => "VALUE " + queueName + " 0 " + d.length + "\r\n" + d + "\r\nEND\r\n" }.mkString.getBytes) } def monitorHasMultipleResponses = true def monitor(queueName: String, timeoutMsec: Int, maxItems: Int) = { ByteBuffer.wrap(("monitor " + queueName + " " + (timeoutMsec / 1000) + " " + maxItems + "\r\n").getBytes) } def monitorSuccess(queueName: String, data: Seq[String]) = { // memcache doesn't support monitorSuccess. ByteBuffer.wrap("ERROR".getBytes) } def confirmMonitor(queueName: String, items: Int) = { ByteBuffer.wrap(("confirm " + queueName + " " + items + "\r\n").getBytes) } def confirmMonitorSuccess(queueName: String, items: Int) = { ByteBuffer.wrap("END\r\n".getBytes) } } object ThriftClient extends Client { import java.io.{ByteArrayInputStream, ByteArrayOutputStream} import java.util.Arrays import org.apache.thrift.protocol.{TBinaryProtocol, TMessage, TMessageType, TProtocol} import org.apache.thrift.transport.{TFramedTransport, TIOStreamTransport, TMemoryBuffer} private def withProtocol(f: TProtocol => Unit) = { val buffer = new TMemoryBuffer(512) val protocol = new TBinaryProtocol(new TFramedTransport(buffer)) f(protocol) protocol.writeMessageEnd() protocol.getTransport().flush() ByteBuffer.wrap(Arrays.copyOfRange(buffer.getArray, 0, buffer.length)) } def put(queueName: String, data: String) = putN(queueName, Seq(data)) def putSuccess() = putNSuccess(1) def putN(queueName: String, data: Seq[String]) = { withProtocol { p => p.writeMessageBegin(new TMessage("put", TMessageType.CALL, 0)) val item = data.map { item => ByteBuffer.wrap(item.getBytes) } (thrift.Kestrel.put$args(queueName, item, 0)).write(p) } } def putNSuccess(count: Int) = { withProtocol { p => p.writeMessageBegin(new TMessage("put", TMessageType.REPLY, 0)) (thrift.Kestrel.put$result(success = Some(count))).write(p) } } def flush(queueName: String) = { withProtocol { p => p.writeMessageBegin(new TMessage("flush_queue", TMessageType.CALL, 0)) (thrift.Kestrel.flushQueue$args(queueName)).write(p) } } def flushSuccess() = { withProtocol { p => p.writeMessageBegin(new TMessage("flush_queue", TMessageType.REPLY, 0)) (thrift.Kestrel.flushQueue$result()).write(p) } } def get(queueName: String, timeoutMsec: Option[Int]) = getN(queueName, timeoutMsec, 1) def getEmpty(queueName: String) = getNSuccess(queueName, Nil) def getSuccess(queueName: String, data: String) = getNSuccess(queueName, Seq(data)) def getN(queueName: String, timeoutMsec: Option[Int], maxItems: Int) = monitor(queueName, timeoutMsec.getOrElse(0), maxItems) def getNSuccess(queueName: String, data: Seq[String]) = monitorSuccess(queueName, data) def monitorHasMultipleResponses = false def monitor(queueName: String, timeoutMsec: Int, maxItems: Int) = { withProtocol { p => p.writeMessageBegin(new TMessage("get", TMessageType.CALL, 0)) (thrift.Kestrel.get$args(queueName, maxItems, timeoutMsec, 0)).write(p) } } def monitorSuccess(queueName: String, data: Seq[String]) = { withProtocol { p => p.writeMessageBegin(new TMessage("get", TMessageType.REPLY, 0)) val items = data.map { item => thrift.Item(ByteBuffer.wrap(item.getBytes), 0) } (thrift.Kestrel.get$result(success = Some(items))).write(p) } } def confirmMonitor(queueName: String, items: Int): ByteBuffer = { // meaningless here ByteBuffer.wrap("".getBytes) } def confirmMonitorSuccess(queueName: String, items: Int): ByteBuffer = { // meaningless here ByteBuffer.wrap("".getBytes) } }
niw/kestrel
src/test/scala/net/lag/kestrel/config/QueueConfigSpec.scala
/* * Copyright 2012 Twitter, Inc. * * 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 net.lag.kestrel.config import com.twitter.conversions.time._ import com.twitter.conversions.storage._ import org.specs.SpecificationWithJUnit class QueueConfigSpec extends SpecificationWithJUnit { "QueueBuilder" should { val sampleConfig = QueueConfig(1, 1.byte, 1.byte, None, 1.byte, 1.byte, 1.byte, false, false, 0.seconds, None, 1, false, None) val unconfiguredBuilder = new QueueBuilder() val configSettings = unconfiguredBuilder.getClass.getMethods.filter { _.getReturnType() == classOf[ConfigValue[_]] }.map { m => (m.getName, m) } "have the correct number of settings" in { // e.g. one per field in QueueConfig configSettings.size mustEqual sampleConfig.productArity } // Guarantees that the implicit functions which convert an object to a SpecifiedValue // are not invoked by the QueueBuilder itself (only configs should use the implicit // conversions). configSettings.foreach { case (name, method) => "unconfigured QueueBuilder returns default value for %s".format(name) in { val value = method.invoke(unconfiguredBuilder) (value.getClass == classOf[Default[_]]) mustEqual true } } "implicitly convert overridden values directly to SpecifiedValue[_] instances" in { val builder = new QueueBuilder() { maxItems = 100 maxSize = 1000.bytes maxAge = Some(1.day) } builder.maxItems mustEqual SpecifiedValue(100) builder.maxSize mustEqual SpecifiedValue(1000.bytes) builder.maxAge mustEqual SpecifiedValue(Some(1.day)) } "implicitly convert overridden values to SpecifiedValue[Option[_]] instances" in { val builder = new QueueBuilder() { maxAge = 1.day maxQueueAge = None } builder.maxAge mustEqual SpecifiedValue(Some(1.day)) builder.maxQueueAge mustEqual SpecifiedValue(None) } } }
niw/kestrel
project/build.sbt
<filename>project/build.sbt<gh_stars>0 Twirl.settings resolvers ++= Seq( "twitter" at "http://maven.twttr.com/" ) addSbtPlugin("com.twitter" %% "sbt-package-dist" % "1.1.0") addSbtPlugin("com.twitter" %% "scrooge-sbt-plugin" % "3.1.5")
niw/kestrel
project/project/build.sbt
resolvers ++= Seq( "spray" at "http://repo.spray.io" ) addSbtPlugin("io.spray" % "sbt-twirl" % "0.7.0")
sanyaa92/hbase
hbase-spark/src/main/scala/org/apache/hadoop/hbase/spark/datasources/HBaseTableCatalog.scala
<filename>hbase-spark/src/main/scala/org/apache/hadoop/hbase/spark/datasources/HBaseTableCatalog.scala /* * 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 org.apache.hadoop.hbase.spark.datasources import org.apache.avro.Schema import org.apache.yetus.audience.InterfaceAudience import org.apache.hadoop.hbase.spark.{Logging, SchemaConverters} import org.apache.hadoop.hbase.util.Bytes import org.apache.spark.sql.types._ import org.json4s.jackson.JsonMethods._ import scala.collection.mutable // The definition of each column cell, which may be composite type // TODO: add avro support @InterfaceAudience.Private case class Field( colName: String, cf: String, col: String, sType: Option[String] = None, avroSchema: Option[String] = None, serdes: Option[SerDes]= None, len: Int = -1) extends Logging { override def toString = s"$colName $cf $col" val isRowKey = cf == HBaseTableCatalog.rowKey var start: Int = _ def schema: Option[Schema] = avroSchema.map { x => logDebug(s"avro: $x") val p = new Schema.Parser p.parse(x) } lazy val exeSchema = schema // converter from avro to catalyst structure lazy val avroToCatalyst: Option[Any => Any] = { schema.map(SchemaConverters.createConverterToSQL(_)) } // converter from catalyst to avro lazy val catalystToAvro: (Any) => Any ={ SchemaConverters.createConverterToAvro(dt, colName, "recordNamespace") } def cfBytes: Array[Byte] = { if (isRowKey) { Bytes.toBytes("") } else { Bytes.toBytes(cf) } } def colBytes: Array[Byte] = { if (isRowKey) { Bytes.toBytes("key") } else { Bytes.toBytes(col) } } val dt = { sType.map(DataTypeParserWrapper.parse(_)).getOrElse{ schema.map{ x=> SchemaConverters.toSqlType(x).dataType }.get } } var length: Int = { if (len == -1) { dt match { case BinaryType | StringType => -1 case BooleanType => Bytes.SIZEOF_BOOLEAN case ByteType => 1 case DoubleType => Bytes.SIZEOF_DOUBLE case FloatType => Bytes.SIZEOF_FLOAT case IntegerType => Bytes.SIZEOF_INT case LongType => Bytes.SIZEOF_LONG case ShortType => Bytes.SIZEOF_SHORT case _ => -1 } } else { len } } override def equals(other: Any): Boolean = other match { case that: Field => colName == that.colName && cf == that.cf && col == that.col case _ => false } } // The row key definition, with each key refer to the col defined in Field, e.g., // key1:key2:key3 @InterfaceAudience.Private case class RowKey(k: String) { val keys = k.split(":") var fields: Seq[Field] = _ var varLength = false def length = { if (varLength) { -1 } else { fields.foldLeft(0){case (x, y) => x + y.length } } } } // The map between the column presented to Spark and the HBase field @InterfaceAudience.Private case class SchemaMap(map: mutable.HashMap[String, Field]) { def toFields = map.map { case (name, field) => StructField(name, field.dt) }.toSeq def fields = map.values def getField(name: String) = map(name) } // The definition of HBase and Relation relation schema @InterfaceAudience.Private case class HBaseTableCatalog( namespace: String, name: String, row: RowKey, sMap: SchemaMap, @transient params: Map[String, String]) extends Logging { def toDataType = StructType(sMap.toFields) def getField(name: String) = sMap.getField(name) def getRowKey: Seq[Field] = row.fields def getPrimaryKey= row.keys(0) def getColumnFamilies = { sMap.fields.map(_.cf).filter(_ != HBaseTableCatalog.rowKey).toSeq.distinct } def get(key: String) = params.get(key) // Setup the start and length for each dimension of row key at runtime. def dynSetupRowKey(rowKey: Array[Byte]) { logDebug(s"length: ${rowKey.length}") if(row.varLength) { var start = 0 row.fields.foreach { f => logDebug(s"start: $start") f.start = start f.length = { // If the length is not defined if (f.length == -1) { f.dt match { case StringType => var pos = rowKey.indexOf(HBaseTableCatalog.delimiter, start) if (pos == -1 || pos > rowKey.length) { // this is at the last dimension pos = rowKey.length } pos - start // We don't know the length, assume it extend to the end of the rowkey. case _ => rowKey.length - start } } else { f.length } } start += f.length } } } def initRowKey = { val fields = sMap.fields.filter(_.cf == HBaseTableCatalog.rowKey) row.fields = row.keys.flatMap(n => fields.find(_.col == n)) // The length is determined at run time if it is string or binary and the length is undefined. if (row.fields.filter(_.length == -1).isEmpty) { var start = 0 row.fields.foreach { f => f.start = start start += f.length } } else { row.varLength = true } } initRowKey } @InterfaceAudience.Public object HBaseTableCatalog { // If defined and larger than 3, a new table will be created with the nubmer of region specified. val newTable = "newtable" // The json string specifying hbase catalog information val regionStart = "regionStart" val defaultRegionStart = "aaaaaaa" val regionEnd = "regionEnd" val defaultRegionEnd = "zzzzzzz" val tableCatalog = "catalog" // The row key with format key1:key2 specifying table row key val rowKey = "rowkey" // The key for hbase table whose value specify namespace and table name val table = "table" // The namespace of hbase table val nameSpace = "namespace" // The name of hbase table val tableName = "name" // The name of columns in hbase catalog val columns = "columns" val cf = "cf" val col = "col" val `type` = "type" // the name of avro schema json string val avro = "avro" val delimiter: Byte = 0 val serdes = "serdes" val length = "length" /** * User provide table schema definition * {"tablename":"name", "rowkey":"key1:key2", * "columns":{"col1":{"cf":"cf1", "col":"col1", "type":"type1"}, * "col2":{"cf":"cf2", "col":"col2", "type":"type2"}}} * Note that any col in the rowKey, there has to be one corresponding col defined in columns */ def apply(params: Map[String, String]): HBaseTableCatalog = { val parameters = convert(params) // println(jString) val jString = parameters(tableCatalog) val map = parse(jString).values.asInstanceOf[Map[String, _]] val tableMeta = map.get(table).get.asInstanceOf[Map[String, _]] val nSpace = tableMeta.get(nameSpace).getOrElse("default").asInstanceOf[String] val tName = tableMeta.get(tableName).get.asInstanceOf[String] val cIter = map.get(columns).get.asInstanceOf[Map[String, Map[String, String]]].toIterator val schemaMap = mutable.HashMap.empty[String, Field] cIter.foreach { case (name, column) => val sd = { column.get(serdes).asInstanceOf[Option[String]].map(n => Class.forName(n).newInstance().asInstanceOf[SerDes] ) } val len = column.get(length).map(_.toInt).getOrElse(-1) val sAvro = column.get(avro).map(parameters(_)) val f = Field(name, column.getOrElse(cf, rowKey), column.get(col).get, column.get(`type`), sAvro, sd, len) schemaMap.+=((name, f)) } val rKey = RowKey(map.get(rowKey).get.asInstanceOf[String]) HBaseTableCatalog(nSpace, tName, rKey, SchemaMap(schemaMap), parameters) } val TABLE_KEY: String = "hbase.table" val SCHEMA_COLUMNS_MAPPING_KEY: String = "hbase.columns.mapping" /* for backward compatibility. Convert the old definition to new json based definition formated as below val catalog = s"""{ |"table":{"namespace":"default", "name":"htable"}, |"rowkey":"key1:key2", |"columns":{ |"col1":{"cf":"rowkey", "col":"key1", "type":"string"}, |"col2":{"cf":"rowkey", "col":"key2", "type":"double"}, |"col3":{"cf":"cf1", "col":"col2", "type":"binary"}, |"col4":{"cf":"cf1", "col":"col3", "type":"timestamp"}, |"col5":{"cf":"cf1", "col":"col4", "type":"double", "serdes":"${classOf[DoubleSerDes].getName}"}, |"col6":{"cf":"cf1", "col":"col5", "type":"$map"}, |"col7":{"cf":"cf1", "col":"col6", "type":"$array"}, |"col8":{"cf":"cf1", "col":"col7", "type":"$arrayMap"} |} |}""".stripMargin */ @deprecated("Please use new json format to define HBaseCatalog") // TODO: There is no need to deprecate since this is the first release. def convert(parameters: Map[String, String]): Map[String, String] = { val tableName = parameters.get(TABLE_KEY).getOrElse(null) // if the hbase.table is not defined, we assume it is json format already. if (tableName == null) return parameters val schemaMappingString = parameters.getOrElse(SCHEMA_COLUMNS_MAPPING_KEY, "") import scala.collection.JavaConverters._ val schemaMap = generateSchemaMappingMap(schemaMappingString).asScala.map(_._2.asInstanceOf[SchemaQualifierDefinition]) val rowkey = schemaMap.filter { _.columnFamily == "rowkey" }.map(_.columnName) val cols = schemaMap.map { x => s""""${x.columnName}":{"cf":"${x.columnFamily}", "col":"${x.qualifier}", "type":"${x.colType}"}""".stripMargin } val jsonCatalog = s"""{ |"table":{"namespace":"default", "name":"${tableName}"}, |"rowkey":"${rowkey.mkString(":")}", |"columns":{ |${cols.mkString(",")} |} |} """.stripMargin parameters ++ Map(HBaseTableCatalog.tableCatalog->jsonCatalog) } /** * Reads the SCHEMA_COLUMNS_MAPPING_KEY and converts it to a map of * SchemaQualifierDefinitions with the original sql column name as the key * * @param schemaMappingString The schema mapping string from the SparkSQL map * @return A map of definitions keyed by the SparkSQL column name */ @InterfaceAudience.Private def generateSchemaMappingMap(schemaMappingString:String): java.util.HashMap[String, SchemaQualifierDefinition] = { println(schemaMappingString) try { val columnDefinitions = schemaMappingString.split(',') val resultingMap = new java.util.HashMap[String, SchemaQualifierDefinition]() columnDefinitions.map(cd => { val parts = cd.trim.split(' ') //Make sure we get three parts //<ColumnName> <ColumnType> <ColumnFamily:Qualifier> if (parts.length == 3) { val hbaseDefinitionParts = if (parts(2).charAt(0) == ':') { Array[String]("rowkey", parts(0)) } else { parts(2).split(':') } resultingMap.put(parts(0), new SchemaQualifierDefinition(parts(0), parts(1), hbaseDefinitionParts(0), hbaseDefinitionParts(1))) } else { throw new IllegalArgumentException("Invalid value for schema mapping '" + cd + "' should be '<columnName> <columnType> <columnFamily>:<qualifier>' " + "for columns and '<columnName> <columnType> :<qualifier>' for rowKeys") } }) resultingMap } catch { case e:Exception => throw new IllegalArgumentException("Invalid value for " + SCHEMA_COLUMNS_MAPPING_KEY + " '" + schemaMappingString + "'", e ) } } } /** * Construct to contains column data that spend SparkSQL and HBase * * @param columnName SparkSQL column name * @param colType SparkSQL column type * @param columnFamily HBase column family * @param qualifier HBase qualifier name */ @InterfaceAudience.Private case class SchemaQualifierDefinition(columnName:String, colType:String, columnFamily:String, qualifier:String)
NTCoding/playapitest
app/config/DependencyWiring.scala
package config import com.google.inject.AbstractModule import data.{DatabaseNotificationsRetriever, NotificationsRetriever} import slick.driver.MySQLDriver.api._ class DependencyWiring extends AbstractModule { override def configure() { bind(classOf[Database]).toInstance(Database.forConfig("chatroomz")) bind(classOf[NotificationsRetriever]).to(classOf[DatabaseNotificationsRetriever]) } }
NTCoding/playapitest
test/api/configuration/TestDatabase.scala
<filename>test/api/configuration/TestDatabase.scala package api.configuration object TestDatabase { val username = "chatty" val password = "<PASSWORD>" val dbName = "apitests" val dbUrl = s"jdbc:mysql://localhost:3306" }
NTCoding/playapitest
test/api/configuration/APITest.scala
package api.configuration import java.io.StringReader import java.sql.DriverManager import api.configuration.TestDatabase._ import com.ibatis.common.jdbc.ScriptRunner import org.scalatest.{BeforeAndAfterAll, FreeSpecLike, Matchers} import play.api.Play import play.api.Play.current import play.api.test.{DefaultAwaitTimeout, FutureAwaits, TestServer} import scala.io.Source import scala.util.Random trait APITest extends FreeSpecLike with Matchers with BeforeAndAfterAll with FutureAwaits with DefaultAwaitTimeout { val port: Int = 1000 + Random.nextInt(8999) val dbScript: String lazy val server: TestServer = CreateTestApplicationWithTestDB(port, dbScript) def startApi() = { info(s"Starting API test: ${getClass.getName} on port: ${server.port}") info(s"Running /db.sql against $dbUrl") DBScriptRunner.runDbScript(dbUrl, username, password, "/db.sql") info(s"Running $dbScript against $dbUrl") DBScriptRunner.runDbScript(dbUrl, username, password, dbScript) } override def afterAll() { server.stop() } } object DBScriptRunner { def runDbScript(url: String, username: String, password: String, resource: String) { Class.forName("com.mysql.jdbc.Driver") val con = DriverManager.getConnection(url, username, password) val sru = new ScriptRunner(con, false, false) val scr = Source.fromInputStream(Play.resourceAsStream(resource).get).getLines.toList.mkString("\n") val reader = new StringReader(scr.replace("use chatroomz;", s"use $dbName;")) sru.runScript(reader) } }
NTCoding/playapitest
test/api/notifications_latest.scala
<reponame>NTCoding/playapitest package api import api.configuration.APITest import play.api.Play.current import play.api.libs.json.{Format, Json} import play.api.libs.ws.WS class notifications_latest extends APITest { import TestData._ val dbScript = "/api/notifications.sql" "When requesting the latest notifications" - { startApi() val httpRes = await(WS.url(s"http://localhost:$port/notifications/latest").get()) "A 200 HTTP resonse is returned" in { assert(httpRes.status === 200) } "The most recent notifications are returned as JSON in the response body" in { val notifications = Json.parse(httpRes.body).as[Seq[APINotification]] assert(notifications === testNotifications) } } object TestData { implicit val f: Format[APINotification] = Json.format[APINotification] // These correspond to the insertions in "$dbScript" val testNotifications = Seq( APINotification("test room1", "user 1", "This room is so amazing", "2015-01-01 00:00:00.0"), APINotification("test room2", "user 2", "This room is so amazing", "2015-01-01 00:00:00.0"), APINotification("test room3", "user 3", "This room is so amazing", "2015-01-01 00:00:00.0"), APINotification("test room4", "user 4", "This room is so amazing", "2015-01-01 00:00:00.0"), APINotification("test room5", "user 5", "This room is so amazing", "2015-01-01 00:00:00.0"), APINotification("test room6", "user 6", "This room is so amazing", "2015-01-01 00:00:00.0"), APINotification("test room7", "user 7", "This room is so amazing", "2015-01-01 00:00:00.0"), APINotification("test room8", "user 8", "This room is so amazing", "2015-01-01 00:00:00.0"), APINotification("test room9", "user 9", "This room is so amazing", "2015-01-01 00:00:00.0"), APINotification("test room10", "user 10", "This room is so amazing", "2015-01-01 00:00:00.0") ) } } case class APINotification(room: String, sender: String, message: String, timestamp: String)
NTCoding/playapitest
app/controllers/Notifications.scala
package controllers import javax.inject.Inject import data.{Notification, NotificationsRetriever} import play.api.libs.concurrent.Execution.Implicits._ import play.api.libs.json.{Format, Json} import play.api.mvc._ class Notifications @Inject() (retriever: NotificationsRetriever) extends Controller { implicit val f: Format[Notification] = Json.format[Notification] def latest = Action.async { retriever.fetchLatest map { notifications => Ok(Json.toJson(notifications)) } } }
NTCoding/playapitest
build.sbt
name := """chatroomz""" version := "1.0-SNAPSHOT" lazy val root = (project in file(".")).enablePlugins(PlayScala) scalaVersion := "2.11.6" libraryDependencies ++= Seq( jdbc, cache, ws, "org.codehaus.jackson" % "jackson-mapper-asl" % "1.9.13", "com.fasterxml.jackson.module" %% "jackson-module-scala" % "2.5.2", "commons-io" % "commons-io" % "2.4", "com.typesafe.slick" %% "slick" % "3.1.0", "com.typesafe.slick" % "slick-hikaricp_2.11" % "3.1.0", "mysql" % "mysql-connector-java" % "5.1.35", "com.ibatis" % "ibatis2-common" % "2.1.7.597", "org.scalatest" % "scalatest_2.11" % "2.2.5" ) resolvers += "scalaz-bintray" at "http://dl.bintray.com/scalaz/releases" // Play provides two styles of routers, one expects its actions to be injected, the // other, legacy style, accesses its actions statically. routesGenerator := InjectedRoutesGenerator
NTCoding/playapitest
app/data/NotificationsRetriever.scala
package data import com.google.inject.Inject import slick.driver.MySQLDriver.api._ import slick.jdbc.GetResult import scala.concurrent.Future class DatabaseNotificationsRetriever @Inject() (db: Database) extends NotificationsRetriever { implicit val parser: GetResult[Notification] = GetResult(r => Notification(r.<<, r.<<, r.<<, r.<<) ) private val select = sql""" select room, username, message, timestamp from notifications order by timestamp desc limit 100 """ def fetchLatest = db.run(select.as[Notification]) } trait NotificationsRetriever { def fetchLatest: Future[Seq[Notification]] } case class Notification(room: String, sender: String, message: String, timestamp: String)
NTCoding/playapitest
test/api/configuration/CreateTestApplicationWithTestDB.scala
<gh_stars>0 package api.configuration import com.typesafe.config.ConfigFactory import play.api.inject._ import play.api.inject.guice.GuiceApplicationBuilder import play.api.test.TestServer import slick.driver.MySQLDriver.api._ import scala.collection.JavaConverters._ object CreateTestApplicationWithTestDB { import api.configuration.TestDatabase._ val m = Map( "chatroomz" -> Map( "url" -> s"$dbUrl/$dbName", "driver" -> "com.mysql.jdbc.Driver", "properties" -> Map( "user" -> username, "password" -> password).asJava, "numThreads" -> 10).asJava ).asJava val dbConfig = ConfigFactory.parseMap(m) def apply(port: Int, dbScript: String) = { val db = Database.forConfig("chatroomz", dbConfig) val app = new GuiceApplicationBuilder() .configure(Map("logger.root" -> "ERROR", "logger.application" -> "ERROR")) .overrides(bind[Database].toInstance(db)) // <- override binding in main app .build val server = TestServer(port, app) server.start() server } }
ethicssystems/examples
legacy/aws-scala-sbt/build.sbt
import sbtassembly.Log4j2MergeStrategy import sbtrelease.Version name := "hello" resolvers += Resolver.sonatypeRepo("public") scalaVersion := "2.13.1" releaseNextVersion := { ver => Version(ver).map(_.bumpMinor.string).getOrElse("Error") } assemblyJarName in assembly := "hello.jar" libraryDependencies ++= Seq( "com.amazonaws" % "aws-lambda-java-events" % "2.2.7", "com.amazonaws" % "aws-lambda-java-core" % "1.2.1", "com.amazonaws" % "aws-lambda-java-log4j2" % "1.5.1" ) scalacOptions ++= Seq( "-unchecked", "-deprecation", "-feature", "-Xfatal-warnings" ) assemblyMergeStrategy in assembly := { case PathList(ps @ _*) if ps.last == "Log4j2Plugins.dat" => Log4j2MergeStrategy.plugincache case x => val oldStrategy = (assemblyMergeStrategy in assembly).value oldStrategy(x) }
p44/Play-Kafka
app/com/processor44/tick/TickConsumer.scala
package com.processor44.tick import akka.actor.{Props, ActorLogging, Actor} import com.typesafe.config.ConfigFactory import java.util.Properties import kafka.consumer._ import kafka.message.MessageAndMetadata import play.api.Logger import play.api.libs.iteratee.Concurrent import play.api.libs.json.{Json, JsValue} /** * Consumes messages from kafka topic defined by config "producer.topic.name.tick" */ object TickConsumer { lazy val CONF = ConfigFactory.load lazy val ZOOKEEPER_CON = CONF.getString("zookeeper.connect") lazy val GROUP_ID = "1" lazy val CONSUMER_CONFIG = new ConsumerConfig(buildConsumerProps) def buildConsumerProps: Properties = { val p = new Properties() p.put("group.id", GROUP_ID) p.put("zookeeper.connect", ZOOKEEPER_CON) p.put("auto.commit.enable", "true") // If true, periodically commit to ZooKeeper the offset of messages already // fetched by the consumer. This committed offset will be used when the process fails as the position from which the // new consumer will begin. Default 60 seconds. p } // Consumer actor case object Consume case object Shutdown case object Test val propsTickConsumerActor = Props[TickConsumerActor] // To broadcast what is consumed from kafka out to web clients // tickOut is Enumerator[JsValue], tickChannel is Concurrent.Channel[JsValue] val (tickOut, tickChannel) = Concurrent.broadcast[JsValue] /** Conversion function for key bytes to String with null check */ def getKeyAsString(key: Array[Byte], charsetName: String = TickProducer.CHARSET): String = { if (key == null) "" else (new String(key, charsetName)) } } /** * Consumes from kafka topic defined by config "producer.topic.name.tick" * Feeds out to another stream */ class TickConsumerActor extends Actor with ActorLogging { val connector: ConsumerConnector = Consumer.create(TickConsumer.CONSUMER_CONFIG) /** */ def receive = { case TickConsumer.Test => if (log.isInfoEnabled) log.info("TickConsumer.Test!") case TickConsumer.Consume => { if (log.isInfoEnabled) log.info("TickConsumerActor consuming...") val topicStreamMap = connector.createMessageStreams(Map(TickProducer.TOPIC -> 1)) topicStreamMap.get(TickProducer.TOPIC) match { case None => log.error("TickConsumerActor NONE for Stream. Can't Consume.") case Some(streamList) => { val kStream: KafkaStream[Array[Byte], Array[Byte]] = streamList(0) iterateStream(kStream) } } } case TickConsumer.Shutdown => { if (log.isInfoEnabled) log.info("TickConsumerActor shutting down...") connector.shutdown } } /** * while (iter.hasNext()) ... consumeAndPublishOne for each * @param kStream */ def iterateStream(kStream: KafkaStream[Array[Byte], Array[Byte]]): Unit = { val iter: ConsumerIterator[Array[Byte], Array[Byte]] = kStream.iterator() while (iter.hasNext()) { consumeAndPublishOne(iter.next()) } } /** * * @param mam * @return */ def consumeAndPublishOne(mam: MessageAndMetadata[Array[Byte], Array[Byte]]): Boolean = { try { val k = TickConsumer.getKeyAsString(mam.key, TickProducer.CHARSET) val m = new String(mam.message, TickProducer.CHARSET) // back to string json if (log.isDebugEnabled) log.debug("consumed [" + k + " " + m + "] at partition " + mam.partition+ ", at offset " + mam.offset) TickConsumer.tickChannel.push(Json.parse(m)) // broadcast it true } catch { case t: Throwable => { Logger.error("consumeAndPublishOne ERROR ", t) false } } } }
p44/Play-Kafka
app/com/processor44/tick/TickSimpleConsumer.scala
<reponame>p44/Play-Kafka package com.processor44.tick import kafka.api.PartitionOffsetRequestInfo import kafka.common.{OffsetAndMetadata, TopicAndPartition} import kafka.javaapi.consumer.SimpleConsumer import kafka.javaapi.message.ByteBufferMessageSet import kafka.javaapi.{OffsetRequest, OffsetResponse} import kafka.message.{MessageAndOffset, Message} import play.api.Logger import scala.util.control.NonFatal /** * // https://people.apache.org/~junrao/kafka-0.8.2.0-candidate2/scaladoc/index.html#kafka.javaapi.consumer.SimpleConsumer */ object TickSimpleConsumer { val PARTITION_DEF = 0 val TO_DEF = 100000 // timeout val BUFF = 64 * 1024 // buffer size def newSimpleConsumer(host: String, port: Int, clientId: String): SimpleConsumer = { new SimpleConsumer(host, port, TO_DEF, BUFF, clientId) } /** * Usage: * getOffset(host, port, clientId, kafkaTopic, partition, kafka.api.OffsetRequest.LatestTime) * * @param host use TickProducer.BROKER_LIST_PARSED_HP(i)._1 * @param port use TickProducer.BROKER_LIST_PARSED_HP(i)._2 * @param clientId use TickConsumer.GROUP_ID * @param topic the topic from the config file def "tick" * @param partition for now use PARTITION_DEF; 0 * @param whichTime either kafka.api.OffsetRequest.{LatestTime, EarliestTime} * @return */ def getOffset(host: String, port: Int, clientId: String, topic: String, partition: Int, whichTime: Long): Option[OffsetResponse] = { val hpString = host + ":" + port withSimpleConsumer(host, port, clientId) { simpCo => val response = getOffset(simpCo, topic, partition, whichTime, clientId) if (Logger.isInfoEnabled) Logger.info("Good response in getOffset --> whichTime (" + whichTime + ") offset response [" + hpString + "]: " + response) return Some(response) } None } def getOffset(simpCo: SimpleConsumer, topic: String, partition: Int, whichTime: Long, clientId: String): OffsetResponse = { val oReq = buildOffsetRequest(topic, partition, whichTime, clientId) if (Logger.isDebugEnabled) { Logger.debug("OffsetRequest: " + oReq.toString) } simpCo.getOffsetsBefore(oReq) } def buildOffsetRequest(topic: String, partition: Int, whichTime: Long, clientId: String): OffsetRequest = { val partitionOffset = new PartitionOffsetRequestInfo(whichTime, 1) // 1 is maxNumOffsets val requestInfo = new java.util.HashMap[TopicAndPartition, PartitionOffsetRequestInfo] requestInfo.put((new TopicAndPartition(topic, partition)), partitionOffset) new OffsetRequest(requestInfo, kafka.api.OffsetRequest.CurrentVersion, clientId) } /** * Usage: * TickSimpleConsumer.getLastOffset(TickProducer.TOPIC, TickSimpleConsumer.PARTITION_DEF) * * Calls getOffset(host, port, clientId, kafkaTopic, partition, kafka.api.OffsetRequest.LatestTime) * with defaults: first host port found in Broker_List and TickConsumer.GROUP_ID as client id * * @param topic * @param partition * @return */ def getLastOffset(topic: String, partition: Int): Option[Long] = { val host = TickProducer.BROKER_LIST_PARSED_HP(0)._1 val port = TickProducer.BROKER_LIST_PARSED_HP(0)._2 val clientId = TickConsumer.GROUP_ID val oResponse = getOffset(host, port, clientId, topic, partition, kafka.api.OffsetRequest.LatestTime) oResponse match { case None => Logger.warn("None last offset"); None case Some(res) => res.hasError match { case true => Logger.error(res.toString); None case false => firstOffsetInArray(res.offsets(topic, partition)) } } } def firstOffsetInArray(offsets: Array[Long]): Option[Long] = { if (offsets.size > 0) Some(offsets(0)) else None } /** * Fetch Messages * * @param simpCo the simple consumer * @param clientId the client id a.k.a. client group id * @param topic the topic name * @param partition the partition * @param readOffset the offset to read from - starting point * @param fetchSize the number of messages to fetch */ def fetchMessages(simpCo: SimpleConsumer, clientId: String, topic: String, partition: Int, readOffset: Long, fetchSize: Int): kafka.javaapi.FetchResponse = { // addFetch(topic: String, partition: Int, offset: Long, fetchSize: Int) val req = (new kafka.api.FetchRequestBuilder()).clientId(clientId).addFetch(topic, partition, readOffset, fetchSize).build() simpCo.fetch(req) } /** * TODO iterator does not have next as expected - needs attention * * @param res * @param topic * @param partition * @return a map of valid messages as [offset -> (key, message)] */ def doFetchResponse(res: kafka.javaapi.FetchResponse, topic: String, partition: Int): Map[Long,(String, String)] = { if (res.hasError) { Map.empty[Long,(String, String)] } else { val bbms: ByteBufferMessageSet = res.messageSet(topic, partition) if (Logger.isDebugEnabled) Logger.debug("bbms " + bbms.sizeInBytes) val convertedMessages = scala.collection.mutable.Map[Long,(String, String)]() val iter = bbms.iterator() var numRead = 0 while (iter.hasNext) { println("XXX") val maos: MessageAndOffset = iter.next val currentOffset = maos.offset val readOffset = maos.nextOffset if (Logger.isDebugEnabled) Logger.debug ("currentOffset " + currentOffset + " readOffset " + readOffset) val message = maos.message if (Logger.isDebugEnabled) Logger.debug ("consumed " + message.toString + " at " + maos.offset) convertMessage(maos.offset, message).map(kvTuple => convertedMessages += (maos.offset -> kvTuple)) numRead += 1 } println("numRead " + numRead) if (numRead == 0) { // kafka recommended additional check try { Thread.sleep(1000) } catch { case e: InterruptedException => // do nothing } } convertedMessages.toMap[Long,(String, String)] } } def convertMessage(offset: Long, message: Message): Option[(String, String)] = { message.isValid match { case false => { if (Logger.isDebugEnabled) Logger.debug("invalid message at offset " + offset) None } case true => { message.hasKey match { case false => { Some(("", convertPayload(message))) } case true => { val k = TickConsumer.getKeyAsString(message.key.array(), TickProducer.CHARSET) Some((k, convertPayload(message))) } } } } } def convertPayload(message: Message): String = { message.isNull match { case false => "" case true => (new String(message.payload.array(), TickProducer.CHARSET)) } } /** * Calls fetchMessages withSimpleConsumer * * @param topic * @param partition * @param fetchSize * @return */ def fetchLastMessages(topic: String, partition: Int, fetchSize: Int): Map[Long,(String, String)] = { val host = TickProducer.BROKER_LIST_PARSED_HP(0)._1 val port = TickProducer.BROKER_LIST_PARSED_HP(0)._2 val clientId = TickConsumer.GROUP_ID getLastOffset(topic, partition).map { lastOffset => val startingOffset = lastOffset - fetchSize - 1L if (Logger.isDebugEnabled) Logger.debug("fetchLastMessages startingOffset " + startingOffset) val hpString = host + ":" + port withSimpleConsumer(host, port, clientId) { simpCo => val fetchResponse = fetchMessages(simpCo, clientId, topic, partition, startingOffset, fetchSize) if (Logger.isInfoEnabled) Logger.info("Good response in fetchLastMessages --> fetchSize (" + fetchSize + ") offset response [" + hpString + "]: error? " + fetchResponse.hasError) val x = doFetchResponse(fetchResponse, topic, partition) return x } } Map.empty[Long,(String, String)] } /** * NOTE: assumes a single broker single partition topic, first in TickProducer.BROKER_LIST_PARSED_HP * Uses these: * val host = TickProducer.BROKER_LIST_PARSED_HP(0)._1 * val port = TickProducer.BROKER_LIST_PARSED_HP(0)._2 * val clientId = TickConsumer.GROUP_ID * * Usage: * TickSimpleConsumer.resetOffset(TickProducer.TOPIC, TickSimpleConsumer.PARTITION_DEF, resetTo) * * @param topic * @param partition * @param offset * @return */ def resetOffset(topic: String, partition: Int, offset: Long): Option[Long] = { val host = TickProducer.BROKER_LIST_PARSED_HP(0)._1 val port = TickProducer.BROKER_LIST_PARSED_HP(0)._2 val clientId = TickConsumer.GROUP_ID resetOffset(host, port, clientId, (new TopicAndPartition(topic, partition)), OffsetAndMetadata(offset)) } /** * Builds an OffsetCommitRequest * Calls simpCo.CommitOffsets() using withSimpleConsumer * * @param host * @param port * @param clientId * @param tp * @param om * @return */ def resetOffset(host: String, port: Int, clientId: String, tp: TopicAndPartition, om: OffsetAndMetadata): Option[Long] = { var result = Map[TopicAndPartition, Short]() val curVer = kafka.api.OffsetRequest.CurrentVersion val tpOmMap = new java.util.HashMap[TopicAndPartition,OffsetAndMetadata]() tpOmMap.put(tp, om) val req = new kafka.javaapi.OffsetCommitRequest(clientId, tpOmMap, 0, clientId, curVer) val hpString = host + ":" + port withSimpleConsumer(host, port, clientId) { simpCo => val resp: kafka.javaapi.OffsetCommitResponse = simpCo.commitOffsets(req) resp.hasError match { case true => { Logger.error("resetOffset ERROR --> tp (" + tp + ") hp [" + hpString + "] code: " + resp.errorCode(tp)) return None } case false => { if (Logger.isDebugEnabled) Logger.debug("resetOffset SUCCESS --> tp (" + tp + ") hp [" + hpString + "] new offset " + om.offset) return Some(om.offset) } } } None } /** * Function for calling functions on SimpleConsumer with exception handling. * * @param host * @param port * @param clientId * @param func * @return */ private def withSimpleConsumer(host: String, port: Int, clientId: String)(func: SimpleConsumer => Any): Unit = { var simpCo: SimpleConsumer = null try { simpCo = newSimpleConsumer(host, port, clientId) func.apply(simpCo) } catch { case NonFatal(e) => { val hpString = host + ":" + port Logger.error("Error in withSimpleConsumer --> clientId (" + clientId + ") hp [" + hpString + "]", e) } } finally { if (simpCo != null) { if (Logger.isDebugEnabled) Logger.debug("simpCo.close()") simpCo.close() } } } }
p44/Play-Kafka
app/com/processor44/PkGlobal.scala
<filename>app/com/processor44/PkGlobal.scala package com.processor44 import akka.actor.ActorPath import com.processor44.tick.TickConsumer import play.api._ import play.api.libs.concurrent.Akka import play.api.Play.current /** * Created by markwilson on 3/13/15. */ object PkGlobal { var pathTickConsumer = "/user/TickConsumer" def onStart(): Unit = { Logger.debug("PkGlobal.onStart") val a = Akka.system.actorOf(TickConsumer.propsTickConsumerActor, "TickConsumer") //println(a.path) val testA = Akka.system.actorSelection(pathTickConsumer) testA ! TickConsumer.Test a ! TickConsumer.Consume } def onStop(): Unit = { Logger.debug("PkGlobal.onStop") val a = Akka.system.actorSelection(pathTickConsumer) a ! TickConsumer.Test a ! TickConsumer.Shutdown Akka.system.shutdown() Akka.system.awaitTermination() } }
p44/Play-Kafka
build.sbt
<reponame>p44/Play-Kafka<gh_stars>1-10 name := """Play-Kafka""" version := "1.0-SNAPSHOT" lazy val root = (project in file(".")).enablePlugins(PlayScala) scalaVersion := "2.11.1" libraryDependencies ++= Seq( "org.apache.kafka" % "kafka_2.11" % "0.8.2.1" )
p44/Play-Kafka
app/controllers/Application.scala
<gh_stars>1-10 package controllers import com.processor44.models.{ViewModels, Msg, Tick} import com.processor44.tick.{TickSimpleConsumer, TickConsumer, TickProducer} import play.api._ import play.api.libs.EventSource import play.api.libs.iteratee.{Concurrent, Enumeratee} import play.api.libs.json.{JsValue, Json} import play.api.mvc._ import scala.concurrent.Future import scala.concurrent.ExecutionContext.Implicits.global object Application extends Controller { def index = Action { Ok(views.html.index()) } /** * Uses server timestamp to create a tick obj then produces it to kafka * @return */ def putGenTick = Action.async { request => // Send it to Kafka TickProducer.produce(Tick(System.currentTimeMillis())).map { r => r match { case false => InternalServerError(ViewModels.MSG_ERROR_JSON) case true => Ok(ViewModels.MSG_SUCCESS_JSON) } } } def getLastOffset = Action.async { request => Future { TickSimpleConsumer.getLastOffset(TickProducer.TOPIC, TickSimpleConsumer.PARTITION_DEF) match { case None => InternalServerError(ViewModels.MSG_ERROR_JSON) case Some(offset) => Ok(Json.prettyPrint(Json.toJson[Msg](Msg("Last Offset: " + offset)))) } } } def getLastMessages(count: Int) = Action.async { request => Future { val r: Map[Long,(String, String)] = TickSimpleConsumer.fetchLastMessages(TickProducer.TOPIC, TickSimpleConsumer.PARTITION_DEF, count) r.isEmpty match { case true => Ok(Json.prettyPrint(Json.toJson[Msg](Msg("Empty Results")))) case false => Ok(Json.prettyPrint(Json.toJson[Msg](Msg("Last Offset: " + r.mkString(" "))))) } } } def getResetOffset(back: Int) = Action.async { request => Future { TickSimpleConsumer.getLastOffset(TickProducer.TOPIC, TickSimpleConsumer.PARTITION_DEF) match { case None => InternalServerError(ViewModels.MSG_ERROR_JSON) case Some(offset) => { val resetTo: Long = calcResetBack(offset, back) TickSimpleConsumer.resetOffset(TickProducer.TOPIC, TickSimpleConsumer.PARTITION_DEF, resetTo) match { case None => InternalServerError(ViewModels.MSG_ERROR_JSON) case Some(newOffset) => { if (Logger.isDebugEnabled) Logger.debug("getResetOffset last offset " + offset + " newOffset " + newOffset) Ok(Json.prettyPrint(Json.toJson[Msg](Msg("Last Offset: " + offset+ " newOffset " + newOffset)))) } } } } } } def calcResetBack(offset: Long, back: Int): Long = { val nOffset = offset - back nOffset < 0 match { case true => 0L case false => nOffset } } // Tick Feed - The Tick consumer will put to the tick chanel json pulled from kafka /** Enumeratee for detecting disconnect of the stream */ def logDisconnect(addr: String): Enumeratee[JsValue, JsValue] = { Enumeratee.onIterateeDone { () => Logger.info(addr + " - tickOut disconnected") } } /** Controller action serving activity for tick json consumed from kafka */ def tickFeed = Action { req => Logger.info("FEED tick - " + req.remoteAddress + " - tick connected") Ok.chunked(TickConsumer.tickOut &> Concurrent.buffer(100) &> logDisconnect(req.remoteAddress) &> EventSource()).as("text/event-stream") // &> Compose this Enumerator with an Enumeratee. Alias for through } }
p44/Play-Kafka
app/com/processor44/tick/TickProducer.scala
<reponame>p44/Play-Kafka<filename>app/com/processor44/tick/TickProducer.scala package com.processor44.tick import com.processor44.models.Tick import com.typesafe.config.ConfigFactory import java.util.Properties import kafka.producer.{KeyedMessage, ProducerConfig, Producer} import play.api.Logger import play.api.libs.json.Json import scala.concurrent.Future import scala.concurrent.ExecutionContext.Implicits.global /** * Produces messages to kafka topic defined by config "producer.topic.name.tick" */ object TickProducer { val CHARSET = "UTF-8" lazy val CONF = ConfigFactory.load lazy val TOPIC = CONF.getString("kafka.topic.name.tick") lazy val BROKER_LIST = CONF.getString("producer.metadata.broker.list") lazy val BROKER_LIST_PARSED: List[String] = parseBrokersToString lazy val BROKER_LIST_PARSED_HP: List[(String, Int)] = parseBrokersToHostPort // http://kafka.apache.org/documentation.html#producerconfigs // "serializer.class" default is kafka.serializer.DefaultEncoder Array[Byte] to Array[Byte] val props = new Properties() props.put("metadata.broker.list", BROKER_LIST) props.put("request.required.acks", "1") // 1 is leader received props.put("producer.type", "sync") props.put("compression.codec", "none") props.put("message.send.max.retries", "3") val PRODUCER = new Producer[AnyRef, AnyRef](new ProducerConfig(props)) def parseBrokersToString: List[String] = { val all = BROKER_LIST.split(",") all.map(_.trim).toList } def parseBrokersToHostPort: List[(String, Int)] = { val r = BROKER_LIST_PARSED.map { s => val hp = s.split(":") (hp(0), hp(1).toInt) } r.toList } /** * Converts to json and calls produce(message: String) * * @param tick */ def produce(tick: Tick): Future[Boolean] = { val message = Json.stringify(Json.toJson(tick)) produce(tick.ts.toString, message) } /** * Calls PRODUCER.send(new KeyedMessage(TOPIC, message.getBytes(CHARSET))) * * @param key as String * @param message assumes verified json */ def produce(key: String, message: String): Future[Boolean] = { if (Logger.isDebugEnabled) Logger.debug("producing " + key + " " + message) val km: KeyedMessage[AnyRef, AnyRef] = new KeyedMessage(TOPIC, key.getBytes(CHARSET), message.getBytes(CHARSET)) send(message, km) } /** * Produce just message with no key. Key will be null upon consume * * @param message * @return */ def produce(message: String): Future[Boolean] = { if (Logger.isDebugEnabled) Logger.debug("producing " + message) val km: KeyedMessage[AnyRef, AnyRef] = new KeyedMessage(TOPIC, message.getBytes(CHARSET)) send(message, km) } /** * * @param message * @param km * @return */ def send(message: String, km: KeyedMessage[AnyRef, AnyRef]): Future[Boolean] = { Future { try { PRODUCER.send(km) true } catch { case t: Throwable => { Logger.error("Failed to send " + message, t) false } } } } }
p44/Play-Kafka
app/Global.scala
import play.api.GlobalSettings import com.processor44.PkGlobal /** */ object Global extends GlobalSettings { override def onStart(app: play.api.Application) { println("Global.onStart") PkGlobal.onStart } override def onStop(app: play.api.Application) { println("Global.onStop") PkGlobal.onStop } }
mkoester/play_2.5.8_query_parameter_parsing_error
app/controllers/TestController.scala
package controllers import javax.inject.{Inject, Singleton} import play.api.mvc.{Action, Controller} @Singleton class TestController @Inject() extends Controller { def testOptionString(stringOption: Option[String]) = Action { Ok(stringOption.toString) } def testString(string: String) = Action { Ok(string) } }
armanbilge/ip4s
shared/src/main/scala-2/Literals.scala
<reponame>armanbilge/ip4s /* * Copyright 2018 Comcast Cable Communications Management, LLC * * 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 com.comcast.ip4s import org.typelevel.literally.Literally /** Macros that support literal string interpolators. */ object Literals { object ip extends Literally[IpAddress] { def validate(c: Context)(s: String) = { import c.universe._ IpAddress.fromString(s) match { case Some(_) => Right(c.Expr(q"_root_.com.comcast.ip4s.IpAddress.fromString($s).get")) case None => Left("invalid IP address") } } def make(c: Context)(args: c.Expr[Any]*): c.Expr[IpAddress] = apply(c)(args: _*) } object ipv4 extends Literally[Ipv4Address] { def validate(c: Context)(s: String) = { import c.universe._ Ipv4Address.fromString(s) match { case Some(_) => Right(c.Expr(q"_root_.com.comcast.ip4s.Ipv4Address.fromString($s).get")) case None => Left("invalid IPv4 address") } } def make(c: Context)(args: c.Expr[Any]*): c.Expr[Ipv4Address] = apply(c)(args: _*) } object ipv6 extends Literally[Ipv6Address] { def validate(c: Context)(s: String) = { import c.universe._ Ipv6Address.fromString(s) match { case Some(_) => Right(c.Expr(q"_root_.com.comcast.ip4s.Ipv6Address.fromString($s).get")) case None => Left("invalid IPv6 address") } } def make(c: Context)(args: c.Expr[Any]*): c.Expr[Ipv6Address] = apply(c)(args: _*) } object mip extends Literally[Multicast[IpAddress]] { def validate(c: Context)(s: String) = { import c.universe._ IpAddress.fromString(s).flatMap(_.asMulticast) match { case Some(_) => Right(c.Expr(q"_root_.com.comcast.ip4s.IpAddress.fromString($s).get.asMulticast.get")) case None => Left("invalid IP multicast address") } } def make(c: Context)(args: c.Expr[Any]*): c.Expr[Multicast[IpAddress]] = apply(c)(args: _*) } object mipv4 extends Literally[Multicast[Ipv4Address]] { def validate(c: Context)(s: String) = { import c.universe._ Ipv4Address.fromString(s).flatMap(_.asMulticast) match { case Some(_) => Right(c.Expr(q"_root_.com.comcast.ip4s.Ipv4Address.fromString($s).get.asMulticast.get")) case None => Left("invalid IPv4 multicast address") } } def make(c: Context)(args: c.Expr[Any]*): c.Expr[Multicast[Ipv4Address]] = apply(c)(args: _*) } object mipv6 extends Literally[Multicast[Ipv6Address]] { def validate(c: Context)(s: String) = { import c.universe._ Ipv6Address.fromString(s).flatMap(_.asMulticast) match { case Some(_) => Right(c.Expr(q"_root_.com.comcast.ip4s.Ipv6Address.fromString($s).get.asMulticast.get")) case None => Left("invalid IPv6 multicast address") } } def make(c: Context)(args: c.Expr[Any]*): c.Expr[Multicast[Ipv6Address]] = apply(c)(args: _*) } object ssmip extends Literally[SourceSpecificMulticast[IpAddress]] { def validate(c: Context)(s: String) = { import c.universe._ IpAddress.fromString(s).flatMap(_.asSourceSpecificMulticast) match { case Some(_) => Right(c.Expr(q"_root_.com.comcast.ip4s.IpAddress.fromString($s).get.asSourceSpecificMulticast.get")) case None => Left("invalid source specific IP multicast address") } } def make(c: Context)(args: c.Expr[Any]*): c.Expr[SourceSpecificMulticast[IpAddress]] = apply(c)(args: _*) } object ssmipv4 extends Literally[SourceSpecificMulticast[Ipv4Address]] { def validate(c: Context)(s: String) = { import c.universe._ Ipv4Address.fromString(s).flatMap(_.asSourceSpecificMulticast) match { case Some(_) => Right(c.Expr(q"_root_.com.comcast.ip4s.Ipv4Address.fromString($s).get.asSourceSpecificMulticast.get")) case None => Left("invalid source specific IPv4 multicast address") } } def make(c: Context)(args: c.Expr[Any]*): c.Expr[SourceSpecificMulticast[Ipv4Address]] = apply(c)(args: _*) } object ssmipv6 extends Literally[SourceSpecificMulticast[Ipv6Address]] { def validate(c: Context)(s: String) = { import c.universe._ Ipv6Address.fromString(s).flatMap(_.asSourceSpecificMulticast) match { case Some(_) => Right(c.Expr(q"_root_.com.comcast.ip4s.Ipv6Address.fromString($s).get.asSourceSpecificMulticast.get")) case None => Left("invalid source specific IPv6 multicast address") } } def make(c: Context)(args: c.Expr[Any]*): c.Expr[SourceSpecificMulticast[Ipv6Address]] = apply(c)(args: _*) } object port extends Literally[Port] { def validate(c: Context)(s: String) = { import c.universe._ scala.util.Try(s.toInt).toOption.flatMap(Port.fromInt) match { case Some(_) => Right(c.Expr(q"_root_.com.comcast.ip4s.Port.fromInt($s.toInt).get")) case None => Left("invalid port") } } def make(c: Context)(args: c.Expr[Any]*): c.Expr[Port] = apply(c)(args: _*) } object hostname extends Literally[Hostname] { def validate(c: Context)(s: String) = { import c.universe._ Hostname.fromString(s) match { case Some(_) => Right(c.Expr(q"_root_.com.comcast.ip4s.Hostname.fromString($s).get")) case None => Left("invalid hostname") } } def make(c: Context)(args: c.Expr[Any]*): c.Expr[Hostname] = apply(c)(args: _*) } object idn extends Literally[IDN] { def validate(c: Context)(s: String) = { import c.universe._ IDN.fromString(s) match { case Some(_) => Right(c.Expr(q"_root_.com.comcast.ip4s.IDN.fromString($s).get")) case None => Left("invalid IDN") } } def make(c: Context)(args: c.Expr[Any]*): c.Expr[IDN] = apply(c)(args: _*) } }
armanbilge/ip4s
test-kit/shared/src/main/scala/com/comcast/ip4s/Arbitraries.scala
/* * Copyright 2018 Comcast Cable Communications Management, LLC * * 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 com.comcast.ip4s import org.scalacheck.{Arbitrary, Gen} object Arbitraries { val ipv4Generator: Gen[Ipv4Address] = for { bytes <- Gen.listOfN(4, Arbitrary.arbitrary[Byte]) } yield Ipv4Address.fromBytes(bytes.toArray).get implicit val ipv4Arbitrary: Arbitrary[Ipv4Address] = Arbitrary(ipv4Generator) val ipv6Generator: Gen[Ipv6Address] = for { bytes <- Gen.listOfN(16, Arbitrary.arbitrary[Byte]) } yield Ipv6Address.fromBytes(bytes.toArray).get implicit val ipv6Arbitrary: Arbitrary[Ipv6Address] = Arbitrary(ipv6Generator) val ipGenerator: Gen[IpAddress] = Gen.oneOf(ipv4Generator, ipv6Generator) implicit val ipArbitrary: Arbitrary[IpAddress] = Arbitrary(ipGenerator) def cidrGenerator[A <: IpAddress](genIp: Gen[A]): Gen[Cidr[A]] = for { ip <- genIp bitLength = ip.fold(_ => 32, _ => 128) prefix <- Gen.chooseNum(0, bitLength) } yield ip / prefix implicit def cidrArbitrary[A <: IpAddress](implicit arbIp: Arbitrary[A]): Arbitrary[Cidr[A]] = Arbitrary(cidrGenerator(arbIp.arbitrary)) val portGenerator: Gen[Port] = Gen.chooseNum(0, 65535).map(Port.fromInt(_).get) implicit val portArbitrary: Arbitrary[Port] = Arbitrary(portGenerator) def socketAddressGenerator[A <: IpAddress](genIp: Gen[A], genPort: Gen[Port]): Gen[SocketAddress[A]] = for { ip <- genIp port <- genPort } yield SocketAddress(ip, port) implicit def socketAddressArbitrary[A <: IpAddress](implicit arbIp: Arbitrary[A], arbPort: Arbitrary[Port] ): Arbitrary[SocketAddress[A]] = Arbitrary(socketAddressGenerator(arbIp.arbitrary, arbPort.arbitrary)) val multicastGenerator4: Gen[Multicast[Ipv4Address]] = for { ip <- ipv4Generator } yield Ipv4Address.fromLong(ip.toLong & ~(15 << 28) | (14 << 28)).asMulticast.get implicit val multicastArbitrary4: Arbitrary[Multicast[Ipv4Address]] = Arbitrary(multicastGenerator4) val multicastGenerator6: Gen[Multicast[Ipv6Address]] = for { ip <- ipv6Generator } yield Ipv6Address.fromBigInt(ip.toBigInt & ~(BigInt(255) << 120) | (BigInt(255) << 120)).asMulticast.get implicit val multicastArbitrary6: Arbitrary[Multicast[Ipv6Address]] = Arbitrary(multicastGenerator6) val multicastGenerator: Gen[Multicast[IpAddress]] = Gen.oneOf(multicastGenerator4, multicastGenerator6) implicit val multicastArbitrary: Arbitrary[Multicast[IpAddress]] = Arbitrary(multicastGenerator) def multicastJoinGenerator[A <: IpAddress](genSource: Gen[A], genGroup: Gen[Multicast[A]]): Gen[MulticastJoin[A]] = genGroup.flatMap { group => group.address.asSourceSpecificMulticast match { case Some(grp) => genSource.filter(_.getClass == grp.getClass).flatMap(src => MulticastJoin.ssm(src, grp)) case None => MulticastJoin.asm(group) } } implicit def multicastJoinArbitrary[A <: IpAddress](implicit arbSource: Arbitrary[A], arbGroup: Arbitrary[Multicast[A]] ): Arbitrary[MulticastJoin[A]] = Arbitrary(multicastJoinGenerator(arbSource.arbitrary, arbGroup.arbitrary)) def multicastSocketAddressGenerator[A <: IpAddress]( genJoin: Gen[MulticastJoin[A]], genPort: Gen[Port] ): Gen[MulticastSocketAddress[MulticastJoin, A]] = for { join <- genJoin port <- genPort } yield MulticastSocketAddress(join, port) implicit def multicastSocketAddressArbitrary[A <: IpAddress](implicit arbJoin: Arbitrary[MulticastJoin[A]], arbPort: Arbitrary[Port] ): Arbitrary[MulticastSocketAddress[MulticastJoin, A]] = Arbitrary(multicastSocketAddressGenerator(arbJoin.arbitrary, arbPort.arbitrary)) val hostnameGenerator: Gen[Hostname] = { val genLabel: Gen[String] = for { first <- Gen.alphaNumChar middleLen <- Gen.chooseNum(0, 61) middle <- Gen.listOfN(middleLen, Gen.oneOf(Gen.alphaNumChar, Gen.const('-'))).map(_.mkString) last <- if (middleLen > 0) Gen.alphaNumChar.map(Some(_)) else Gen.option(Gen.alphaNumChar) } yield first.toString + middle + last.fold("")(_.toString) for { numLabels <- Gen.chooseNum(1, 5) labels <- Gen.listOfN(numLabels, genLabel) if labels.foldLeft(0)(_ + _.size) < (253 - (numLabels - 1)) } yield Hostname.fromString(labels.mkString(".")).get } implicit val hostnameArbitrary: Arbitrary[Hostname] = Arbitrary(hostnameGenerator) lazy val idnGenerator: Gen[IDN] = { val genChar: Gen[Char] = Gen.oneOf(Gen.alphaNumChar, Gen.const('δ'), Gen.const('π'), Gen.const('θ')) val genLabel: Gen[String] = for { first <- genChar middleLen <- Gen.chooseNum(0, 61) middle <- Gen.listOfN(middleLen, Gen.oneOf(genChar, Gen.const('-'))).map(_.mkString) last <- if (middleLen > 0) genChar.map(Some(_)) else Gen.option(genChar) str = first.toString + middle + last.fold("")(_.toString) if IDN.toAscii(str).size < 64 } yield str for { numLabels <- Gen.chooseNum(1, 5) labels <- Gen.listOfN(numLabels, genLabel) dot <- Gen.oneOf('.', '\u002e', '\u3002', '\uff0e', '\uff61') idn = IDN.fromString(labels.mkString(dot.toString)) if idn.isDefined } yield idn.get } implicit def idnArbitrary: Arbitrary[IDN] = Arbitrary(idnGenerator) val macAddressGenerator: Gen[MacAddress] = for { bytes <- Gen.listOfN(6, Arbitrary.arbitrary[Byte]) } yield MacAddress.fromBytes(bytes.toArray).get implicit val macAddressArbitrary: Arbitrary[MacAddress] = Arbitrary(macAddressGenerator) }
armanbilge/ip4s
shared/src/main/scala/com/comcast/ip4s/Dns.scala
/* * Copyright 2018 Comcast Cable Communications Management, LLC * * 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 com.comcast.ip4s /** Capability for an effect `F[_]` which can do DNS lookups. * * An instance is available for any effect which has a `Sync` instance on JVM and `Async` on Node.js. */ sealed trait Dns[F[_]] { /** Resolves the supplied hostname to an ip address using the platform DNS resolver. * * If the hostname cannot be resolved, the effect fails with an `UnknownHostException`. */ def resolve(hostname: Hostname): F[IpAddress] /** Resolves the supplied hostname to an ip address using the platform DNS resolver. * * If the hostname cannot be resolved, a `None` is returned. */ def resolveOption(hostname: Hostname): F[Option[IpAddress]] /** Resolves the supplied hostname to all ip addresses known to the platform DNS resolver. * * If the hostname cannot be resolved, an empty list is returned. */ def resolveAll(hostname: Hostname): F[List[IpAddress]] /** Reverses the supplied address to a hostname using the platform DNS resolver. * * If the address cannot be reversed, the effect fails with an `UnknownHostException`. */ def reverse(address: IpAddress): F[Hostname] /** Reverses the supplied address to a hostname using the platform DNS resolver. * * If the address cannot be reversed, a `None` is returned. */ def reverseOption(address: IpAddress): F[Option[Hostname]] /** Reverses the supplied address to all hostnames known to the platform DNS resolver. * * If the address cannot be reversed, an empty list is returned. */ def reverseAll(address: IpAddress): F[List[Hostname]] /** Gets an IP address representing the loopback interface. */ def loopback: F[IpAddress] } private[ip4s] trait UnsealedDns[F[_]] extends Dns[F] object Dns extends DnsCompanionPlatform { def apply[F[_]](implicit F: Dns[F]): F.type = F }
armanbilge/ip4s
js/src/main/scala/com/comcast/ip4s/DnsPlatform.scala
/* * Copyright 2018 Comcast Cable Communications Management, LLC * * 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 com.comcast.ip4s import cats.effect.kernel.Async import cats.syntax.all._ import scala.scalajs.js import scala.scalajs.js.| import scala.scalajs.js.annotation.JSImport private[ip4s] trait DnsCompanionPlatform { implicit def forAsync[F[_]](implicit F: Async[F]): Dns[F] = new UnsealedDns[F] { def resolve(hostname: Hostname): F[IpAddress] = F.fromPromise(F.delay(dnsPromises.lookup(hostname.toString, LookupOptions(all = false)))) .flatMap { address => IpAddress .fromString(address.asInstanceOf[LookupResult].address) .liftTo[F](new RuntimeException("Node.js returned invalid IP address")) } .adaptError { case ex @ js.JavaScriptException(error: js.Error) if error.message.contains("ENOTFOUND") => new JavaScriptUnknownHostException(hostname.toString, ex) } def resolveOption(hostname: Hostname): F[Option[IpAddress]] = resolve(hostname).map(_.some).recover { case _: UnknownHostException => None } def resolveAll(hostname: Hostname): F[List[IpAddress]] = F.fromPromise(F.delay(dnsPromises.lookup(hostname.toString, LookupOptions(all = true)))) .flatMap { addresses => addresses .asInstanceOf[js.Array[LookupResult]] .toList .traverse { address => IpAddress .fromString(address.address) .liftTo[F](new RuntimeException("Node.js returned invalid IP address")) } } .recover { case js.JavaScriptException(error: js.Error) if error.message.contains("ENOTFOUND") => Nil } def reverse(address: IpAddress): F[Hostname] = reverseAllOrError(address).flatMap(_.headOption.liftTo(new UnknownHostException(address.toString))) def reverseOption(address: IpAddress): F[Option[Hostname]] = reverseAll(address).map(_.headOption) def reverseAll(address: IpAddress): F[List[Hostname]] = reverseAllOrError(address).recover { case _: UnknownHostException => Nil } private def reverseAllOrError(address: IpAddress): F[List[Hostname]] = F.fromPromise(F.delay(dnsPromises.reverse(address.toString))) .flatMap { hostnames => hostnames.toList.traverse { hostname => Hostname .fromString(hostname) .liftTo[F](new RuntimeException("Node.js returned invalid hostname")) } } .adaptError { case ex @ js.JavaScriptException(error: js.Error) if error.message.contains("ENOTFOUND") => new JavaScriptUnknownHostException(address.toString, ex) } def loopback: F[IpAddress] = resolve(Hostname.fromString("localhost").get) } } @js.native @JSImport("dns", "promises") private[ip4s] object dnsPromises extends js.Any { def lookup(hostname: String, options: LookupOptions): js.Promise[LookupResult | js.Array[LookupResult]] = js.native def reverse(ip: String): js.Promise[js.Array[String]] = js.native } private[ip4s] sealed trait LookupOptions extends js.Object object LookupOptions { def apply(all: Boolean): LookupOptions = js.Dynamic.literal(all = all).asInstanceOf[LookupOptions] } @js.native private[ip4s] sealed trait LookupResult extends js.Object { def address: String = js.native def family: Int = js.native }
armanbilge/ip4s
test-kit/shared/src/test/scala/com/comcast/ip4s/DnsTest.scala
/* * Copyright 2018 Comcast Cable Communications Management, LLC * * 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 com.comcast.ip4s import cats.effect.IO import cats.syntax.all._ import munit.CatsEffectSuite class DnsTest extends CatsEffectSuite { test("resolve/reverseAll round-trip") { for { hostname <- Hostname.fromString("comcast.com").liftTo[IO](new NoSuchElementException) address <- Dns[IO].resolve(hostname) hostnames <- Dns[IO].reverseAll(address) _ <- IO(assert(hostnames.nonEmpty)) reversedAddress <- hostnames.traverse(Dns[IO].resolve) } yield assert(reversedAddress.forall(_ == address)) } test("resolveAll/reverse round-trip") { for { hostname <- Hostname.fromString("comcast.com").liftTo[IO](new NoSuchElementException) addresses <- Dns[IO].resolveAll(hostname) _ <- IO(assert(addresses.nonEmpty)) hostnames <- addresses.traverse(Dns[IO].reverse) reversedAddresses <- hostnames.traverse(Dns[IO].resolve) } yield assertEquals(Set(addresses), Set(reversedAddresses)) } test("loopback") { assertIO(Dns[IO].loopback.map(_.some), IpAddress.fromString("127.0.0.1")) } }
armanbilge/ip4s
jvm/src/main/scala/com/comcast/ip4s/DnsPlatform.scala
<gh_stars>100-1000 /* * Copyright 2018 Comcast Cable Communications Management, LLC * * 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 com.comcast.ip4s import cats.effect.kernel.Sync import cats.syntax.all._ import java.net.InetAddress private[ip4s] trait DnsCompanionPlatform { implicit def forSync[F[_]](implicit F: Sync[F]): Dns[F] = new UnsealedDns[F] { def resolve(hostname: Hostname): F[IpAddress] = F.blocking { val addr = InetAddress.getByName(hostname.toString) IpAddress.fromBytes(addr.getAddress).get } def resolveOption(hostname: Hostname): F[Option[IpAddress]] = resolve(hostname).map(_.some).recover { case _: UnknownHostException => None } def resolveAll(hostname: Hostname): F[List[IpAddress]] = F.blocking { try { val addrs = InetAddress.getAllByName(hostname.toString) addrs.toList.flatMap(addr => IpAddress.fromBytes(addr.getAddress)) } catch { case _: UnknownHostException => Nil } } def reverse(address: IpAddress): F[Hostname] = F.blocking { address.toInetAddress.getCanonicalHostName } flatMap { hn => // getCanonicalHostName returns the IP address as a string on failure Hostname.fromString(hn).liftTo[F](new UnknownHostException(address.toString)) } def reverseOption(address: IpAddress): F[Option[Hostname]] = reverse(address).map(_.some).recover { case _: UnknownHostException => None } def reverseAll(address: IpAddress): F[List[Hostname]] = reverseOption(address).map(_.toList) def loopback: F[IpAddress] = F.blocking(IpAddress.fromInetAddress(InetAddress.getByName(null))) } }
armanbilge/ip4s
test-kit/shared/src/test/scala/com/comcast/ip4s/MacAddressTest.scala
<reponame>armanbilge/ip4s<gh_stars>100-1000 /* * Copyright 2018 Comcast Cable Communications Management, LLC * * 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 com.comcast.ip4s import org.scalacheck.{Arbitrary, Gen, Prop} import Prop.forAll import Arbitraries._ class MacAddressTest extends BaseTestSuite { test("roundtrip through string") { forAll(Gen.listOfN(6, Arbitrary.arbitrary[Byte])) { bytesList => if (bytesList.size == 6) { val bytes = bytesList.toArray val addr = MacAddress.fromBytes(bytes).get assertEquals(MacAddress.fromString(addr.toString), Some(addr)) } } } test("support ordering") { forAll { (left: MacAddress, right: MacAddress) => val longCompare = left.toLong.compare(right.toLong) val result = Ordering[MacAddress].compare(left, right) assertEquals(result, longCompare) } } }
armanbilge/ip4s
build.sbt
<reponame>armanbilge/ip4s import sbtcrossproject.CrossPlugin.autoImport.crossProject import sbtcrossproject.CrossPlugin.autoImport.CrossType import com.typesafe.tools.mima.core._ ThisBuild / baseVersion := "3.1" ThisBuild / organization := "com.comcast" ThisBuild / organizationName := "Comcast Cable Communications Management, LLC" ThisBuild / homepage := Some(url("https://github.com/comcast/ip4s")) ThisBuild / startYear := Some(2018) ThisBuild / publishGithubUser := "mpilquist" ThisBuild / publishFullName := "<NAME>" ThisBuild / developers ++= List( Developer("matthughes", "<NAME>", "@matthughes", url("https://github.com/matthughes")), Developer("nequissimus", "<NAME>", "@nequissimus", url("https://github.com/nequissimus")) ) ThisBuild / githubWorkflowJavaVersions := Seq(JavaSpec.temurin("8")) ThisBuild / crossScalaVersions := List("2.12.15", "2.13.7", "3.1.0") ThisBuild / spiewakCiReleaseSnapshots := true ThisBuild / spiewakMainBranches := List("main") ThisBuild / homepage := Some(url("https://github.com/comcast/ip4s")) ThisBuild / scmInfo := Some( ScmInfo( url("https://github.com/comcast/ip4s"), "<EMAIL>:comcast/ip4s.git" ) ) ThisBuild / testFrameworks += new TestFramework("munit.Framework") ThisBuild / doctestTestFramework := DoctestTestFramework.ScalaCheck ThisBuild / scalafmtOnCompile := true ThisBuild / initialCommands := "import com.comcast.ip4s._" ThisBuild / fatalWarningsInCI := false ThisBuild / mimaBinaryIssueFilters ++= Seq( ProblemFilters.exclude[DirectMissingMethodProblem]("com.comcast.ip4s.Ipv6Address.toInetAddress"), ProblemFilters.exclude[ReversedMissingMethodProblem]("com.comcast.ip4s.Dns.*") // sealed trait ) lazy val root = project .in(file(".")) .enablePlugins(NoPublishPlugin, SonatypeCiReleasePlugin) .aggregate(coreJVM, coreJS, testKitJVM, testKitJS) lazy val testKit = crossProject(JVMPlatform, JSPlatform) .in(file("./test-kit")) .settings(commonSettings) .settings( name := "ip4s-test-kit" ) .settings(mimaPreviousArtifacts := Set.empty) .settings( libraryDependencies ++= Seq( "org.scalacheck" %%% "scalacheck" % "1.15.4", "org.scalameta" %%% "munit-scalacheck" % "0.7.29" % Test, "org.typelevel" %%% "cats-effect" % "3.3.1" % Test, "org.typelevel" %%% "munit-cats-effect-3" % "1.0.7" % Test ) ) .jvmSettings( libraryDependencies += "com.google.guava" % "guava" % "31.0.1-jre" % "test" ) .dependsOn(core % "compile->compile") lazy val testKitJVM = testKit.jvm lazy val testKitJS = testKit.js .disablePlugins(DoctestPlugin) .enablePlugins(ScalaJSBundlerPlugin) lazy val core = crossProject(JVMPlatform, JSPlatform) .in(file(".")) .settings(commonSettings) .settings( name := "ip4s-core", libraryDependencies ++= { if (isDotty.value) Nil else List("org.scala-lang" % "scala-reflect" % scalaVersion.value % "provided") }, scalacOptions := scalacOptions.value.filterNot(_ == "-source:3.0-migration"), Compile / scalafmt / unmanagedSources := (Compile / scalafmt / unmanagedSources).value.filterNot( _.toString.endsWith("Literals.scala") ), Test / scalafmt / unmanagedSources := (Test / scalafmt / unmanagedSources).value.filterNot( _.toString.endsWith("Literals.scala") ), Compile / unmanagedSourceDirectories ++= { val major = if (isDotty.value) "-3" else "-2" List(CrossType.Pure, CrossType.Full).flatMap( _.sharedSrcDir(baseDirectory.value, "main").toList.map(f => file(f.getPath + major)) ) } ) .settings( libraryDependencies ++= Seq( "org.typelevel" %%% "literally" % "1.0.2", "org.typelevel" %%% "cats-core" % "2.7.0", "org.typelevel" %%% "cats-effect-kernel" % "3.3.1" ) ) lazy val coreJVM = core.jvm lazy val coreJS = core.js .disablePlugins(DoctestPlugin) .enablePlugins(ScalaJSBundlerPlugin) .settings( scalaJSLinkerConfig ~= (_.withModuleKind(ModuleKind.CommonJSModule)), Compile / npmDependencies += "punycode" -> "2.1.1" ) lazy val docs = project .in(file("docs")) .enablePlugins(MdocPlugin) .dependsOn(coreJVM) .settings( mdocIn := baseDirectory.value / "src", mdocOut := baseDirectory.value / "../docs", crossScalaVersions := (ThisBuild / crossScalaVersions).value.filter(_.startsWith("2.")), githubWorkflowArtifactUpload := false ) lazy val commonSettings = Seq( Compile / unmanagedResources ++= { val base = baseDirectory.value / ".." (base / "NOTICE") +: (base / "LICENSE") +: (base / "CONTRIBUTING") +: ((base / "licenses") * "LICENSE_*").get } )
armanbilge/ip4s
project/plugins.sbt
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.8.0") addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "1.1.0") addSbtPlugin("ch.epfl.scala" % "sbt-scalajs-bundler" % "0.20.0") addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.4.6") addSbtPlugin("com.codecommit" % "sbt-spiewak-sonatype" % "0.23.0") addSbtPlugin("com.codecommit" % "sbt-github-actions" % "0.14.2") addSbtPlugin("com.github.tkawachi" % "sbt-doctest" % "0.9.9") addSbtPlugin("com.typesafe" % "sbt-mima-plugin" % "1.0.1") addSbtPlugin("org.scalameta" % "sbt-mdoc" % "2.2.24")
armanbilge/ip4s
shared/src/main/scala/com/comcast/ip4s/MacAddress.scala
/* * Copyright 2018 Comcast Cable Communications Management, LLC * * 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 com.comcast.ip4s import scala.util.control.NonFatal import cats.{Order, Show} /** 6-byte MAC address. */ final class MacAddress private (private val bytes: Array[Byte]) extends Ordered[MacAddress] with Serializable { def toBytes: Array[Byte] = bytes.clone def toLong: Long = { val bs = bytes var result = 0L for (i <- 0 until bs.size) { result = (result << 8) | (0x0ff & bs(i)) } result } override def compare(that: MacAddress): Int = { var i, result = 0 val tb = that.bytes val sz = bytes.length while (i < sz && result == 0) { result = Integer.compare(bytes(i) & 0xff, tb(i) & 0xff) i += 1 } result } override def equals(other: Any): Boolean = other match { case that: MacAddress => java.util.Arrays.equals(bytes, that.bytes) case _ => false } override def hashCode: Int = java.util.Arrays.hashCode(bytes) override def toString: String = bytes.map(b => f"${0xff & b}%02x").mkString("", ":", "") } object MacAddress { /** Constructs a `MacAddress` from a 6-element byte array. Returns `Some` when array is exactly 6-bytes and `None` * otherwise. */ def fromBytes(bytes: Array[Byte]): Option[MacAddress] = { if (bytes.length == 6) Some(new MacAddress(bytes)) else None } /** Constructs a `MacAddress` from the specified 6 bytes. * * Each byte is represented as an `Int` to avoid having to manually call `.toByte` on each value -- the `toByte` call * is done inside this function. */ def fromBytes( b0: Int, b1: Int, b2: Int, b3: Int, b4: Int, b5: Int ): MacAddress = { val bytes = new Array[Byte](6) bytes(0) = b0.toByte bytes(1) = b1.toByte bytes(2) = b2.toByte bytes(3) = b3.toByte bytes(4) = b4.toByte bytes(5) = b5.toByte new MacAddress(bytes) } /** Constructs a `MacAddress` from a `Long`, using the lower 48-bits. */ def fromLong(value: Long): MacAddress = { val bytes = new Array[Byte](6) var rem = value for (i <- 5 to 0 by -1) { bytes(i) = (rem & 0x0ff).toByte rem = rem >> 8 } new MacAddress(bytes) } /** Parses a `MacAddress` from a string, returning `None` if the string is not a valid mac. */ def fromString(value: String): Option[MacAddress] = { val trimmed = value.trim val fields = trimmed.split(':') if (fields.length == 6) { val result = new Array[Byte](6) var i = 0 while (i < result.length) { val field = fields(i) if (field.size == 2) { try { result(i) = (0xff & Integer.parseInt(field, 16)).toByte i += 1 } catch { case NonFatal(_) => return None } } else return None } Some(new MacAddress(result)) } else None } implicit val order: Order[MacAddress] = Order.fromComparable[MacAddress] implicit val show: Show[MacAddress] = Show.fromToString[MacAddress] }
wsargent/ReactiveCouchbase-core
driver/src/main/scala/org/reactivecouchbase/client/BucketAPI.scala
package org.reactivecouchbase.client import play.api.libs.json._ import scala.concurrent.{ Future, ExecutionContext } import com.couchbase.client.protocol.views.{ DesignDocument, SpatialView, View, Query } import play.api.libs.iteratee.Enumerator import net.spy.memcached.{ PersistTo, ReplicateTo } import org.reactivecouchbase.{ Couchbase, CouchbaseBucket } import java.util.concurrent.TimeUnit import net.spy.memcached.CASValue import org.reactivecouchbase.CouchbaseExpiration._ import scala.Some import play.api.libs.json.JsObject /** * Trait containing the whole ReactiveCouchbase API to put on CouchbaseBucket */ trait BucketAPI { self: CouchbaseBucket => def docName(name: String) = Couchbase.docName(name)(self) /** * * Perform a Couchbase query on a view * * @param docName the name of the design doc * @param viewName the name of the view * @param query the actual query * @param r Json reader for type T * @param ec ExecutionContext for async processing * @tparam T type of the doc * @return the list of docs */ def find[T](docName: String, viewName: String)(query: Query)(implicit r: Reads[T], ec: ExecutionContext): Future[List[T]] = { Couchbase.find[T](docName, viewName)(query)(self, r, ec) } /** * * Perform a Couchbase query on a view * * @param view the view to query * @param query the actual query * @param r Json reader for type T * @param ec ExecutionContext for async processing * @tparam T type of the doc * @return the list of docs */ def find[T](view: View)(query: Query)(implicit r: Reads[T], ec: ExecutionContext): Future[List[T]] = { Couchbase.find[T](view)(query)(self, r, ec) } /** * * Poll query every n millisec * * @param doc the name of the design doc * @param view the view to query * @param query the actual query * @param everyMillis repeat every ... * @param r Json reader for type T * @param ec ExecutionContext for async processing * @tparam T type of the doc * @return the query enumerator */ def pollQuery[T](doc: String, view: String, query: Query, everyMillis: Long, filter: T => Boolean = { chunk: T => true })(implicit r: Reads[T], ec: ExecutionContext): Enumerator[T] = { Couchbase.pollQuery[T](doc, view, query, everyMillis, filter)(self, r, ec) } /** * * Repeat query * * @param doc the name of the design doc * @param view the view to query * @param query the actual query * @param filter the filter for documents selection * @param r Json reader for type T * @param ec ExecutionContext for async processing * @tparam T type of the doc * @return the query enumerator */ def repeatQuery[T](doc: String, view: String, query: Query, filter: T => Boolean = { chunk: T => true }, trigger: Future[AnyRef] = Future.successful(Some))(implicit r: Reads[T], ec: ExecutionContext): Enumerator[T] = { Couchbase.repeatQuery[T](doc, view, query, trigger, filter)(self, r, ec) } /** * * 'Tail -f' on a query * * @param doc the name of the design doc * @param view the view to query * @param extractor id extrator of natural insertion order * @param from start from id * @param every tail every * @param unit unit of time * @param r Json reader for type T * @param ec ExecutionContext for async processing * @tparam T type of the doc * @return the query enumerator */ def tailableQuery[T](doc: String, view: String, extractor: T => Long, from: Long = 0L, every: Long = 1000L, unit: TimeUnit = TimeUnit.MILLISECONDS)(implicit r: Reads[T], ec: ExecutionContext): Enumerator[T] = { Couchbase.tailableQuery[T](doc, view, extractor, from, every, unit)(() => driver.bucket(alias), r, ec) } /** * * Fetch a stream of documents * * @param keysEnumerator stream of keys * @param ec ExecutionContext for async processing * @return */ def rawFetch(keysEnumerator: Enumerator[String])(implicit ec: ExecutionContext): QueryEnumerator[(String, String)] = Couchbase.rawFetch(keysEnumerator)(this, ec) /** * * Fetch a stream of documents * * @param keysEnumerator stream of keys * @param r Json reader * @param ec ExecutionContext for async processing * @tparam T type of the doc * @return */ def fetch[T](keysEnumerator: Enumerator[String])(implicit r: Reads[T], ec: ExecutionContext): QueryEnumerator[(String, T)] = Couchbase.fetch[T](keysEnumerator)(this, r, ec) /** * * Fetch a stream of documents * * @param keysEnumerator stream of keys * @param r Json reader * @param ec ExecutionContext for async processing * @tparam T type of the doc * @return */ def fetchValues[T](keysEnumerator: Enumerator[String])(implicit r: Reads[T], ec: ExecutionContext): QueryEnumerator[T] = Couchbase.fetchValues[T](keysEnumerator)(this, r, ec) /** * * Fetch a stream of documents * * @param keys the key of the documents * @param r Json reader * @param ec ExecutionContext for async processing * @tparam T type of the doc * @return */ def fetch[T](keys: Seq[String])(implicit r: Reads[T], ec: ExecutionContext): QueryEnumerator[(String, T)] = Couchbase.fetch[T](keys)(this, r, ec) /** * * Fetch a stream of documents * * @param keys the key of the documents * @param r Json reader * @param ec ExecutionContext for async processing * @tparam T type of the doc * @return */ def fetchValues[T](keys: Seq[String])(implicit r: Reads[T], ec: ExecutionContext): QueryEnumerator[T] = Couchbase.fetchValues[T](keys)(this, r, ec) /** * * Fetch a optional document and its key * * @param key the key of the document * @param r Json reader * @param ec ExecutionContext for async processing * @tparam T type of the doc * @return */ def getWithKey[T](key: String)(implicit r: Reads[T], ec: ExecutionContext): Future[Option[(String, T)]] = Couchbase.getWithKey[T](key)(this, r, ec) /** * * Perform a Couchbase query on a view * * @param docName the name of the design doc * @param viewName the name of the view * @param query the actual query * @param ec ExecutionContext for async processing * @return the query enumerator */ def rawSearch(docName: String, viewName: String)(query: Query)(implicit ec: ExecutionContext): QueryEnumerator[RawRow] = Couchbase.rawSearch(docName, viewName)(query)(this, ec) /** * * Perform a Couchbase query on a view * * @param view the view to query * @param query the actual query * @param ec ExecutionContext for async processing * @return the query enumerator */ def rawSearch(view: View)(query: Query)(implicit ec: ExecutionContext): QueryEnumerator[RawRow] = Couchbase.rawSearch(view)(query)(this, ec) /** * * Perform a Couchbase query on a view * * @param docName the name of the design doc * @param viewName the name of the view * @param query the actual query * @param r Json reader for type T * @param ec ExecutionContext for async processing * @tparam T type of the doc * @return the query enumerator */ def search[T](docName: String, viewName: String)(query: Query)(implicit r: Reads[T], ec: ExecutionContext): QueryEnumerator[TypedRow[T]] = Couchbase.search[T](docName, viewName)(query)(this, r, ec) /** * * Perform a Couchbase query on a view * * @param view the view to query * @param query the actual query * @param r Json reader for type T * @param ec ExecutionContext for async processing * @tparam T type of the doc * @return the query enumerator */ def search[T](view: View)(query: Query)(implicit r: Reads[T], ec: ExecutionContext): QueryEnumerator[TypedRow[T]] = Couchbase.search[T](view)(query)(this, r, ec) /** * * Perform a Couchbase query on a view * * @param docName the name of the design doc * @param viewName the name of the view * @param query the actual query * @param r Json reader for type T * @param ec ExecutionContext for async processing * @tparam T type of the doc * @return the query enumerator */ def searchValues[T](docName: String, viewName: String)(query: Query)(implicit r: Reads[T], ec: ExecutionContext): QueryEnumerator[T] = Couchbase.searchValues[T](docName, viewName)(query)(this, r, ec) /** * * Perform a Couchbase query on a view * * @param view the view to query * @param query the actual query * @param r Json reader for type T * @param ec ExecutionContext for async processing * @tparam T type of the doc * @return the query enumerator */ def searchValues[T](view: View)(query: Query)(implicit r: Reads[T], ec: ExecutionContext): QueryEnumerator[T] = Couchbase.searchValues[T](view)(query)(this, r, ec) ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * * Fetch a view * * @param docName the name of the design doc * @param viewName the name of the view * @param ec ExecutionContext for async processing * @return the view */ def view(docName: String, viewName: String)(implicit ec: ExecutionContext): Future[View] = { Couchbase.view(docName, viewName)(self, ec) } /** * * Fetch a spatial view * * @param docName the name of the design doc * @param viewName the name of the view * @param ec ExecutionContext for async processing * @return the spatial view */ def spatialView(docName: String, viewName: String)(implicit ec: ExecutionContext): Future[SpatialView] = { Couchbase.spatialView(docName, viewName)(self, ec) } /** * * Fetch a design document * * @param docName the name of the design doc * @param ec ExecutionContext for async processing * @return fetch design doc */ def designDocument(docName: String)(implicit ec: ExecutionContext): Future[DesignDocument] = { Couchbase.designDocument(docName)(self, ec) } /** * * Create a design doc * * @param name name of the design doc * @param value the content of the design doc * @param ec ExecutionContext for async processing * @return the operation status */ def createDesignDoc(name: String, value: JsObject)(implicit ec: ExecutionContext): Future[OpResult] = { Couchbase.createDesignDoc(name, value)(self, ec) } /** * * Create a design doc * * @param name name of the design doc * @param value the content of the design doc * @param ec ExecutionContext for async processing * @return the operation status */ def createDesignDoc(name: String, value: String)(implicit ec: ExecutionContext): Future[OpResult] = { Couchbase.createDesignDoc(name, value)(self, ec) } /** * * Create a design doc * * @param value the content of the design doc * @param ec ExecutionContext for async processing * @return the operation status */ def createDesignDoc(value: DesignDocument)(implicit ec: ExecutionContext): Future[OpResult] = { Couchbase.createDesignDoc(value)(self, ec) } /** * * Delete a design doc * * @param name name of the design doc * @param ec ExecutionContext for async processing * @return the operation status */ def deleteDesignDoc(name: String)(implicit ec: ExecutionContext): Future[OpResult] = { Couchbase.deleteDesignDoc(name)(self, ec) } /** * * Fetch keys stats * * @param key the key of the document * @param ec ExecutionContext for async processing * @return */ def keyStats(key: String)(implicit ec: ExecutionContext): Future[Map[String, String]] = { Couchbase.keyStats(key)(self, ec) } /** * * fetch a document * * @param key the key of the document * @param ec ExecutionContext for async processing * @tparam T type of the doc * @return */ def get[T](key: String)(implicit r: Reads[T], ec: ExecutionContext): Future[Option[T]] = { Couchbase.get[T](key)(self, r, ec) } /** * * * * @param key * @param ec * @return */ def getBlob(key: String)(implicit ec: ExecutionContext): Future[Option[String]] = { Couchbase.javaGet(key, self, ec).map { case s: String => Some(s) case _ => None } } def getInt(key: String)(implicit ec: ExecutionContext): Future[Int] = Couchbase.getInt(key)(self, ec) def getLong(key: String)(implicit ec: ExecutionContext): Future[Long] = Couchbase.getLong(key)(self, ec) def setInt(key: String, value: Int)(implicit ec: ExecutionContext): Future[OpResult] = Couchbase.setInt(key, value)(self, ec) def setLong(key: String, value: Long)(implicit ec: ExecutionContext): Future[OpResult] = Couchbase.setLong(key, value)(self, ec) /** * * Increment an Int * * @param key key of the Int value * @param by increment of the value * @param ec ExecutionContext for async processing * @return */ def incr(key: String, by: Int)(implicit ec: ExecutionContext): Future[OpResult] = Couchbase.incr(key, by)(self, ec) /** * * Increment a Long * * @param key key of the Long value * @param by the value to increment * @param ec ExecutionContext for async processing * @return */ def incr(key: String, by: Long)(implicit ec: ExecutionContext): Future[OpResult] = Couchbase.incr(key, by)(self, ec) /** * * Decrement an Int * * @param key key of the Int value * @param by the value to decrement * @param ec ExecutionContext for async processing * @return */ def decr(key: String, by: Int)(implicit ec: ExecutionContext): Future[OpResult] = Couchbase.decr(key, by)(self, ec) /** * * Decrement a Long * * @param key key of the Long value * @param by the value to decrement * @param ec ExecutionContext for async processing * @return */ def decr(key: String, by: Long)(implicit ec: ExecutionContext): Future[OpResult] = Couchbase.decr(key, by)(self, ec) /** * * Increment and get an Int * * @param key key of the Int value * @param by the value to increment * @param ec ExecutionContext for async processing * @return */ def incrAndGet(key: String, by: Int)(implicit ec: ExecutionContext): Future[Int] = Couchbase.incrAndGet(key, by)(self, ec) /** * * Increment and get a Long * * @param key key of the Long value * @param by the value to increment * @param ec ExecutionContext for async processing * @return */ def incrAndGet(key: String, by: Long)(implicit ec: ExecutionContext): Future[Long] = Couchbase.incrAndGet(key, by)(self, ec) /** * * Decrement and get an Int * * @param key key of the Int value * @param by the value to decrement * @param ec ExecutionContext for async processing * @return */ def decrAndGet(key: String, by: Int)(implicit ec: ExecutionContext): Future[Int] = Couchbase.decrAndGet(key, by)(self, ec) /** * * Decrement and get a Long * * @param key key of the Long value * @param by the value to decrement * @param ec ExecutionContext for async processing * @return */ def decrAndGet(key: String, by: Long)(implicit ec: ExecutionContext): Future[Long] = Couchbase.decrAndGet(key, by)(self, ec) /** * * * * @param key * @param value * @param exp * @param persistTo * @param replicateTo * @param ec * @return */ def setBlob(key: String, value: String, exp: CouchbaseExpirationTiming = Constants.expiration, persistTo: PersistTo = PersistTo.ZERO, replicateTo: ReplicateTo = ReplicateTo.ZERO)(implicit ec: ExecutionContext): Future[OpResult] = { Couchbase.javaSet(key, exp, value, persistTo, replicateTo, self, ec) } /** * * Set a document * * @param key the key of the document * @param value the document * @param ec ExecutionContext for async processing * @tparam T the type of the doc * @return the operation status */ def set[T](key: String, value: T, exp: CouchbaseExpirationTiming = Constants.expiration, persistTo: PersistTo = PersistTo.ZERO, replicateTo: ReplicateTo = ReplicateTo.ZERO)(implicit w: Writes[T], ec: ExecutionContext): Future[OpResult] = { Couchbase.set[T](key, value, exp, persistTo, replicateTo)(self, w, ec) } /** * * Set a document * * @param key the key of the document * @param value the document * @param exp expiration of the doc * @param persistTo persistence flag * @param replicateTo replication flag * @param w Json writer for type T * @param ec ExecutionContext for async processing * @tparam T the type of the doc * @return the operation status */ def setWithKey[T](key: T => String, value: T, exp: CouchbaseExpirationTiming = Constants.expiration, persistTo: PersistTo = PersistTo.ZERO, replicateTo: ReplicateTo = ReplicateTo.ZERO)(implicit w: Writes[T], ec: ExecutionContext): Future[OpResult] = { Couchbase.setWithKey[T](key, value, exp, persistTo, replicateTo)(self, w, ec) } /** * * Set a document that contains an id field * * @param value the document * @param exp expiration of the doc * @param persistTo persistence flag * @param replicateTo replication flag * @param w Json writer for type T * @param ec ExecutionContext for async processing * @tparam T the type of the doc * @return the operation status */ def setWithId[T <: { def id: String }](value: T, exp: CouchbaseExpirationTiming = Constants.expiration, persistTo: PersistTo = PersistTo.ZERO, replicateTo: ReplicateTo = ReplicateTo.ZERO)(implicit w: Writes[T], ec: ExecutionContext): Future[OpResult] = { Couchbase.set[T](value.id, value, exp, persistTo, replicateTo)(self, w, ec) } /** * * Set a stream of documents * * @param data the stream of documents * @param exp expiration of the doc * @param persistTo persistence flag * @param replicateTo replication flag * @param w Json writer for type T * @param ec ExecutionContext for async processing * @tparam T the type of the doc * @return the operation status */ def setStream[T](data: Enumerator[(String, T)], exp: CouchbaseExpirationTiming = Constants.expiration, persistTo: PersistTo = PersistTo.ZERO, replicateTo: ReplicateTo = ReplicateTo.ZERO)(implicit w: Writes[T], ec: ExecutionContext): Future[List[OpResult]] = { Couchbase.setStream[T](data, exp, persistTo, replicateTo)(self, w, ec) } /** * * Set a stream of documents * * @param key the key of the document * @param data the stream of documents * @param exp expiration of the doc * @param persistTo persistence flag * @param replicateTo replication flag * @param w Json writer for type T * @param ec ExecutionContext for async processing * @tparam T the type of the doc * @return the operation status */ def setStreamWithKey[T](key: T => String, data: Enumerator[T], exp: CouchbaseExpirationTiming = Constants.expiration, persistTo: PersistTo = PersistTo.ZERO, replicateTo: ReplicateTo = ReplicateTo.ZERO)(implicit w: Writes[T], ec: ExecutionContext): Future[List[OpResult]] = { Couchbase.setStreamWithKey[T](key, data, exp, persistTo, replicateTo)(self, w, ec) } /** * * * * @param key * @param value * @param exp * @param persistTo * @param replicateTo * @param ec * @return */ def addBlob(key: String, value: String, exp: CouchbaseExpirationTiming = Constants.expiration, persistTo: PersistTo = PersistTo.ZERO, replicateTo: ReplicateTo = ReplicateTo.ZERO)(implicit ec: ExecutionContext): Future[OpResult] = { Couchbase.javaAdd(key, exp, value, persistTo, replicateTo, self, ec) } /** * * Add a document * * @param key the key of the document * @param value the document * @param exp expiration of the doc * @param persistTo persistence flag * @param replicateTo replication flag * @param w Json writer for type T * @param ec ExecutionContext for async processing * @tparam T the type of the doc * @return the operation status */ def add[T](key: String, value: T, exp: CouchbaseExpirationTiming = Constants.expiration, persistTo: PersistTo = PersistTo.ZERO, replicateTo: ReplicateTo = ReplicateTo.ZERO)(implicit w: Writes[T], ec: ExecutionContext): Future[OpResult] = { Couchbase.add[T](key, value, exp, persistTo, replicateTo)(self, w, ec) } /** * * Add a document * * @param key the key of the document * @param value the document * @param exp expiration of the doc * @param persistTo persistence flag * @param replicateTo replication flag * @param w Json writer for type T * @param ec ExecutionContext for async processing * @tparam T the type of the doc * @return the operation status */ def addWithKey[T](key: T => String, value: T, exp: CouchbaseExpirationTiming = Constants.expiration, persistTo: PersistTo = PersistTo.ZERO, replicateTo: ReplicateTo = ReplicateTo.ZERO)(implicit w: Writes[T], ec: ExecutionContext): Future[OpResult] = { Couchbase.addWithKey[T](key, value, exp, persistTo, replicateTo)(self, w, ec) } /** * * Add a document * * @param value the document * @param exp expiration of the doc * @param persistTo persistence flag * @param replicateTo replication flag * @param w Json writer for type T * @param ec ExecutionContext for async processing * @tparam T the type of the doc * @return the operation status */ def addWithId[T <: { def id: String }](value: T, exp: CouchbaseExpirationTiming = Constants.expiration, persistTo: PersistTo = PersistTo.ZERO, replicateTo: ReplicateTo = ReplicateTo.ZERO)(implicit w: Writes[T], ec: ExecutionContext): Future[OpResult] = { Couchbase.add[T](value.id, value, exp, persistTo, replicateTo)(self, w, ec) } /** * * Add a stream of documents * * @param data the stream of documents * @param exp expiration of the doc * @param persistTo persistence flag * @param replicateTo replication flag * @param w Json writer for type T * @param ec ExecutionContext for async processing * @tparam T the type of the doc * @return the operation status */ def addStream[T](data: Enumerator[(String, T)], exp: CouchbaseExpirationTiming = Constants.expiration, persistTo: PersistTo = PersistTo.ZERO, replicateTo: ReplicateTo = ReplicateTo.ZERO)(implicit w: Writes[T], ec: ExecutionContext): Future[List[OpResult]] = { Couchbase.addStream[T](data, exp, persistTo, replicateTo)(self, w, ec) } /** * * Add a stream of documents * * @param key the key of the document * @param data the stream of documents * @param exp expiration of the doc * @param persistTo persistence flag * @param replicateTo replication flag * @param w Json writer for type T * @param ec ExecutionContext for async processing * @tparam T the type of the doc * @return the operation status */ def addStreamWithKey[T](key: T => String, data: Enumerator[T], exp: CouchbaseExpirationTiming = Constants.expiration, persistTo: PersistTo = PersistTo.ZERO, replicateTo: ReplicateTo = ReplicateTo.ZERO)(implicit w: Writes[T], ec: ExecutionContext): Future[List[OpResult]] = { Couchbase.addStreamWithKey[T](key, data, exp, persistTo, replicateTo)(self, w, ec) } /** * * * * @param key * @param value * @param exp * @param persistTo * @param replicateTo * @param ec * @return */ def replaceBlob(key: String, value: String, exp: CouchbaseExpirationTiming = Constants.expiration, persistTo: PersistTo = PersistTo.ZERO, replicateTo: ReplicateTo = ReplicateTo.ZERO)(implicit ec: ExecutionContext): Future[OpResult] = { Couchbase.javaReplace(key, exp, value, persistTo, replicateTo, self, ec) } /** * * Replace a document * * @param key the key of the document * @param value the document * @param exp expiration of the doc * @param persistTo persistence flag * @param replicateTo replication flag * @param w Json writer for type T * @param ec ExecutionContext for async processing * @tparam T the type of the doc * @return the operation status */ def replace[T](key: String, value: T, exp: CouchbaseExpirationTiming = Constants.expiration, persistTo: PersistTo = PersistTo.ZERO, replicateTo: ReplicateTo = ReplicateTo.ZERO)(implicit w: Writes[T], ec: ExecutionContext): Future[OpResult] = { Couchbase.replace[T](key, value, exp, persistTo, replicateTo)(self, w, ec) } /** * * Replace a document * * @param key the key of the document * @param value the document * @param exp expiration of the doc * @param persistTo persistence flag * @param replicateTo replication flag * @param w Json writer for type T * @param ec ExecutionContext for async processing * @tparam T the type of the doc * @return the operation status */ def replaceWithKey[T](key: T => String, value: T, exp: CouchbaseExpirationTiming = Constants.expiration, persistTo: PersistTo = PersistTo.ZERO, replicateTo: ReplicateTo = ReplicateTo.ZERO)(implicit w: Writes[T], ec: ExecutionContext): Future[OpResult] = { Couchbase.replaceWithKey[T](key, value, exp, persistTo, replicateTo)(self, w, ec) } /** * * Replace a document * * @param value the document * @param exp expiration of the doc * @param persistTo persistence flag * @param replicateTo replication flag * @param w Json writer for type T * @param ec ExecutionContext for async processing * @tparam T the type of the doc * @return the operation status */ def replaceWithId[T <: { def id: String }](value: T, exp: CouchbaseExpirationTiming = Constants.expiration, persistTo: PersistTo = PersistTo.ZERO, replicateTo: ReplicateTo = ReplicateTo.ZERO)(implicit w: Writes[T], ec: ExecutionContext): Future[OpResult] = { Couchbase.replace[T](value.id, value, exp, persistTo, replicateTo)(self, w, ec) } /** * * Replace a stream documents * * @param data the stream of documents * @param exp expiration of the doc * @param persistTo persistence flag * @param replicateTo replication flag * @param w Json writer for type T * @param ec ExecutionContext for async processing * @tparam T the type of the doc * @return the operation status */ def replaceStream[T](data: Enumerator[(String, T)], exp: CouchbaseExpirationTiming = Constants.expiration, persistTo: PersistTo = PersistTo.ZERO, replicateTo: ReplicateTo = ReplicateTo.ZERO)(implicit w: Writes[T], ec: ExecutionContext): Future[List[OpResult]] = { Couchbase.replaceStream[T](data, exp, persistTo, replicateTo)(self, w, ec) } /** * * Replace a stream documents * * @param key the key of the document * @param data the stream of documents * @param exp expiration of the doc * @param persistTo persistence flag * @param replicateTo replication flag * @param w Json writer for type T * @param ec ExecutionContext for async processing * @tparam T the type of the doc * @return the operation status */ def replaceStreamWithKey[T](key: T => String, data: Enumerator[T], exp: CouchbaseExpirationTiming = Constants.expiration, persistTo: PersistTo = PersistTo.ZERO, replicateTo: ReplicateTo = ReplicateTo.ZERO)(implicit w: Writes[T], ec: ExecutionContext): Future[List[OpResult]] = { Couchbase.replaceStreamWithKey[T](key, data, exp, persistTo, replicateTo)(self, w, ec) } /** * * Delete a document * * @param key the key to delete * @param persistTo persist flag * @param replicateTo repplication flag * @param ec ExecutionContext for async processing * @return the operation status for the delete operation */ def delete(key: String, persistTo: PersistTo = PersistTo.ZERO, replicateTo: ReplicateTo = ReplicateTo.ZERO)(implicit ec: ExecutionContext): Future[OpResult] = { Couchbase.delete(key, persistTo, replicateTo)(self, ec) } /** * * Delete a document with an id field of type String * * @param value * @param persistTo persist flag * @param replicateTo repplication flag * @param ec ExecutionContext for async processing * @tparam T type of documents * @return the operation status for the delete operation */ def deleteWithId[T <: { def id: String }](value: T, persistTo: PersistTo = PersistTo.ZERO, replicateTo: ReplicateTo = ReplicateTo.ZERO)(implicit ec: ExecutionContext): Future[OpResult] = { Couchbase.delete(value.id, persistTo, replicateTo)(self, ec) } /** * * Delete a stream of documents * * @param data the stream of documents to delete * @param persistTo persist flag * @param replicateTo repplication flag * @param ec ExecutionContext for async processing * @return the operation statuses for the delete operation */ def deleteStream(data: Enumerator[String], persistTo: PersistTo = PersistTo.ZERO, replicateTo: ReplicateTo = ReplicateTo.ZERO)(implicit ec: ExecutionContext): Future[List[OpResult]] = { Couchbase.deleteStream(data, persistTo, replicateTo)(self, ec) } /** * * Delete a stream of documents * * @param key the extractor to get the key * @param data the stream of documents to delete * @param persistTo persist flag * @param replicateTo repplication flag * @param ec ExecutionContext for async processing * @tparam T type of document * @return the operation statuses for the delete operation */ def deleteStreamWithKey[T](key: T => String, data: Enumerator[T], persistTo: PersistTo = PersistTo.ZERO, replicateTo: ReplicateTo = ReplicateTo.ZERO)(implicit ec: ExecutionContext): Future[List[OpResult]] = { Couchbase.deleteStreamWithKey[T](key, data, persistTo, replicateTo)(self, ec) } /** * * Flush the current bucket * * @param delay delay to flush * @param ec ExecutionContext for async processing * @return the operation status */ def flush(delay: Int)(implicit ec: ExecutionContext): Future[OpResult] = Couchbase.flush(delay)(self, ec) /** * * Flush the current bucket * * @param ec ExecutionContext for async processing * @return the operation status */ def flush()(implicit ec: ExecutionContext): Future[OpResult] = Couchbase.flush()(self, ec) /** * * Get a doc and lock it * * @param key key of the lock * @param exp expiration of the lock * @param r Json reader for type T * @param ec ExecutionContext for async processing * @tparam T type of the doc * @return Cas value */ def getAndLock[T](key: String, exp: CouchbaseExpirationTiming)(implicit r: Reads[T], ec: ExecutionContext): Future[Option[CASValue[T]]] = { Couchbase.getAndLock(key, exp)(r, self, ec) } /** * * Unlock a locked key * * @param key key to unlock * @param casId id of the compare and swap operation * @param ec ExecutionContext for async processing * @return the operation status */ def unlock(key: String, casId: Long)(implicit ec: ExecutionContext): Future[OpResult] = { Couchbase.unlock(key, casId)(self, ec) } /** * * Atomically perform operation(s) on a document while it's locked * * @param key the key of the document * @param operation the operation(s) to perform on the document while it's locked * @param ec ExecutionContext for async processing * @param r Json reader * @param w Json writer * @tparam T type of the doc * @return the document */ //def atomicUpdate[T](key: String, persistTo: PersistTo = PersistTo.ZERO, replicateTo: ReplicateTo = ReplicateTo.ZERO)(operation: T => T)(implicit ec: ExecutionContext, r: Reads[T], w: Writes[T]): Future[T] = { // Couchbase.atomicUpdate[T](key, persistTo, replicateTo)(operation)(self, ec, r, w) //} /** * * Atomically perform async operation(s) on a document while it's locked * * @param key the key of the document * @param operation the async operation(s) to perform on the document while it's locked * @param ec ExecutionContext for async processing * @param r Json reader * @param w Json writer * @tparam T type of the doc * @return the document */ //def atomicallyUpdate[T](key: String, persistTo: PersistTo = PersistTo.ZERO, replicateTo: ReplicateTo = ReplicateTo.ZERO)(operation: T => Future[T])(implicit ec: ExecutionContext, r: Reads[T], w: Writes[T]): Future[T] = { // Couchbase.atomicallyUpdate[T](key, persistTo, replicateTo)(operation)(self, ec, r, w) //} def atomicallyUpdate[T](key: String, exp: CouchbaseExpirationTiming = Constants.expiration, persistTo: PersistTo = PersistTo.ZERO, replicateTo: ReplicateTo = ReplicateTo.ZERO)(operation: T => Future[T])(implicit ec: ExecutionContext, r: Reads[T], w: Writes[T]): Future[T] = { Couchbase.atomicallyUpdate[T](key, exp, persistTo, replicateTo)(operation)(self, ec, r, w) } def atomicUpdate[T](key: String, exp: CouchbaseExpirationTiming = Constants.expiration, persistTo: PersistTo = PersistTo.ZERO, replicateTo: ReplicateTo = ReplicateTo.ZERO)(operation: T => T)(implicit ec: ExecutionContext, r: Reads[T], w: Writes[T]): Future[T] = { Couchbase.atomicUpdate[T](key, exp, persistTo, replicateTo)(operation)(self, ec, r, w) } }
wsargent/ReactiveCouchbase-core
driver/src/test/scala/NonExistentSpec.scala
<reponame>wsargent/ReactiveCouchbase-core import org.reactivecouchbase.CouchbaseRWImplicits.jsObjectToDocumentWriter import org.reactivecouchbase.ReactiveCouchbaseDriver import org.specs2.mutable.{Specification, Tags} import play.api.libs.json.{JsValue, JsObject, Json} import scala.concurrent.{Future, Await} import scala.util.{Success, Failure} class NonExistentSpec extends Specification with Tags { sequential import Utils._ """ You need to start a Couchbase server with a 'default' bucket on standard port to run those tests ... """ in ok val driver = ReactiveCouchbaseDriver() val bucket = driver.bucket("default") "ReactiveCouchbase read API" should { "lookup without throwing" in { val none : Future[Option[JsValue]] = bucket.get[JsValue]("a dummy that doesn't exists") none.onComplete { case Success(Some(stuff)) => println(s"Some of $stuff" ) case Success(None) => println(s"None") case Failure(e) => println(s"Got some error : ${e.getMessage}") } Await.result(none.recover { case _ => None }, timeout) must beNone } "shutdown now" in { driver.shutdown() success } } }
wsargent/ReactiveCouchbase-core
driver/src/test/scala/AtomicSpec.scala
import org.reactivecouchbase.ReactiveCouchbaseDriver import org.specs2.mutable._ import scala.concurrent._ import scala.concurrent.duration._ import scala.util.{Failure, Success} import akka.pattern.after import org.reactivecouchbase.CouchbaseExpiration._ class AtomicSpec extends Specification with Tags { sequential import Utils._ """ You need to start a Couchbase server with a 'default' bucket on standard port to run those tests ... """ in ok "ReactiveCouchbase atomic API" should { import Utils._ val driver = ReactiveCouchbaseDriver() val bucket = driver.bucket("default") "try to update a non existent key" in { val res = bucket.atomicallyUpdate[Person]("idontexists") { person => Future.successful(Person(person.name, person.surname, person.age + 1)) } res.onComplete { case Success(s) => bucket.logger.info("success " + s) case Failure(f) => bucket.logger.info("failure " + f) } Await.ready(res, timeout) success } "try to update an existent key" in { Await.result(bucket.set("iexist", Person("John", "Doe", 42)), timeout) val res = bucket.atomicallyUpdate[Person]("iexist") { person => Future.successful(Person(person.name, person.surname, person.age + 1)) } res.onComplete { case Success(s) => bucket.logger.info("success " + s) case Failure(f) => bucket.logger.info("failure " + f) } Await.result(res, timeout) Await.result(bucket.delete("iexist"), timeout) success } "shutdown now" in { //Await.result(bucket.flush(), timeout) driver.shutdown() success } } "ReactiveCouchbase atomic API" should { val driver = ReactiveCouchbaseDriver() val bucket = driver.bucket("default") val tk = "mylocktestkey_" // + UUID.randomUUID "delete locked key" in { val fut = bucket.delete(tk) Await.result(fut, timeout) success } "set key \"" + tk + "\" in default bucket" in { val tv = new TestValue("testValue", 42, List()) val s = bucket.set[TestValue](tk, tv, Duration(2, "hours")) Await.result(s, Duration(20000, "millis")).isSuccess must equalTo(true) } "lock the key \"" + tk + "\" in default bucket" in { val f = { x: TestValue => { val l = x.l.toList val ll = (new TestValue("testValue", l.size, List())) :: l val ntv = new TestValue(x.value, x.number, ll) ntv } } bucket.atomicUpdate[TestValue](tk)(f).onComplete({ case Success(r) => println("Success of 1 atomic update") case Failure(r) => println("Faillure of 1 atomic update") }) bucket.atomicUpdate[TestValue](tk)(f).onComplete({ case Success(r) => println("Success of 2 atomic update") case Failure(r) => println("Faillure of 2 atomic update") }) bucket.atomicUpdate[TestValue](tk)(f).onComplete({ case Success(r) => println("Success of 3 atomic update") case Failure(r) => println("Faillure of 3 atomic update") }) bucket.atomicUpdate[TestValue](tk)(f).onComplete({ case Success(r) => println("Success of 4 atomic update") case Failure(r) => println("Faillure of 4 atomic update") }) bucket.atomicUpdate[TestValue](tk + "-plop")(f).onComplete({ case Success(r) => println("Failure : successfully updated a non existing key O_o") case Failure(r) => println("Success : unable to update a non existing key") }) Await.result(after(Duration(6000, "millis"), using = bucket.driver.scheduler())(Future.successful(true)), Duration(7001, "millis")) } "delete locked key (again)" in { val fut = bucket.delete(tk) Await.result(fut, timeout) success } "shutdown now" in { //Await.result(bucket.flush(), timeout) driver.shutdown() success } } }
wsargent/ReactiveCouchbase-core
driver/src/main/scala/org/reactivecouchbase/N1QL.scala
package org.reactivecouchbase import scala.concurrent._ import play.api.libs.iteratee._ import play.api.libs.json._ import com.ning.http.client.{Response, AsyncCompletionHandler} import org.reactivecouchbase.client.ReactiveCouchbaseException /** * Container to run N1QL query against a Couchbase Server. Uses it's own HTTP client from CouchbaseBucket * * @param bucket the bucket containing an HTTP client. It could be any CouchbaseBucket instance for any targeted actual bucket * @param query the N1QL query you want to run * @param host the host on which N1QL server is running * @param port the port of the N1QL server */ class N1QLQuery(bucket: CouchbaseBucket, query: String, host: String, port: String) { /** * The N1QL URL for querying */ val url = s"http://${host}:${port}/query" /** * * Stream the content of the query result as JsObjects * * @param ec the execution context in which the Enumerator is executed the execution context in which the Enumerator is executed * @return the future JsObject Enumerator */ def enumerateJson(implicit ec: ExecutionContext): Future[Enumerator[JsObject]] = { toJsArray(ec).map { arr => Enumerator.enumerate(arr.value) &> Enumeratee.map[JsValue](_.as[JsObject]) } } /** * * Stream the content of the query result as instances of T * * @param r Json reader to transform raw Json into Scala instances * @param ec the execution context in which the Enumerator is executed * @tparam T the type of object used by deserialization * @return the future T enumerator */ def enumerate[T](implicit r: Reads[T], ec: ExecutionContext): Future[Enumerator[T]] = { enumerateJson(ec).map { e => e &> Enumeratee.map[JsObject](r.reads(_)) &> Enumeratee.collect[JsResult[T]] { case JsSuccess(value, _) => value } } } /** * * Stream the content of the query result as JsObjects * * @param ec the execution context in which the Enumerator is executed * @return the Enumerator of JsObject instances */ def asJsonEnumerator(implicit ec: ExecutionContext): Enumerator[JsObject] = { Enumerator.flatten(enumerateJson(ec)) //Concurrent.unicast[JsObject](onStart = c => enumerateJson(ec).map(_(Iteratee.foreach[JsObject](c.push).map(_ => c.eofAndEnd())))) } /** * * Stream the content of the query result as instances of T * * @param r Json reader to transform raw Json into Scala instances * @param ec the execution context in which the Enumerator is executed * @tparam T the type of object used by deserialization * @return the Enumerator of T instances */ def asEnumerator[T](implicit r: Reads[T], ec: ExecutionContext): Enumerator[T] = { Enumerator.flatten(enumerate[T](r, ec)) //Concurrent.unicast[T](onStart = c => enumerate[T](r, ec).map(_(Iteratee.foreach[T](c.push).map(_ => c.eofAndEnd())))) } /** * * Transform the query result as a JsArray * * @param ec the execution context in which the Future is executed * @return the future JsArray */ def toJsArray(implicit ec: ExecutionContext): Future[JsArray] = { val result = Promise[JsValue]() bucket.httpClient.preparePost(url).addQueryParameter("q", query).execute(new AsyncCompletionHandler[Response]() { override def onCompleted(response: Response) = { result.success(Json.parse(response.getResponseBody)) response } override def onThrowable(t: Throwable) = { result.failure(t) } }) result.future.map { response => (response \ "resultset").as[JsArray] } } /** * * Transform the query result as a List of T instances * * @param r Json reader to transform raw Json into Scala instances * @param ec the execution context in which the Enumerator is executed * @tparam T the type of object used by deserialization * @return the future List of T instances */ def toList[T](implicit r: Reads[T], ec: ExecutionContext): Future[List[T]] = { enumerate[T](r, ec).flatMap(_(Iteratee.getChunks[T]).flatMap(_.run)) } /** * * Fetch the optional head of a query result * * @param r Json reader to transform raw Json into Scala instances * @param ec the execution context in which the Enumerator is executed * @tparam T the type of object used by deserialization * @return the future Optional head of the query result */ def headOption[T](implicit r: Reads[T], ec: ExecutionContext): Future[Option[T]] = { enumerate[T](r, ec).flatMap(_(Iteratee.head[T]).flatMap(_.run)) } } /** * The N1QL public API for users */ object CouchbaseN1QL { /** * * Creates a N1QL query * * @param bucket the targeted bucket * @param query the actual N1QL query written in N1QL query language * @param host the host of the N1QL server * @param port the port of the N1QL server * @return the created N1QLQuery instance */ def N1QL(bucket: CouchbaseBucket, query: String, host: String, port: String): N1QLQuery = { new N1QLQuery(bucket, query, host, port) } /** * * Creates a N1QL query * * Example : * {{{ * import scala.concurrent.ExecutionContext.Implicits.global * * case class Person(name: String, age: Int) * * val driver = ReactiveCouchbaseDriver() * implicit val bucket = driver.bucket("default") * implicit val fmt = Json.format[Person] * * val age = 42 * * N1QL( s""" SELECT fname, age FROM tutorial WHERE age > ${age} """, driver ) * .toList[Person].map { persons => * println(s"Persons older than ${age}", persons)) * } * }}} * * @param query the actual N1QL query written in N1QL query language * @param bucket the targeted bucket * @return the created N1QLQuery instance */ def N1QL(query: String)(implicit bucket: CouchbaseBucket): N1QLQuery = { val host = bucket.N1QLHost.getOrElse(throw new ReactiveCouchbaseException("Cannot find N1QL host", "Cannot find N1QL host in couchbase.n1ql conf.")) val port = bucket.N1QLPort.getOrElse(throw new ReactiveCouchbaseException("Cannot find N1QL port", "Cannot find N1QL port in couchbase.n1ql conf.")) new N1QLQuery(bucket, query, host, port) } }
wsargent/ReactiveCouchbase-core
driver/src/test/scala/AppendSpec.scala
import org.reactivecouchbase.{CouchbaseRWImplicits, ReactiveCouchbaseDriver} import org.reactivecouchbase.CouchbaseRWImplicits.documentAsJsObjectReader import org.reactivecouchbase.CouchbaseRWImplicits.jsObjectToDocumentWriter import org.specs2.mutable.{Tags, Specification} import play.api.libs.json.{JsArray, JsObject, Json} import scala.concurrent.{ExecutionContext, Await} class AppendSpec extends Specification with Tags { sequential import Utils._ """ You need to start a Couchbase server with a 'default' bucket on standard port to run those tests ... """ in ok val driver = ReactiveCouchbaseDriver() val bucketDefault = driver.bucket("default") "ReactiveCouchbase append API" should { "insert" in { Await.result(bucketDefault.set[JsObject]("alias-key", Json.obj("hello" -> "world")), timeout) success } "append shit" in { //val id = bucketDefault.couchbaseClient.gets("alias-key").getCas bucketDefault.couchbaseClient.append("alias-key",""" "added":"stuff" """).get() println("\n\n\n" + bucketDefault.couchbaseClient.get("alias-key")) success } /* "delete from default bucket" in { Await.result(bucketDefault.delete("alias-key"), timeout) success }*/ "shutdown now" in { driver.shutdown() success } } }
wsargent/ReactiveCouchbase-core
driver/src/test/scala/ViewsSpec.scala
<gh_stars>0 import com.couchbase.client.protocol.views.{Stale, Query} import org.reactivecouchbase.experimental.{TypedViewRow, Views} import org.reactivecouchbase.ReactiveCouchbaseDriver import org.specs2.mutable._ import play.api.libs.iteratee.Iteratee import play.api.libs.json.Json import scala.concurrent._ class ViewsSpec extends Specification with Tags { sequential import Utils._ """ You need to start a Couchbase server with a 'default' bucket on standard port to run those tests ... """ in ok val driver = ReactiveCouchbaseDriver() implicit val bucket = driver.bucket("default") "ReactiveCouchbase Views API" should { "create some view" in { Await.result(bucket.createDesignDoc("persons", """ | { | "views":{ | "by_name": { | "map": "function (doc, meta) { emit(doc.name, null); } " | }, | "by_surname": { | "map": "function (doc, meta) { emit(doc.surname, null); } " | }, | "by_age": { | "map": "function (doc, meta) { emit(doc.age, null); } " | } | } | } """.stripMargin), timeout) success } "insert a lot of data" in { for(i <- 0 to 99) { Await.result(bucket.set(s"person--$i", Person("Billy", s"Doe-$i", i)), timeout) } success } "Check view API" in { Await.result(bucket.view("persons", "by_name").flatMap { view => Future.sequence(Seq( Views.query[Person](view, new Query().setStale(Stale.FALSE).setIncludeDocs(true)).flatMap(e => e.apply(Iteratee.foreach[TypedViewRow[Person]]( doc => println(doc))).map(_.run)), Views.query[Person](view, new Query().setStale(Stale.FALSE).setIncludeDocs(true)).flatMap(e => e.apply(Iteratee.foreach[TypedViewRow[Person]]( doc => bucket.logger.debug(doc.document.map(Json.stringify).getOrElse("ERROR !!!")))).map(_.run)), Views.query[Person](view, new Query().setStale(Stale.FALSE).setIncludeDocs(true)).flatMap(e => e.apply(Iteratee.foreach[TypedViewRow[Person]]( doc => bucket.logger.debug(doc.document.map(Json.stringify).getOrElse("ERROR !!!")))).map(_.run)), Views.query[Person](view, new Query().setStale(Stale.FALSE).setIncludeDocs(true)).flatMap(e => e.apply(Iteratee.foreach[TypedViewRow[Person]]( doc => bucket.logger.debug(doc.document.map(Json.stringify).getOrElse("ERROR !!!")))).map(_.run)), Views.query[Person](view, new Query().setStale(Stale.FALSE).setIncludeDocs(true)).flatMap(e => e.apply(Iteratee.foreach[TypedViewRow[Person]]( doc => bucket.logger.debug(doc.document.map(Json.stringify).getOrElse("ERROR !!!")))).map(_.run)), Views.query[Person](view, new Query().setStale(Stale.FALSE).setIncludeDocs(true)).flatMap(e => e.apply(Iteratee.foreach[TypedViewRow[Person]]( doc => bucket.logger.debug(doc.document.map(Json.stringify).getOrElse("ERROR !!!")))).map(_.run)) )) }, timeout) success } "delete all data" in { Await.result(bucket.deleteDesignDoc("persons"), timeout) for(i <- 0 to 99) { Await.result(bucket.delete(s"person--$i"), timeout) } success } "shutdown now" in { driver.shutdown() success } } }
wsargent/ReactiveCouchbase-core
project/Build.scala
import sbt._ import Keys._ object ApplicationBuild extends Build { val appName = "ReactiveCouchbase-core" val appVersion = "0.3-SNAPSHOT" val appScalaVersion = "2.11.1" //val appScalaBinaryVersion = "2.10" val appScalaCrossVersions = Seq("2.11.1", "2.10.4") val local: Def.Initialize[Option[sbt.Resolver]] = version { (version: String) => val localPublishRepo = "./repository" if(version.trim.endsWith("SNAPSHOT")) Some(Resolver.file("snapshots", new File(localPublishRepo + "/snapshots"))) else Some(Resolver.file("releases", new File(localPublishRepo + "/releases"))) } val nexusPublish = version { v => val nexus = "https://oss.sonatype.org/" if (v.trim.endsWith("SNAPSHOT")) Some("snapshots" at nexus + "content/repositories/snapshots") else Some("releases" at nexus + "service/local/staging/deploy/maven2") } lazy val baseSettings = Defaults.defaultSettings ++ Seq( scalaVersion := appScalaVersion, //scalaBinaryVersion := appScalaBinaryVersion, crossScalaVersions := appScalaCrossVersions, parallelExecution in Test := false ) lazy val root = Project("root", base = file(".")) .settings(baseSettings: _*) .settings( publishLocal := {}, publish := {} ).aggregate( driver ) lazy val driver = Project(appName, base = file("driver")) .settings(baseSettings: _*) .settings( resolvers += "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/", libraryDependencies += "com.couchbase.client" % "couchbase-client" % "1.4.2", libraryDependencies += "com.typesafe.akka" %% "akka-actor" % "2.3.3" cross CrossVersion.binary, libraryDependencies += "com.typesafe.play" %% "play-iteratees" % "2.3.0" cross CrossVersion.binary, libraryDependencies += "com.typesafe.play" %% "play-json" % "2.3.0" cross CrossVersion.binary, libraryDependencies += "ch.qos.logback" % "logback-classic" % "1.1.1", libraryDependencies += "com.ning" % "async-http-client" % "1.8.8", libraryDependencies += "com.typesafe" % "config" % "1.2.1", libraryDependencies += "org.specs2" %% "specs2" % "2.3.12" % "test" cross CrossVersion.binary, organization := "org.reactivecouchbase", version := appVersion, publishTo <<= local, publishMavenStyle := true, publishArtifact in Test := false, pomIncludeRepository := { _ => false }, pomExtra := ( <url>http://reactivecouchbase.org</url> <licenses> <license> <name>Apache 2</name> <url>http://www.apache.org/licenses/LICENSE-2.0</url> <distribution>repo</distribution> </license> </licenses> <scm> <url><EMAIL>:ReactiveCouchbase/ReactiveCouchbase-core.git</url> <connection>scm:git:<EMAIL>:ReactiveCouchbase/ReactiveCouchbase-core.git</connection> </scm> <developers> <developer> <id>mathieu.ancelin</id> <name><NAME></name> <url>https://github.com/mathieuancelin</url> </developer> </developers>) ) }
wsargent/ReactiveCouchbase-core
driver/src/test/scala/AliasSpec.scala
<filename>driver/src/test/scala/AliasSpec.scala import org.reactivecouchbase.ReactiveCouchbaseDriver import org.reactivecouchbase.CouchbaseRWImplicits.documentAsJsObjectReader import org.reactivecouchbase.CouchbaseRWImplicits.jsObjectToDocumentWriter import org.specs2.mutable.{Tags, Specification} import play.api.libs.json.{JsObject, Json} import scala.concurrent.{Await} class AliasSpec extends Specification with Tags { sequential import Utils._ """ You need to start a Couchbase server with a 'default' bucket on standard port to run those tests ... """ in ok val driver = ReactiveCouchbaseDriver() val bucketDefault = driver.bucket("default") val aliasedBucketDefault = driver.bucket("aliased-default") "ReactiveCouchbase aliases" should { "insert data in default bucket" in { Await.result(bucketDefault.set[JsObject]("alias-key", Json.obj("hello" -> "world")), timeout) success } "fetch data from aliased default bucket" in { Await.result(aliasedBucketDefault.get[JsObject]("alias-key").map { json => json mustEqual Some(Json.obj("hello" -> "world")) }, timeout) success } "delete from default bucket" in { Await.result(bucketDefault.delete("alias-key"), timeout) success } "shutdown now" in { driver.shutdown() driver.shutdown() success } } }
gaborh-da/daml
ledger/ledger-api-common/src/test/suite/scala/com/digitalasset/ledger/api/validation/CommandSubmissionRequestValidatorTest.scala
// Copyright (c) 2019 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.digitalasset.ledger.api.validation import java.time.Instant import com.digitalasset.api.util.TimestampConversion import com.digitalasset.daml.lf.command.{Commands => LfCommands} import com.digitalasset.daml.lf.data._ import com.digitalasset.daml.lf.value.Value.ValueRecord import com.digitalasset.daml.lf.value.{Value => Lf} import com.digitalasset.ledger.api.DomainMocks.{applicationId, commandId, workflowId} import com.digitalasset.ledger.api.domain.{Commands => ApiCommands} import com.digitalasset.ledger.api.v1.commands.Commands import com.digitalasset.ledger.api.v1.value.Value.Sum import com.digitalasset.ledger.api.v1.value.{ List => ApiList, Map => ApiMap, Optional => ApiOptional, _ } import com.digitalasset.ledger.api.{DomainMocks, domain} import com.digitalasset.platform.server.api.validation.IdentifierResolver import com.google.protobuf.empty.Empty import io.grpc.Status.Code.{INVALID_ARGUMENT, NOT_FOUND} import org.scalatest.WordSpec import org.scalatest.prop.TableDrivenPropertyChecks import scalaz.syntax.tag._ import scala.concurrent.Future @SuppressWarnings(Array("org.wartremover.warts.Any")) class CommandSubmissionRequestValidatorTest extends WordSpec with ValidatorTestUtils with TableDrivenPropertyChecks { val ledgerId = "ledger-id" object api { val identifier = Identifier("package", moduleName = "module", entityName = "entity") val int64 = Sum.Int64(1) val label = "label" val constructor = "constructor" val workflowId = "workflowId" val applicationId = "applicationId" val commandId = "commandId" val submitter = "party" val let = TimestampConversion.fromInstant(Instant.now) val mrt = TimestampConversion.fromInstant(Instant.now) val commands = Commands( ledgerId, workflowId, applicationId, commandId, submitter, Some(let), Some(mrt), Seq.empty ) } object internal { val let = TimestampConversion.toInstant(api.let) val mrt = TimestampConversion.toInstant(api.mrt) val emptyCommands = ApiCommands( domain.LedgerId(ledgerId), Some(workflowId), applicationId, commandId, DomainMocks.party, let, mrt, LfCommands( ImmArray.empty, Time.Timestamp.assertFromInstant(let), workflowId.unwrap ) ) } val sut = new CommandSubmissionRequestValidator( ledgerId, new IdentifierResolver(_ => Future.successful(None))) def recordFieldWithValue(value: Value) = RecordField("label", Some(value)) private def unexpectedError = sys.error("unexpected error") "CommandSubmissionRequestValidator" when { "validating command submission requests" should { "convert valid requests with empty commands" in { sut.validateCommands(api.commands) shouldEqual Right(internal.emptyCommands) } "not allow missing ledgerId" in { requestMustFailWith( sut.validateCommands(api.commands.withLedgerId("")), NOT_FOUND, "Ledger ID '' not found. Actual Ledger ID is 'ledger-id'.") } "tolerate a missing workflowId" in { sut.validateCommands(api.commands.withWorkflowId("")) shouldEqual Right( internal.emptyCommands.copy( workflowId = None, commands = internal.emptyCommands.commands.copy(commandsReference = ""))) } "not allow missing applicationId" in { requestMustFailWith( sut.validateCommands(api.commands.withApplicationId("")), INVALID_ARGUMENT, "Missing field: application_id") } "not allow missing commandId" in { requestMustFailWith( sut.validateCommands(api.commands.withCommandId("")), INVALID_ARGUMENT, "Missing field: command_id") } "not allow missing submitter" in { requestMustFailWith( sut.validateCommands(api.commands.withParty("")), INVALID_ARGUMENT, """Invalid field party: string "" does not match regex "[a-zA-Z0-9\-_ ]+"""") } "not allow missing let" in { requestMustFailWith( sut.validateCommands(api.commands.copy(ledgerEffectiveTime = None)), INVALID_ARGUMENT, "Missing field: ledger_effective_time") } "not allow missing mrt" in { requestMustFailWith( sut.validateCommands(api.commands.copy(maximumRecordTime = None)), INVALID_ARGUMENT, "Missing field: maximum_record_time") } } "validating contractId values" should { "succeed" in { val coid = "coid" val input = Value(Sum.ContractId(coid)) val expected = Lf.ValueContractId(Lf.AbsoluteContractId(coid)) sut.validateValue(input) shouldEqual Right(expected) } } "validating party values" should { "convert valid party" in { sut.validateValue(DomainMocks.values.validApiParty) shouldEqual Right( DomainMocks.values.validLfParty) } "reject non valid party" in { requestMustFailWith( sut.validateValue(DomainMocks.values.invalidApiParty), INVALID_ARGUMENT, DomainMocks.values.invalidPartyMsg ) } } "validating decimal values" should { "convert valid decimals" in { val signs = Table("signs", "", "+", "-") val absoluteValues = Table( "absolute values", "0", "0.0", "3.1415926536", "1" + "0" * 27, "1" + "0" * 27 + "." + "0" * 9 + "1", "0." + "0" * 9 + "1" ) forEvery(signs) { sign => forEvery(absoluteValues) { absoluteValue => val s = sign + absoluteValue val input = Value(Sum.Decimal(s)) val expected = Lf.ValueDecimal(Decimal.fromString(s).getOrElse(unexpectedError)) sut.validateValue(input) shouldEqual Right(expected) } } } "reject out-of-bound decimals" in { val signs = Table("signs", "", "+", "-") val absoluteValues = Table( "absolute values", "1" + "0" * 28, "1" + "0" * 28 + "." + "0" * 9 + "1", "1" + "0" * 28 + "." + "0" * 10 + "1", "1" + "0" * 27 + "." + "0" * 10 + "1", "0." + "0" * 10 + "1", ) forEvery(signs) { sign => forEvery(absoluteValues) { absoluteValue => val s = sign + absoluteValue val input = Value(Sum.Decimal(s)) requestMustFailWith( sut.validateValue(input), INVALID_ARGUMENT, s"""Invalid argument: Could not read Decimal string "$s"""" ) } } } "reject invalid decimals" in { val signs = Table("signs", "", "+", "-") val absoluteValues = Table( "invalid absolute values", "zero", "1E10", "+", "-", "0x01", ".", "", "0.", ".0", ) forEvery(signs) { sign => forEvery(absoluteValues) { absoluteValue => val s = sign + absoluteValue val input = Value(Sum.Decimal(s)) requestMustFailWith( sut.validateValue(input), INVALID_ARGUMENT, s"""Invalid argument: Could not read Decimal string "$s"""" ) } } } } "validating text values" should { "accept any of them" in { val strings = Table("string", "", "a¶‱😂", "a¶‱😃") forEvery(strings) { s => val input = Value(Sum.Text(s)) val expected = Lf.ValueText(s) sut.validateValue(input) shouldEqual Right(expected) } } } "validating timestamp values" should { "accept valid timestamp" in { val testCases = Table( "long/timestamp", Time.Timestamp.MinValue.micros -> Time.Timestamp.MinValue, 0L -> Time.Timestamp.Epoch, Time.Timestamp.MaxValue.micros -> Time.Timestamp.MaxValue, ) forEvery(testCases) { case (long, timestamp) => val input = Value(Sum.Timestamp(long)) val expected = Lf.ValueTimestamp(timestamp) sut.validateValue(input) shouldEqual Right(expected) } } "reject out-of-bound timestamp" in { val testCases = Table( "long/timestamp", Long.MinValue, Time.Timestamp.MinValue.micros - 1, Time.Timestamp.MaxValue.micros + 1, Long.MaxValue) forEvery(testCases) { long => val input = Value(Sum.Timestamp(long)) requestMustFailWith( sut.validateValue(input), INVALID_ARGUMENT, s"Invalid argument: out of bound Timestamp $long" ) } } } "validating date values" should { "accept valid date" in { val testCases = Table( "int/date", Time.Date.MinValue.days -> Time.Date.MinValue, 0 -> Time.Date.Epoch, Time.Date.MaxValue.days -> Time.Date.MaxValue, ) forEvery(testCases) { case (int, date) => val input = Value(Sum.Date(int)) val expected = Lf.ValueDate(date) sut.validateValue(input) shouldEqual Right(expected) } } "reject out-of-bound date" in { val testCases = Table( "int/date", Int.MinValue, Time.Date.MinValue.days - 1, Time.Date.MaxValue.days + 1, Int.MaxValue) forEvery(testCases) { int => val input = Value(Sum.Date(int)) requestMustFailWith( sut.validateValue(input), INVALID_ARGUMENT, s"Invalid argument: out of bound Date $int" ) } } } "validating boolean values" should { "accept any of them" in { sut.validateValue(Value(Sum.Bool(true))) shouldEqual Right(Lf.ValueBool(true)) sut.validateValue(Value(Sum.Bool(false))) shouldEqual Right(Lf.ValueBool(false)) } } "validating unit values" should { "succeed" in { sut.validateValue(Value(Sum.Unit(Empty()))) shouldEqual Right(Lf.ValueUnit) } } "validating record values" should { "convert valid records" in { val record = Value( Sum.Record( Record(Some(api.identifier), Seq(RecordField(api.label, Some(Value(api.int64))))))) val expected = Lf.ValueRecord( Some(DomainMocks.identifier), ImmArray(Some(DomainMocks.label) -> DomainMocks.values.int64)) sut.validateValue(record) shouldEqual Right(expected) } "tolerate missing identifiers in records" in { val record = Value(Sum.Record(Record(None, Seq(RecordField(api.label, Some(Value(api.int64))))))) val expected = Lf.ValueRecord(None, ImmArray(Some(DomainMocks.label) -> DomainMocks.values.int64)) sut.validateValue(record) shouldEqual Right(expected) } "tolerate missing labels in record fields" in { val record = Value(Sum.Record(Record(None, Seq(RecordField("", Some(Value(api.int64))))))) val expected = ValueRecord(None, ImmArray(None -> DomainMocks.values.int64)) sut.validateValue(record) shouldEqual Right(expected) } "not allow missing record values" in { val record = Value(Sum.Record(Record(Some(api.identifier), Seq(RecordField(api.label, None))))) requestMustFailWith(sut.validateValue(record), INVALID_ARGUMENT, "Missing field: value") } } "validating variant values" should { "convert valid variants" in { val variant = Value(Sum.Variant(Variant(Some(api.identifier), api.constructor, Some(Value(api.int64))))) val expected = Lf.ValueVariant( Some(DomainMocks.identifier), DomainMocks.values.constructor, DomainMocks.values.int64) sut.validateValue(variant) shouldEqual Right(expected) } "tolerate missing identifiers" in { val variant = Value(Sum.Variant(Variant(None, api.constructor, Some(Value(api.int64))))) val expected = Lf.ValueVariant(None, DomainMocks.values.constructor, DomainMocks.values.int64) sut.validateValue(variant) shouldEqual Right(expected) } "not allow missing constructor" in { val variant = Value(Sum.Variant(Variant(None, "", Some(Value(api.int64))))) requestMustFailWith( sut.validateValue(variant), INVALID_ARGUMENT, "Missing field: constructor") } "not allow missing values" in { val variant = Value(Sum.Variant(Variant(None, api.constructor, None))) requestMustFailWith(sut.validateValue(variant), INVALID_ARGUMENT, "Missing field: value") } } "validating list values" should { "convert empty lists" in { val input = Value(Sum.List(ApiList(List.empty))) val expected = Lf.ValueList(FrontStack.empty) sut.validateValue(input) shouldEqual Right(expected) } "convert valid lists" in { val list = Value(Sum.List(ApiList(Seq(Value(api.int64), Value(api.int64))))) val expected = Lf.ValueList(FrontStack(ImmArray(DomainMocks.values.int64, DomainMocks.values.int64))) sut.validateValue(list) shouldEqual Right(expected) } "reject lists containing invalid values" in { val input = Value( Sum.List( ApiList(Seq(DomainMocks.values.validApiParty, DomainMocks.values.invalidApiParty)))) requestMustFailWith( sut.validateValue(input), INVALID_ARGUMENT, DomainMocks.values.invalidPartyMsg) } } "validating optional values" should { "convert empty optionals" in { val input = Value(Sum.Optional(ApiOptional(None))) val expected = Lf.ValueOptional(None) sut.validateValue(input) shouldEqual Right(expected) } "convert valid non-empty optionals" in { val list = Value(Sum.Optional(ApiOptional(Some(DomainMocks.values.validApiParty)))) val expected = Lf.ValueOptional(Some(DomainMocks.values.validLfParty)) sut.validateValue(list) shouldEqual Right(expected) } "reject optional containing invalid values" in { val input = Value(Sum.Optional(ApiOptional(Some(DomainMocks.values.invalidApiParty)))) requestMustFailWith( sut.validateValue(input), INVALID_ARGUMENT, DomainMocks.values.invalidPartyMsg) } } "validating map values" should { "convert empty maps" in { val input = Value(Sum.Map(ApiMap(List.empty))) val expected = Lf.ValueMap(SortedLookupList.empty) sut.validateValue(input) shouldEqual Right(expected) } "convert valid maps" in { val entries = ImmArray(1 until 5).map { x => Utf8.sha256(x.toString) -> x.toLong } val apiEntries = entries.map { case (k, v) => ApiMap.Entry(k, Some(Value(Sum.Int64(v)))) } val input = Value(Sum.Map(ApiMap(apiEntries.toSeq))) val lfEntries = entries.map { case (k, v) => k -> Lf.ValueInt64(v) } val expected = Lf.ValueMap(SortedLookupList.fromImmArray(lfEntries).getOrElse(unexpectedError)) sut.validateValue(input) shouldEqual Right(expected) } "reject maps with repeated keys" in { val entries = ImmArray(1 +: (1 until 5)).map { x => Utf8.sha256(x.toString) -> x.toLong } val apiEntries = entries.map { case (k, v) => ApiMap.Entry(k, Some(Value(Sum.Int64(v)))) } val input = Value(Sum.Map(ApiMap(apiEntries.toSeq))) requestMustFailWith( sut.validateValue(input), INVALID_ARGUMENT, s"Invalid argument: key ${Utf8.sha256("1")} duplicated when trying to build map") } "reject maps containing invalid value" in { val apiEntries = List( ApiMap.Entry("1", Some(DomainMocks.values.validApiParty)), ApiMap.Entry("2", Some(DomainMocks.values.invalidApiParty))) val input = Value(Sum.Map(ApiMap(apiEntries))) requestMustFailWith( sut.validateValue(input), INVALID_ARGUMENT, DomainMocks.values.invalidPartyMsg) } } } }
gaborh-da/daml
ledger/ledger-api-integration-tests/src/test/itsuite/scala/com/digitalasset/platform/tests/integration/ledger/api/TransactionServiceIT.scala
<reponame>gaborh-da/daml // Copyright (c) 2019 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.digitalasset.platform.tests.integration.ledger.api import java.time.{Duration, Instant} import akka.Done import akka.stream.scaladsl.{Flow, Sink} import com.digitalasset.grpc.adapter.utils.DirectExecutionContext import com.digitalasset.ledger.api.domain.EventId import com.digitalasset.ledger.api.testing.utils.MockMessages.{party, _} import com.digitalasset.ledger.api.testing.utils.{ AkkaBeforeAndAfterAll, IsStatusException, MockMessages, SuiteResourceManagementAroundAll } import com.digitalasset.ledger.api.v1.commands.Command.Command.Create import com.digitalasset.ledger.api.v1.commands.{Command, CreateCommand, ExerciseCommand} import com.digitalasset.ledger.api.v1.event.Event.Event.{Archived, Created} import com.digitalasset.ledger.api.v1.event.{ArchivedEvent, CreatedEvent, Event} import com.digitalasset.ledger.api.v1.ledger_offset.LedgerOffset import com.digitalasset.ledger.api.v1.transaction.{Transaction, TransactionTree, TreeEvent} import com.digitalasset.ledger.api.v1.transaction_filter.{Filters, TransactionFilter, _} import com.digitalasset.ledger.api.v1.transaction_service.TransactionServiceGrpc.TransactionService import com.digitalasset.ledger.api.v1.value.Value.Sum import com.digitalasset.ledger.api.v1.value.Value.Sum.{Bool, ContractId} import com.digitalasset.ledger.api.v1.value.{ Identifier, Optional, Record, RecordField, Value, Variant } import com.digitalasset.ledger.client.services.transactions.TransactionClient import com.digitalasset.platform.api.v1.event.EventOps._ import com.digitalasset.platform.apitesting.LedgerContextExtensions._ import com.digitalasset.platform.apitesting.{LedgerContext, MultiLedgerFixture, TestTemplateIds} import com.digitalasset.platform.esf.TestExecutionSequencerFactory import com.digitalasset.platform.participant.util.ValueConversions._ import com.digitalasset.platform.services.time.TimeProviderType import com.google.rpc.code.Code import io.grpc.{Status, StatusRuntimeException} import org.scalatest._ import org.scalatest.concurrent.AsyncTimeLimitedTests import org.scalatest.time.Span import org.scalatest.time.SpanSugar._ import scalaz.syntax.tag._ import scalaz.{ICons, NonEmptyList, Tag} import scala.collection.{breakOut, immutable} import scala.concurrent.Future @SuppressWarnings(Array("org.wartremover.warts.Any")) class TransactionServiceIT extends AsyncWordSpec with AkkaBeforeAndAfterAll with MultiLedgerFixture with SuiteResourceManagementAroundAll with Inside with AsyncTimeLimitedTests with TestExecutionSequencerFactory with TransactionServiceHelpers with ParameterShowcaseTesting with OptionValues with Matchers with TestTemplateIds { override protected val config: Config = Config.default.withTimeProvider(TimeProviderType.WallClock) override val timeLimit: Span = 300.seconds private def newClient(stub: TransactionService, ledgerId: String): TransactionClient = new TransactionClient(ledgerId, stub) private val getAllContracts = transactionFilter private def filterSingleTemplate(templateClientSubscribedTo: Identifier) = { TransactionFilter( Map(party -> Filters(Some(InclusiveFilters(List(templateClientSubscribedTo)))))) } private val NonEmptyList(party1, ICons(party2, ICons(party3, _))) = config.parties private val smallCommandCount = 5 private val configuredParties = config.parties.list.toList private val filterForAllParties = TransactionFilter( configuredParties.map(_ -> Filters.defaultInstance).toMap) private val unitArg = Value(Sum.Record(Record.defaultInstance)) "Transaction Service" when { "reading transactions with LedgerBegin as end offset" should { "serve an empty stream of transactions" in allFixtures { context => for { transactions <- context.transactionClient .getTransactions(ledgerBegin, Some(ledgerBegin), getAllContracts) .runWith(Sink.seq) } yield { transactions shouldBe empty } } } "submitting and reading transactions" should { "serve elements until canceled from downstream" in allFixtures { context => val elemsToTake = 10L for { _ <- insertCommands( getTrackerFlow(context), "cancellation-test", 14, config.assertStaticLedgerId) transactions <- context.transactionClient .getTransactions(ledgerBegin, None, getAllContracts) .take(elemsToTake) .runWith(Sink.seq) } yield { transactions should have length elemsToTake } } "deduplicate commands with identical command + application ID pairs" in allFixtures { context => val client = context.transactionClient for { le <- client.getLedgerEnd _ <- insertCommands("deduplicated", 1, context) _ = insertCommands("deduplicated", 1, context) // we don't wait for this since the result won't be seen txs <- client .getTransactions(le.getOffset, None, getAllContracts) .takeWithin(2.seconds) .runWith(Sink.seq) } yield { txs should have length 1 } } "respond with empty stream if TransactionFilter is empty" in allFixtures { context => context.transactionClient .getTransactions(ledgerBegin, None, TransactionFilter()) .runWith(Sink.seq) .map(_ shouldBe empty) } "complete the stream by itself as soon as LedgerEnd is hit" in allFixtures { context => val resultsF = context.transactionClient .getTransactions(ledgerBegin, Some(ledgerEnd), getAllContracts) .runWith(Sink.seq) for { _ <- insertCommands( getTrackerFlow(context), "stream-completion-test", 14, config.assertStaticLedgerId) _ <- resultsF } yield { succeed // resultF would not complete unless the server terminates the connection } } "serve the complete sequence of transactions even if processing is stopped and resumed mid-stream" in allFixtures { context => val client = context.transactionClient val commandsPerSection = smallCommandCount val sharedPrefix = "stream-partial-read-test" val firstSectionPrefix = sharedPrefix + "-1" for { ledgerEndResponse <- client.getLedgerEnd _ <- insertCommands(firstSectionPrefix, commandsPerSection, context) firstSection <- client .getTransactions(ledgerEndResponse.getOffset, None, getAllContracts) .filter(_.commandId.startsWith(sharedPrefix)) .take(commandsPerSection.toLong) .runWith(Sink.seq) _ = firstSection should have size commandsPerSection.toLong ledgerEndAfterFirstSection = lastOffsetIn(firstSection).value _ <- insertCommands(sharedPrefix + "-2", commandsPerSection, context) secondSection <- client .getTransactions(ledgerEndAfterFirstSection, None, getAllContracts) .take(commandsPerSection.toLong) .runWith(Sink.seq) _ = secondSection should have size commandsPerSection.toLong ledgerEndAfterSecondSection = lastOffsetIn(secondSection).value completeSequence <- client .getTransactions( ledgerEndResponse.getOffset, Some(ledgerEndAfterSecondSection), getAllContracts) .filter(_.commandId.startsWith(sharedPrefix)) .completionTimeout(3.seconds) .runWith(Sink.seq) } yield { completeSequence shouldEqual (firstSection ++ secondSection) completeSequence should have length (commandsPerSection.toLong * 2) } } "serve the same data for identical requests coming in parallel" in allFixtures { context => val client = context.transactionClient val commandPrefix = "parallel-subscription-test" val subscriptions = 10 for { ledgerEndOnStart <- client.getLedgerEnd _ <- insertCommands(commandPrefix, smallCommandCount, context) readTransactions = () => client .getTransactions(ledgerEndOnStart.getOffset, None, getAllContracts) .filter(_.commandId.startsWith(commandPrefix)) .take(smallCommandCount.toLong) .runWith(Sink.seq) results <- 1 .to(subscriptions) .map(_ => readTransactions()) .foldLeft(Future.successful(Vector.empty[Seq[Transaction]]))((accF, currF) => accF.flatMap(acc => currF.map(acc :+ _))) } yield { results.foreach(_ should have size smallCommandCount.toLong) results.sliding(2).foreach { case Vector(s1, s2) => s1 shouldEqual s2 } results.size shouldEqual subscriptions } } "not expose data to parties without privileges to see it" in allFixtures { context => val client = context.transactionClient val commandPrefix = "visibility-test" val anotherParty = "Alice" for { ledgerEndResponse <- client.getLedgerEnd _ <- insertCommands(commandPrefix, 1, context) // At this point we verified that the value has been written to the submitter's LSM. // This test code assumes that the value would be written to other parties' LSMs within 100 ms. transactions <- client .getTransactions( ledgerEndResponse.getOffset, None, TransactionFilter(Map(anotherParty -> Filters.defaultInstance))) .filter(_.commandId.startsWith(commandPrefix)) .takeWithin(100.millis) .runWith(Sink.seq) } yield { transactions shouldBe empty } } "serve an empty stream if start offset equals the end offset (supplied)" in allFixtures { context => val client = context.transactionClient for { ledgerEnd <- client.getLedgerEnd transactions <- client .getTransactions(ledgerEnd.getOffset, Some(ledgerEnd.getOffset), getAllContracts) .runWith(Sink.seq) } yield { transactions shouldBe empty } } "serve an empty stream if start offset equals the end offset (resolved on server from Boundary)" in allFixtures { context => for { savedLedgerEnd <- context.transactionClient.getLedgerEnd txs <- context.transactionClient .getTransactions(savedLedgerEnd.getOffset, Some(ledgerEnd), getAllContracts) .runWith(Sink.seq) } yield { txs shouldBe empty } } "return INVALID_ARGUMENT if start offset is after end offset" in allFixtures { context => val client = context.transactionClient for { savedLedgerEnd <- client.getLedgerEnd _ <- insertCommands("end-before-start-test", 1, context) tx <- client .getTransactions(savedLedgerEnd.getOffset, None, getAllContracts) .runWith(Sink.head) higherLedgerOffset = tx.offset error <- client .getTransactions( LedgerOffset(LedgerOffset.Value.Absolute(higherLedgerOffset)), Some(savedLedgerEnd.getOffset), getAllContracts) .runWith(Sink.head) .failed } yield { IsStatusException(Status.INVALID_ARGUMENT)(error) } } "expose transactions to non-submitting stakeholders without the commandId" in allFixtures { c => c.submitCreateAndReturnTransaction( "Checking commandId visibility for non-submitter party", templateIds.agreementFactory, List("receiver" -> party1.asParty, "giver" -> party2.asParty).asRecordFields, party2, party1 ) .map(_.commandId shouldBe empty) } "expose only the requested templates to the client" in allFixtures { context => val commandId = "Client should see only the Dummy create." val templateInSubscription = templateIds.dummy val otherTemplateCreated = templateIds.dummyFactory for { tx <- context.testingHelpers.submitAndListenForSingleResultOfCommand( context.command( commandId, List(templateInSubscription, otherTemplateCreated).map(tid => Command(create(tid, List("operator" -> "party".asParty))))), filterSingleTemplate(templateInSubscription) ) } yield { val singleEvent = getHead(tx.events.map(_.event)) singleEvent match { case Created(createdEvent) => createdEvent.templateId.value shouldEqual templateInSubscription case other => fail(s"Expected create event, got $other") } } } "expose contract Ids that are ready to be used for exercising choices" in allFixtures { context => val factoryCreation = "Creating factory" val exercisingChoice = "Exercising choice on factory" val exercisedTemplate = templateIds.dummyFactory for { createdEvent <- context.submitCreate( factoryCreation, exercisedTemplate, List("operator" -> "party".asParty).asRecordFields, "party") factoryContractId = createdEvent.contractId exerciseTx <- context.testingHelpers.submitAndListenForSingleResultOfCommand( context.command( exercisingChoice, List(exerciseCallChoice(exercisedTemplate, factoryContractId).wrap)), getAllContracts ) } yield { val events = exerciseTx.events.map(_.event) val (created, archived) = events.partition(_.isCreated) created should have length 2 getHead(archived).archived.value.contractId shouldEqual factoryContractId } } "expose contract Ids that are results of exercising choices when filtering by template" in allFixtures { context => val factoryCreation = "Creating second factory" val exercisingChoice = "Exercising choice on second factory" val exercisedTemplate = templateIds.dummyFactory for { creation <- context.submitCreate( factoryCreation, exercisedTemplate, List("operator" -> "party".asParty).asRecordFields, "party") factoryContractId = creation.contractId offsetToListenFrom <- context.testingHelpers.submitSuccessfullyAndReturnOffset( context.command( exercisingChoice, List(exerciseCallChoice(exercisedTemplate, factoryContractId).wrap))) txsWithCreate <- context.testingHelpers.listenForResultOfCommand( filterSingleTemplate(templateIds.dummyWithParam), Some(exercisingChoice), offsetToListenFrom) txsWithArchive <- context.testingHelpers.listenForResultOfCommand( filterSingleTemplate(templateIds.dummyFactory), Some(exercisingChoice), offsetToListenFrom) } yield { val txCreate = getHead(txsWithCreate) val txArchive = getHead(txsWithArchive) // Create txCreate.commandId shouldEqual exercisingChoice val createdEvent = getHead(createdEventsIn(txCreate)) createdEvent.getTemplateId shouldEqual templateIds.dummyWithParam // Archive txArchive.commandId shouldEqual exercisingChoice val archivedEvent = getHead(archivedEventsIn(txArchive)) archivedEvent.getTemplateId shouldEqual templateIds.dummyFactory } } "reject exercising a choice where an assertion fails" in allFixtures { c => for { dummy <- c.submitCreate( "Create for assertion failing test", templateIds.dummy, List("operator" -> party.asParty).asRecordFields, party) assertion <- failingExercise( c, "Assertion failing exercise", party, templateIds.dummy, dummy.contractId, "ConsumeIfTimeIsBetween", List( "begin" -> Instant.now().plus(Duration.ofDays(1)).asTime, "end" -> Instant.now().plus(Duration.ofDays(2)).asTime).asRecordValue, Code.INVALID_ARGUMENT, "error" // the error message is different with the unified interpreter, so the text is matched to error // N.B.: The full DAML error message here is not very lucid. ) } yield { assertion } } "accept and serve all kinds of arguments in creates" in allFixtures { c => val template = templateIds.parameterShowcase val expectedArg = paramShowcaseArgsWithoutLabels for { create <- c.submitCreate( "Creating contract with a multitude of param types", template, paramShowcaseArgs(templateIds.testPackageId), "party", verbose = false) } yield { create.getCreateArguments.recordId shouldBe empty create.getCreateArguments.fields shouldEqual expectedArg } } "accept and serve all kinds of verbose arguments in creates" in allFixtures { c => val template = templateIds.parameterShowcase val arg = paramShowcaseArgs(templateIds.testPackageId) val variant = Value(Value.Sum.Variant(Variant(None, "SomeInteger", 1.asInt64))) for { create <- c.submitCreate( "Creating contract with a multitude of verbose param types", template, arg, "party", verbose = true) } yield { val args = create.getCreateArguments args.recordId should contain(template) args.fields shouldEqual arg args.fields .collectFirst { case f if f.label == "nestedOptionalInteger" => f.value.value } .value .getRecord .fields .headOption .value .value // This is the actual field access. .value .getVariant .variantId should contain( template.copy(name = "Test.OptionalInteger", entityName = "OptionalInteger")) } } "accept and serve all kinds of arguments in choices" in allFixtures { c => val args = c.testingHelpers.recordFieldsWithArgument( paramShowcaseArgs(templateIds.testPackageId), RecordField("decimal", Some("37.0".asDecimal))) val expectedArg = paramShowcaseArgsWithoutLabels.updated(2, RecordField("", Some("37.0".asDecimal))) verifyParamShowcaseChoice( c, "Choice1", // choice name "same args", paramShowcaseArgumentsToChoice1Argument(Record(None, args)), // submitted choice args expectedArg) // expected args } "accept huge submissions with a long lists" in allFixtures { c => val listElements = 10000 // Gets very slow / times out after this val integerList = 1.to(listElements).map(_.toLong.asInt64).asList val arg: Seq[RecordField] = c.testingHelpers .recordFieldsWithArgument( paramShowcaseArgs(templateIds.testPackageId), RecordField(integerListRecordLabel, integerList)) val expectedArg = paramShowcaseArgsWithoutLabels.updated(7, RecordField("", integerList)) val template = templateIds.parameterShowcase for { create <- c.submitCreate( "Huge command with a long list", template, arg, "party" ) } yield { create.getCreateArguments.fields shouldEqual expectedArg } } "not archive the exercised contract on non-consuming choices" in allFixtures { c => val receiver = "party" val giver = "Alice" for { created <- c.submitCreateWithListenerAndReturnEvent( "Creating Agreement Factory", templateIds.agreementFactory, List("receiver" -> receiver.asParty, "giver" -> giver.asParty).asRecordFields, giver, giver) choiceResult <- c.testingHelpers.submitAndListenForSingleResultOfCommand( c.command( "Calling non-consuming choice", List( ExerciseCommand( Some(templateIds.agreementFactory), created.contractId, "CreateAgreement", Some(unitArg)).wrap) ) .update(_.commands.party := receiver), TransactionFilter(Map(receiver -> Filters.defaultInstance)) ) } yield { archivedEventsIn(choiceResult) shouldBe empty getHead(createdEventsIn(choiceResult)) should have( 'templateId (Some(templateIds.agreement))) } } "require only authorization of chosen branching signatory" in allFixtures { c => val branchingSignatoriesArg = getBranchingSignatoriesArg(true, party1, party2) val expectedArg = branchingSignatoriesArg.map(_.copy(label = "")) for { branchingSignatories <- c.submitCreateWithListenerAndReturnEvent( "BranchingSignatoriesTrue", templateIds.branchingSignatories, branchingSignatoriesArg, party1, party1) } yield { branchingSignatories.getCreateArguments.fields shouldEqual expectedArg } } "not disclose create to non-chosen branching signatory" in allFixtures { c => val branchingSignatoriesArg = getBranchingSignatoriesArg(false, party1, party2) c.submitCreateWithListenerAndAssertNotVisible( "BranchingSignatoriesFalse", templateIds.branchingSignatories, branchingSignatoriesArg, party2, party1) } "disclose create to chosen branching controller" in allFixtures { c => val templateId = templateIds.branchingControllers val branchingControllersArgs = getBranchingControllerArgs(party1, party2, party3, true) val expectedArg = branchingControllersArgs.map(_.copy(label = "")) for { branchingControllers <- c.submitCreateWithListenerAndReturnEvent( "BranchingControllersTrue", templateId, branchingControllersArgs, party1, party2) } yield { branchingControllers.getCreateArguments.fields shouldEqual expectedArg } } "not disclose create to non-chosen branching controller" in allFixtures { c => val templateId = templateIds.branchingControllers val branchingControllersArgs = getBranchingControllerArgs(party1, party2, party3, false) c.submitCreateWithListenerAndAssertNotVisible( "BranchingControllersFalse", templateId, branchingControllersArgs, party1, party2) } "disclose create to observers" in allFixtures { c => val giver = party1 val observers = List(party2, party3) val withObserversArg = Vector( RecordField("giver", giver.asParty), RecordField("observers", observers.map(_.asParty).asList)) val expectedArg = withObserversArg.map(_.copy(label = "")) Future .sequence(observers.map(observer => for { withObservers <- c.submitCreateWithListenerAndReturnEvent( "Obs1create:" + observer, templateIds.withObservers, withObserversArg, giver, observer) } yield { withObservers.getCreateArguments.fields shouldEqual expectedArg })) .map(_ => succeed) } "DAML engine returns Unit as argument to Nothing" in allFixtures { c => val createArguments = Vector( RecordField("operator", "party".asParty), RecordField("arg1", Value(Value.Sum.Optional(Optional(None)))) ) val expectedArgs = createArguments.map(_.copy(label = "")) c.submitCreate( "Creating contract with a Nothing argument", templateIds.nothingArgument, createArguments, "party") .map(_.getCreateArguments.fields shouldEqual expectedArgs) } "accept exercising a well-authorized multi-actor choice" in allFixtures { c => val List(operator, receiver, giver) = List(party1, party2, party3) val triProposalArg = mkTriProposalArg(operator, receiver, giver) val expectedArg = triProposalArg.map(_.copy(label = "")) for { agreement <- createAgreement(c, "MA1", receiver, giver) triProposal <- c.submitCreate( "MA1proposal", templateIds.triProposal, triProposalArg, operator) tx <- c.submitExercise( "MA1acceptance", templateIds.agreement, List("cid" -> Value(ContractId(triProposal.contractId))).asRecordValue, "AcceptTriProposal", agreement.contractId, giver ) } yield { val triAgreement = getHead(c.testingHelpers.createdEventsIn(tx)) triAgreement.getCreateArguments.fields shouldBe expectedArg } } "accept exercising a well-authorized multi-actor choice with coinciding controllers" in allFixtures { c => val List(operator, receiver, giver) = List(party1, party2, party3) val triProposalArg = mkTriProposalArg(operator, giver, giver) val expectedArg = triProposalArg.map(_.copy(label = "")) for { triProposal <- c.submitCreate( "MA2proposal", templateIds.triProposal, triProposalArg, operator) tx <- c.submitExercise( "MA2acceptance", templateIds.triProposal, unitArg, "TriProposalAccept", triProposal.contractId, giver) } yield { val triAgreement = getHead(c.testingHelpers.createdEventsIn(tx)) triAgreement.getCreateArguments.fields shouldBe expectedArg } } "reject exercising a multi-actor choice with missing authorizers" in allFixtures { c => val List(operator, receiver, giver) = List(party1, party2, party3) val triProposalArg = mkTriProposalArg(operator, receiver, giver) for { triProposal <- c.submitCreate( "MA3proposal", templateIds.triProposal, triProposalArg, operator) assertion <- failingExercise( c, "MA3acceptance", giver, templateIds.triProposal, triProposal.contractId, "TriProposalAccept", unitArg, Code.INVALID_ARGUMENT, // the error message is different with the unified interpreter, so the text is matched to error "error" ) } yield { assertion } } // NOTE(MH): This is the current, most conservative semantics of // multi-actor choice authorization. It is likely that this will change // in the future. Should we delete this test, we should also remove the // 'UnrestrictedAcceptTriProposal' choice from the 'Agreement' template. "reject exercising a multi-actor choice with too many authorizers" in allFixtures { c => val List(operator, receiver, giver) = List(party1, party2, party3) val triProposalArg = mkTriProposalArg(operator, giver, giver) for { agreement <- createAgreement(c, "MA4", receiver, giver) triProposal <- c.submitCreate( "MA4proposal", templateIds.triProposal, triProposalArg, operator) assertion <- failingExercise( c, "MA4acceptance", giver, templateIds.agreement, agreement.contractId, "AcceptTriProposal", List("cid" -> Value(ContractId(triProposal.contractId))).asRecordValue, Code.INVALID_ARGUMENT, "error" // the error message is different with the unified interpreter, so the text is matched to error ) } yield { assertion } } "not reorder fields in data structures of choices" in allFixtures { c => val arguments = List("street", "city", "state", "zip") for { dummy <- c.submitCreate( "Create dummy for creating AddressWrapper", templateIds.dummy, List("operator" -> party.asParty).asRecordFields, party) exercise <- c.submitExercise( "Creating AddressWrapper", templateIds.dummy, List("address" -> arguments.map(e => e -> e.asText).asRecordValue).asRecordValue, "WrapWithAddress", dummy.contractId, party ) } yield { val events = c.testingHelpers.createdEventsIn(exercise) events should have length 1 val createRecordFields = events.headOption.value.createArguments.value.fields createRecordFields should have length 2 val addressRecordFields = createRecordFields .map(_.value.value) .collectFirst { case Value(Value.Sum.Record(Record(_, fields))) => fields } .value addressRecordFields.map(_.value.value) should contain theSameElementsInOrderAs arguments .map(_.asText) } } "serve the proper content for each party, regardless of single/multi party subscription" in allFixtures { c => val configuredParties = config.parties.list.toList for { mpResults <- c.transactionClient .getTransactions( ledgerBegin, Some(ledgerEnd), TransactionFilter(configuredParties.map(_ -> Filters.defaultInstance).toMap)) .runWith(Sink.seq) spResults <- Future.sequence(configuredParties.map { party => c.transactionClient .getTransactions( ledgerBegin, Some(ledgerEnd), TransactionFilter( Map(party -> Filters.defaultInstance) )) .runWith(Sink.seq) }) } yield { val brokenUpMultiPartyEvents = mpResults.flatMap(tx => tx.events.flatMap { event => withClue("All disclosed events should have a non-empty set of witnesses")( event.witnesses should not be empty) event.witnesses.map(w => event.withWitnesses(List(w))) }) val singlePartyEvents = spResults.flatten.flatMap(_.events) brokenUpMultiPartyEvents should contain theSameElementsAs singlePartyEvents } } } "ledger Ids don't match" should { "fail with the expected status" in allFixtures { context => newClient(context.transactionService, "notLedgerId") .getTransactions(ledgerBegin, Some(ledgerEnd), getAllContracts) .runWith(Sink.head) .failed .map(IsStatusException(Status.NOT_FOUND)) } } "querying ledger end" should { "return the value if ledger Ids match" in allFixtures { context => context.transactionClient.getLedgerEnd.map(_ => succeed) } "return NOT_FOUND if ledger Ids don't match" in allFixtures { context => newClient(context.transactionService, "not" + config.assertStaticLedgerId).getLedgerEnd.failed .map(IsStatusException(Status.NOT_FOUND)) } } "asking for historical transaction trees by id" should { "return the transaction tree if it exists, and the party can see it" in allFixtures { context => val beginOffset = LedgerOffset(LedgerOffset.Value.Boundary(LedgerOffset.LedgerBoundary.LEDGER_BEGIN)) for { _ <- insertCommands( getTrackerFlow(context), "tree-provenance-by-id", 1, config.assertStaticLedgerId) firstTransaction <- context.transactionClient .getTransactions(beginOffset, None, transactionFilter) .runWith(Sink.head) transactionId = firstTransaction.transactionId response <- context.transactionClient .getTransactionById(transactionId, List("party")) notVisibleError <- context.transactionClient .getTransactionById(transactionId, List("Alice")) .failed } yield { response.transaction should not be empty inside(notVisibleError) { case sre: StatusRuntimeException => sre.getStatus.getCode shouldEqual Status.INVALID_ARGUMENT.getCode sre.getStatus.getDescription shouldEqual "Transaction not found, or not visible." } } } "return INVALID_ARGUMENT if it does not exist" in allFixtures { context => context.transactionClient .getTransactionById( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", List("party")) .failed .map(IsStatusException(Status.INVALID_ARGUMENT)) } "fail with the expected status on a ledger Id mismatch" in allFixtures { context => newClient(context.transactionService, "not" + config.assertStaticLedgerId) .getTransactionById(transactionId, List("party")) .failed .map(IsStatusException(Status.NOT_FOUND)) } "fail with INVALID_ARGUMENT status if the requesting parties field is empty" in allFixtures { context => context.transactionClient .getTransactionById(transactionId, Nil) .failed .map(IsStatusException(Status.INVALID_ARGUMENT)) } "return the same events for each tx as the transaction stream itself" in allFixtures { context => val requestingParties = transactionFilter.filtersByParty.keySet context.transactionClient .getTransactions(ledgerBegin, Some(ledgerEnd), transactionFilter, true) .mapAsyncUnordered(16) { tx => context.transactionClient .getTransactionById(tx.transactionId, requestingParties.toList) .map(tx -> _.getTransaction) } .runFold(succeed) { (acc, pair) => inside(pair) { case (tx, tree) => tx.transactionId shouldEqual tree.transactionId tx.traceContext shouldEqual tree.traceContext tx.commandId shouldEqual tree.commandId tx.effectiveAt shouldEqual tree.effectiveAt tx.workflowId shouldEqual tree.workflowId // tx.offset shouldEqual tree.offset We don't return the offset. // TODO we can't get proper Archived Event Ids while the old daml core interpreter is in place. ADD JIRA val flatEvents = tx.events.map { case Event(Archived(v)) => Archived(v.copy(eventId = "")) case other => other.event } val treeEvents = tree.rootEventIds.flatMap(e => getEventsFromTree(e, tree.eventsById, Nil)) withClue("Non-requesting party present among witnesses") { treeEvents.foreach { event => event.witnesses.foreach(party => requestingParties should contain(party)) } } treeEvents.filter(_.isCreated) should contain theSameElementsAs flatEvents.filter( _.isCreated) // there are some transient archives present in the events generated from the tree treeEvents.filter(_.isArchived) should contain allElementsOf flatEvents.filter( _.isArchived) succeed } } } } "asking for historical flat transactions by id" should { "return the flat transaction if it exists, and the party can see it" in allFixtures { context => val beginOffset = LedgerOffset(LedgerOffset.Value.Boundary(LedgerOffset.LedgerBoundary.LEDGER_BEGIN)) for { _ <- insertCommands( getTrackerFlow(context), "flat-provenance-by-id", 1, config.assertStaticLedgerId) firstTransaction <- context.transactionClient .getTransactions(beginOffset, None, transactionFilter) .runWith(Sink.head) transactionId = firstTransaction.transactionId response <- context.transactionClient .getFlatTransactionById(transactionId, List("party")) notVisibleError <- context.transactionClient .getFlatTransactionById(transactionId, List("Alice")) .failed } yield { response.transaction should not be empty inside(notVisibleError) { case sre: StatusRuntimeException => sre.getStatus.getCode shouldEqual Status.INVALID_ARGUMENT.getCode sre.getStatus.getDescription shouldEqual "Transaction not found, or not visible." } } } "return INVALID_ARGUMENT if it does not exist" in allFixtures { context => context.transactionClient .getFlatTransactionById( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", List("party")) .failed .map(IsStatusException(Status.INVALID_ARGUMENT)) } "fail with the expected status on a ledger Id mismatch" in allFixtures { context => newClient(context.transactionService, "not" + config.assertStaticLedgerId) .getFlatTransactionById(transactionId, List("party")) .failed .map(IsStatusException(Status.NOT_FOUND)) } "fail with INVALID_ARGUMENT status if the requesting parties field is empty" in allFixtures { context => context.transactionClient .getFlatTransactionById(transactionId, Nil) .failed .map(IsStatusException(Status.INVALID_ARGUMENT)) } "return the same events for each tx as the transaction stream itself" in allFixtures { context => val requestingParties = transactionFilter.filtersByParty.keySet context.transactionClient .getTransactions(ledgerBegin, Some(ledgerEnd), transactionFilter, true) .mapAsyncUnordered(16) { tx => context.transactionClient .getFlatTransactionById(tx.transactionId, requestingParties.toList) .map(tx -> _.getTransaction) } .runFold(succeed) { case (acc, (original, byId)) => byId shouldBe original } } } "asking for historical transaction trees by event id" should { "return the transaction tree if it exists" in allFixtures { context => val beginOffset = LedgerOffset(LedgerOffset.Value.Boundary(LedgerOffset.LedgerBoundary.LEDGER_BEGIN)) for { _ <- insertCommands( getTrackerFlow(context), "tree provenance-by-event-id", 1, config.assertStaticLedgerId) tx <- context.transactionClient .getTransactions(beginOffset, None, transactionFilter) .runWith(Sink.head) eventId = tx.events.headOption .map(_.event match { case Archived(v) => v.eventId case Created(v) => v.eventId case Event.Event.Empty => fail(s"Received empty event in $tx") }) .value result <- context.transactionClient .getTransactionByEventId(eventId, Seq(party)) notVisibleError <- context.transactionClient .getTransactionByEventId(eventId, List("Alice")) .failed } yield { result.transaction should not be empty inside(notVisibleError) { case sre: StatusRuntimeException => sre.getStatus.getCode shouldEqual Status.INVALID_ARGUMENT.getCode sre.getStatus.getDescription shouldEqual "Transaction not found, or not visible." } } } "return INVALID_ARGUMENT for invalid event IDs" in allFixtures { context => context.transactionClient .getTransactionByEventId("don't worry, be happy", List("party")) .failed .map(IsStatusException(Status.INVALID_ARGUMENT)) } "return INVALID_ARGUMENT if it does not exist" in allFixtures { context => context.transactionClient .getTransactionByEventId( "#aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:000", List("party")) .failed .map(IsStatusException(Status.INVALID_ARGUMENT)) } "fail with the expected status on a ledger Id mismatch" in allFixtures { context => newClient(context.transactionService, "not" + config.assertStaticLedgerId) .getTransactionByEventId("#42:0", List("party")) .failed .map(IsStatusException(Status.NOT_FOUND)) } "fail with INVALID_ARGUMENT status if the requesting parties field is empty" in allFixtures { context => context.transactionClient .getTransactionByEventId(transactionId, Nil) .failed .map(IsStatusException(Status.INVALID_ARGUMENT)) } } "asking for historical flat transactions by event id" should { "return the flat transaction if it exists" in allFixtures { context => val beginOffset = LedgerOffset(LedgerOffset.Value.Boundary(LedgerOffset.LedgerBoundary.LEDGER_BEGIN)) for { _ <- insertCommands( getTrackerFlow(context), "flat-provenance-by-event-id", 1, config.assertStaticLedgerId) tx <- context.transactionClient .getTransactions(beginOffset, None, transactionFilter) .runWith(Sink.head) eventId = tx.events.headOption .map(_.event match { case Archived(v) => v.eventId case Created(v) => v.eventId case Event.Event.Empty => fail(s"Received empty event in $tx") }) .value result <- context.transactionClient .getFlatTransactionByEventId(eventId, Seq(party)) notVisibleError <- context.transactionClient .getFlatTransactionByEventId(eventId, List("Alice")) .failed } yield { result.transaction should not be empty inside(notVisibleError) { case sre: StatusRuntimeException => sre.getStatus.getCode shouldEqual Status.INVALID_ARGUMENT.getCode sre.getStatus.getDescription shouldEqual "Transaction not found, or not visible." } } } "return INVALID_ARGUMENT for invalid event IDs" in allFixtures { context => context.transactionClient .getFlatTransactionByEventId("don't worry, be happy", List("party")) .failed .map(IsStatusException(Status.INVALID_ARGUMENT)) } "return INVALID_ARGUMENT if it does not exist" in allFixtures { context => context.transactionClient .getFlatTransactionByEventId( "#aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:000", List("party")) .failed .map(IsStatusException(Status.INVALID_ARGUMENT)) } "fail with the expected status on a ledger Id mismatch" in allFixtures { context => newClient(context.transactionService, "not" + config.assertStaticLedgerId) .getFlatTransactionByEventId("#42:0", List("party")) .failed .map(IsStatusException(Status.NOT_FOUND)) } "fail with INVALID_ARGUMENT status if the requesting parties field is empty" in allFixtures { context => context.transactionClient .getFlatTransactionByEventId(transactionId, Nil) .failed .map(IsStatusException(Status.INVALID_ARGUMENT)) } } "reading transactions events " should { def validateStream(getEvents: () => Future[Seq[Event.Event]]) = for { events <- getEvents() } yield { val (creates, archives) = events.zipWithIndex.partition(_._1.isCreated) val createIndices = creates.map { case (e, i) => e.contractId -> i }.toMap val archiveIndices = archives.map { case (e, i) => e.contractId -> i }.toMap createIndices.size shouldEqual creates.size archiveIndices.size shouldEqual archives.size archiveIndices.map { case (cId, archiveIndex) => val createIndex = createIndices(cId) createIndex should be < archiveIndex } } val configuredParties = config.parties.list.toList "not arrive out of order when using single party subscription " in allFixtures { c => Future .sequence( configuredParties.map( p => validateStream( () => c.transactionClient .getTransactions( ledgerBegin, Some(ledgerEnd), TransactionFilter( Map(p -> Filters.defaultInstance) )) .runWith(Sink.seq) .map(_.flatMap(_.events.map(_.event))) ))) .map(_ => succeed) } "not arrive out of order when using a multi party subscription " in allFixtures { c => validateStream( () => c.transactionClient .getTransactions( ledgerBegin, Some(ledgerEnd), TransactionFilter(configuredParties.map(_ -> Filters.defaultInstance).toMap)) .runWith(Sink.seq) .map(_.flatMap(_.events.map(_.event))) ).map(_ => succeed) } } "reading transaction trees with LedgerBegin as end offset" should { "serve an empty stream of transactions" in allFixtures { context => context.transactionClient .getTransactionTrees(ledgerBegin, Some(ledgerBegin), transactionFilter) .runWith(Sink.seq) .map(_ shouldBe empty) } "fail with the expected status on a ledger Id mismatch" in allFixtures { context => new TransactionClient("notLedgerId", context.transactionService) .getTransactionTrees(ledgerBegin, Some(ledgerEnd), transactionFilter) .runWith(Sink.head) .failed .map(IsStatusException(Status.NOT_FOUND)) } "reading transaction trees without an end offset" should { "serve elements until canceled from downstream" in allFixtures { context => val elemsToTake = 10L val commandsToSend = 14 val resultsF = context.transactionClient .getTransactionTrees(ledgerBegin, None, transactionFilter) .take(elemsToTake) .runWith(Sink.seq) for { _ <- insertCommands( getTrackerFlow(context), "cancellation-test-tree", commandsToSend, config.assertStaticLedgerId) elems <- resultsF } yield (elems should have length elemsToTake) } "serve the proper content for each party, regardless of single/multi party subscription" in allFixtures { c => for { mpResults <- c.transactionClient .getTransactionTrees(ledgerBegin, Some(ledgerEnd), filterForAllParties) .runWith(Sink.seq) spResults <- Future.sequence(configuredParties.map { party => c.transactionClient .getTransactionTrees( ledgerBegin, Some(ledgerEnd), TransactionFilter( Map(party -> Filters.defaultInstance) )) .runWith(Sink.seq) .map(party -> _)(DirectExecutionContext) }) } yield { val mpTransactionById: Map[String, TransactionTree] = mpResults.map(t => t.transactionId -> t)(breakOut) val spTreesByParty = spResults.toMap for { (inspectedParty, transactions) <- spTreesByParty transaction <- transactions } { transaction.rootEventIds.foreach( evId => transaction .eventsById(evId) .kind .fold(_.witnessParties, _.witnessParties) should not be empty) val multiPartyTx = mpTransactionById(transaction.transactionId) val filteredMultiPartyTx = removeOtherWitnesses(multiPartyTx, inspectedParty) val withoutInvisibleRoots = removeInvisibleRoots(filteredMultiPartyTx, inspectedParty) transaction.rootEventIds shouldEqual withoutInvisibleRoots.rootEventIds transaction.eventsById shouldEqual withoutInvisibleRoots.eventsById } succeed } } } "reading transaction trees with LedgerEnd as end offset" should { "complete the stream by itself as soon as LedgerEnd is hit" in allFixtures { context => val noOfCommands = 10 for { r1 <- context.transactionClient .getTransactionTrees(ledgerBegin, Some(ledgerEnd), transactionFilter) .runWith(Sink.seq) _ <- insertCommands( getTrackerFlow(context), "complete_test", noOfCommands, config.assertStaticLedgerId) r2 <- context.transactionClient .getTransactionTrees(ledgerBegin, Some(ledgerEnd), transactionFilter) .runWith(Sink.seq) } yield { r2.size - r1.size shouldEqual (noOfCommands.toLong) } } } "reading flat transactions and trees" should { "serve a subset of the tree data in the flat stream" in allFixtures { context => val treesF = context.transactionClient .getTransactionTrees( ledgerBegin, Some(ledgerEnd), TransactionFilter(Map("Bob" -> Filters()))) .runWith(Sink.seq) val txsF = context.transactionClient .getTransactions( ledgerBegin, Some(ledgerEnd), TransactionFilter(Map("Bob" -> Filters()))) .runWith(Sink.seq) for { txs <- txsF trees <- treesF _ = txs.map(_.transactionId) shouldEqual trees.map(_.transactionId) } yield { for { (tx, tree) <- txs.iterator.zip(trees.iterator) treeEventIds: Set[EventId] = Tag.subst(tree.eventsById.keySet) txEvent <- tx.events } { withClue( "There should be no event that the flat API serves, but the tree API does not.") { treeEventIds should contain(txEvent.eventId) } withClue( "Witnesses on the flat API must be a subset of the witnesses on the tree API") { val treeEventWitnesses = tree.eventsById(txEvent.eventId.unwrap).witnessParties.toSet txEvent.witnesses.foreach(w => treeEventWitnesses should contain(w)) } } succeed } } } "reading transactions" should { "serve a stream of transactions" in allFixtures { context => val treesF = context.transactionClient .getTransactionTrees( ledgerBegin, Some(ledgerEnd), TransactionFilter(Map("Bob" -> Filters()))) .map(_.eventsById.values) .mapConcat(context.testingHelpers.exercisedEventsInNodes(_).toList) .map(_.exerciseResult) .runWith(Sink.seq) treesF.map { results => all(results) should not be empty } } } } } private def getEventsFromTree( eventId: String, events: Map[String, TreeEvent], inheritedWitnesses: Seq[String] = Nil): Seq[Event.Event] = { val event = events(eventId).kind event match { case TreeEvent.Kind.Empty => fail("Unexpected empty event") case TreeEvent.Kind.Created(c) => List(Event.Event.Created(c)) case TreeEvent.Kind.Exercised(e) => val allWitnesses = e.witnessParties ++ inheritedWitnesses val childEvents = e.childEventIds.flatMap { e => getEventsFromTree(e, events, allWitnesses) } childEvents ++ (if (e.consuming) // TODO we can't get proper Archived Event Ids while the old daml core interpreter is in place. ADD JIRA List( Archived( ArchivedEvent("", e.contractId, e.templateId, allWitnesses.distinct))) else Nil) } } private def getTrackerFlow(context: LedgerContext) = { Flow.lazyInitAsync(() => context.commandClient().flatMap(_.trackCommands[Int](List(MockMessages.party)))) } private def getBranchingSignatoriesArg( whichSign: Boolean, signTrue: String, signFalse: String) = { Vector( RecordField("whichSign", Value(Bool(whichSign))), RecordField("signTrue", signTrue.asParty), RecordField("signFalse", signFalse.asParty) ) } private def getBranchingControllerArgs( giver: String, ctrlTrue: String, ctrlFalse: String, whichCtrl: Boolean) = { Vector( RecordField("giver", giver.asParty), RecordField("whichCtrl", Value(Bool(whichCtrl))), RecordField("ctrlTrue", ctrlTrue.asParty), RecordField("ctrlFalse", ctrlFalse.asParty) ) } private def exerciseCallChoice(exercisedTemplate: Identifier, factoryContractId: String) = { ExerciseCommand(Some(exercisedTemplate), factoryContractId, "DummyFactoryCall", Some(unitArg)) } private def insertCommands( prefix: String, commandsPerSection: Int, context: LedgerContext): Future[Done] = { insertCommands(getTrackerFlow(context), prefix, commandsPerSection, config.assertStaticLedgerId) } private def lastOffsetIn(secondSection: immutable.Seq[Transaction]): Option[LedgerOffset] = { secondSection.lastOption.map(tx => LedgerOffset(LedgerOffset.Value.Absolute(tx.offset))) } private def create(templateId: Identifier, arguments: immutable.Seq[(String, Value)]): Create = { Create(CreateCommand(Some(templateId), Some(arguments.asRecordOf(templateId)))) } def getHead[T](elements: Iterable[T]): T = { elements should have size 1 elements.headOption.value } private def findCreatedEventIn( contractCreationTx: Transaction, templateToLookFor: Identifier): CreatedEvent = { // for helpful scalatest error message createdEventsIn(contractCreationTx).flatMap(_.templateId.toList) should contain( templateToLookFor) createdEventsIn(contractCreationTx).find(_.templateId.contains(templateToLookFor)).value } private def createdEventsIn(transaction: Transaction): Seq[CreatedEvent] = transaction.events .map(_.event) .collect { case Created(createdEvent) => createdEvent } private def archivedEventsIn(transaction: Transaction): Seq[ArchivedEvent] = transaction.events.map(_.event).collect { case Archived(archivedEvent) => archivedEvent } private def mkTriProposalArg( operator: String, receiver: String, giver: String ): Vector[RecordField] = { Vector( RecordField("operator", operator.asParty), RecordField("receiver", receiver.asParty), RecordField("giver", giver.asParty)) } private def removeOtherWitnesses(t: TransactionTree, party: String): TransactionTree = { t.copy(eventsById = t.eventsById.map { case (eventId, event) => eventId -> TreeEvent( event.kind.fold[TreeEvent.Kind]( ev => TreeEvent.Kind.Exercised(ev.withWitnessParties(ev.witnessParties.filter(_ == party))), ev => TreeEvent.Kind.Created(ev.withWitnessParties(ev.witnessParties.filter(_ == party))) )) }) } private def removeInvisibleRoots(t: TransactionTree, party: String): TransactionTree = { val rootsWithVisibility = t.rootEventIds.map { eventId => val event = t.eventsById(eventId).kind val witnessParties = event.fold(_.witnessParties, _.witnessParties) val visible = witnessParties.contains(party) eventId -> visible } if (rootsWithVisibility.exists(_._2 == false)) { val newRoots = rootsWithVisibility.flatMap { case (eventId, visible) => if (visible) List(eventId) else Tag.unsubst(t.eventsById(eventId).children) } val eventsWithoutInvisibleRoots = rootsWithVisibility.foldLeft(t.eventsById) { case (acc, (eventId, visible)) => if (visible) acc else acc - eventId } removeInvisibleRoots( t.copy(rootEventIds = newRoots, eventsById = eventsWithoutInvisibleRoots), party) } else t } private def createAgreement( c: LedgerContext, commandId: String, receiver: String, giver: String ): Future[CreatedEvent] = { for { agreementFactory <- c.submitCreate( commandId + "factory creation", templateIds.agreementFactory, List( "receiver" -> receiver.asParty, "giver" -> giver.asParty ).asRecordFields, giver) tx <- c.submitExercise( commandId + " acceptance", templateIds.agreementFactory, unitArg, "AgreementFactoryAccept", agreementFactory.contractId, receiver) } yield { getHead(c.testingHelpers.createdEventsIn(tx)) } } private def failingExercise( c: LedgerContext, commandId: String, submitter: String, template: Identifier, contractId: String, choice: String, arg: Value, code: Code, pattern: String ): Future[Assertion] = c.testingHelpers.assertCommandFailsWithCode( c.command( commandId, List(ExerciseCommand(Some(template), contractId, choice, Some(arg)).wrap)) .update( _.commands.party := submitter ), code, pattern ) private def verifyParamShowcaseChoice( context: LedgerContext, choice: String, lbl: String, exerciseArg: Value, expectedCreateArgs: Seq[RecordField]): Future[Assertion] = { for { creation <- context.submitCreate( s"Creating contract with a multitude of param types for exercising ($choice, $lbl)", templateIds.parameterShowcase, paramShowcaseArgs(templateIds.testPackageId), MockMessages.party ) contractId = creation.contractId // first, verify that if we submit with the same inputs they're equal exerciseCommand = ExerciseCommand( Some(templateIds.parameterShowcase), contractId, choice, exerciseArg).wrap exerciseTx <- context.testingHelpers.submitAndListenForSingleResultOfCommand( context.command( s"Exercising with a multitiude of params ($choice, $lbl)", List(exerciseCommand)), getAllContracts ) } yield { // check that we have the create val create = getHead(createdEventsIn(exerciseTx)) create.getCreateArguments.fields shouldEqual expectedCreateArgs } } }
gaborh-da/daml
ledger/ledger-api-integration-tests/src/test/lib/scala/com/digitalasset/platform/PlatformApplications.scala
<reponame>gaborh-da/daml // Copyright (c) 2019 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.digitalasset.platform import java.io.File import java.nio.file.Path import java.time.Duration import com.digitalasset.platform.common.LedgerIdMode import com.digitalasset.platform.sandbox.config.{ CommandConfiguration, DamlPackageContainer, SandboxConfig } import com.digitalasset.platform.services.time.{TimeModel, TimeProviderType} import scalaz.NonEmptyList import scala.concurrent.duration.{FiniteDuration, _} object PlatformApplications { /** * Meant to be a simple common denominator for fixture configuration. The constructor is private to avoid using * exceptions for validation. * * In the companion object add more smart constructors with * validation if you need other parameters than the ones provided * existing smart constructors */ final case class Config private ( ledgerId: LedgerIdMode, darFiles: List[Path], parties: NonEmptyList[String], committerParty: String, timeProviderType: TimeProviderType, timeModel: TimeModel, heartBeatInterval: FiniteDuration = 5.seconds, persistenceEnabled: Boolean = false, maxNumberOfAcsContracts: Option[Int] = None, commandConfiguration: CommandConfiguration = SandboxConfig.defaultCommandConfig) { require( Duration.ofSeconds(timeModel.minTtl.getSeconds) == timeModel.minTtl && Duration.ofSeconds(timeModel.maxTtl.getSeconds) == timeModel.maxTtl, "Max TTL's granularity is subsecond. Ledger Server does not support subsecond granularity for this configuration - please use whole seconds." ) @SuppressWarnings(Array("org.wartremover.warts.StringPlusAny")) def assertStaticLedgerId: String = ledgerId match { case LedgerIdMode.Static(ledgerId) => ledgerId case _ => throw new IllegalArgumentException("Unsupported ledger id config: " + ledgerId) } def withDarFile(path: Path) = copy(darFiles = List(path)) def withDarFiles(path: List[Path]) = copy(darFiles = path) def withTimeProvider(tpt: TimeProviderType) = copy(timeProviderType = tpt) def withLedgerIdMode(mode: LedgerIdMode): Config = copy(ledgerId = mode) def withParties(p1: String, rest: String*) = copy(parties = NonEmptyList(p1, rest: _*)) def withCommitterParty(committer: String) = copy(committerParty = committer) def withPersistence(enabled: Boolean) = copy(persistenceEnabled = enabled) def withHeartBeatInterval(interval: FiniteDuration) = copy(heartBeatInterval = interval) def withMaxNumberOfAcsContracts(cap: Int) = copy(maxNumberOfAcsContracts = Some(cap)) def withCommandConfiguration(cc: CommandConfiguration) = copy(commandConfiguration = cc) } object Config { val defaultLedgerId = "ledger server" val defaultDarFile = new File("ledger/sandbox/Test.dar") val defaultParties = NonEmptyList("party", "Alice", "Bob") val defaultTimeProviderType = TimeProviderType.Static def default: Config = { val darFiles = List(defaultDarFile) new Config( LedgerIdMode.Static(defaultLedgerId), darFiles.map(_.toPath), defaultParties, "committer", defaultTimeProviderType, TimeModel.reasonableDefault ) } } def sandboxConfig(config: Config, jdbcUrl: Option[String]) = { val selectedPort = 0 SandboxConfig( address = None, port = selectedPort, damlPackageContainer = DamlPackageContainer(config.darFiles.map(_.toFile)), timeProviderType = config.timeProviderType, timeModel = config.timeModel, commandConfig = config.commandConfiguration, scenario = None, tlsConfig = None, ledgerIdMode = config.ledgerId, jdbcUrl = jdbcUrl ) } }
gaborh-da/daml
ledger/ledger-api-integration-tests/src/test/lib/scala/com/digitalasset/platform/apitesting/LedgerFactories.scala
<gh_stars>0 // Copyright (c) 2019 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.digitalasset.platform.apitesting import java.io.{BufferedInputStream, FileInputStream, InputStream} import java.nio.file.Path import com.digitalasset.daml.lf.data.Ref import com.digitalasset.grpc.adapter.ExecutionSequencerFactory import com.digitalasset.ledger.api.testing.utils.Resource import com.digitalasset.platform.PlatformApplications import com.digitalasset.platform.apitesting.LedgerFactories.SandboxStore.InMemory import com.digitalasset.platform.damllf.PackageParser import com.digitalasset.platform.sandbox.config.SandboxConfig import com.digitalasset.platform.sandbox.persistence.{PostgresFixture, PostgresResource} import scala.util.control.NonFatal object LedgerFactories { private def packageIdFromString(str: String): Either[Throwable, Ref.PackageId] = Ref.PackageId.fromString(str) match { case Left(e) => Left(new IllegalStateException(e)) case Right(x) => Right(x) } private def getPackageId(path: Path): Either[Throwable, Ref.PackageId] = { val inputStream: InputStream = new BufferedInputStream(new FileInputStream(path.toFile)) try { if (path.toFile.getName.endsWith(".dalf")) { PackageParser.getPackageIdFromDalf(inputStream) } else PackageParser.getPackageIdFromDar(inputStream).flatMap(packageIdFromString) } catch { case NonFatal(t) => throw new RuntimeException(s"Couldn't parse ${path}", t) } } private def getPackageIdOrThrow(path: Path): Ref.PackageId = getPackageId(path).fold(t => throw t, identity) sealed abstract class SandboxStore extends Product with Serializable object SandboxStore { case object InMemory extends SandboxStore case object Postgres extends SandboxStore // meant to be used purely for JMH benchmarks def apply(s: String): SandboxStore = s match { case "InMemory" => SandboxStore.InMemory case "Postgres" => SandboxStore.Postgres } } def createSandboxResource(config: PlatformApplications.Config, store: SandboxStore = InMemory)( implicit esf: ExecutionSequencerFactory): Resource[LedgerContext.SingleChannelContext] = { val packageIds = config.darFiles.map(getPackageIdOrThrow) def createResource(sandboxConfig: SandboxConfig) = SandboxServerResource(sandboxConfig).map { case PlatformChannels(channel) => LedgerContext.SingleChannelContext(channel, config.ledgerId, packageIds) } store match { case SandboxStore.InMemory => createResource(PlatformApplications.sandboxConfig(config, None)) case SandboxStore.Postgres => new Resource[LedgerContext.SingleChannelContext] { @volatile private var postgres: Resource[PostgresFixture] = null @volatile private var sandbox: Resource[LedgerContext.SingleChannelContext] = null override def value(): LedgerContext.SingleChannelContext = sandbox.value override def setup(): Unit = { postgres = PostgresResource() postgres.setup() sandbox = createResource( PlatformApplications.sandboxConfig(config, Some(postgres.value.jdbcUrl))) sandbox.setup() } override def close(): Unit = { sandbox.close() postgres.close() sandbox = null postgres = null } } } } }
gaborh-da/daml
daml-lf/data/src/test/scala/com/digitalasset/daml/lf/data/RefTest.scala
// Copyright (c) 2019 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.digitalasset.daml.lf.data import com.digitalasset.daml.lf.data.Ref.{DottedName, PackageId, Party, QualifiedName} import org.scalatest.{FreeSpec, Matchers} class RefTest extends FreeSpec with Matchers { "DottedName" - { "rejects bad segments" - { "digit at the start" in { DottedName.fromString("9test") shouldBe 'left } "bad symbols" in { DottedName.fromString("test%") shouldBe 'left DottedName.fromString("test-") shouldBe 'left DottedName.fromString("test@") shouldBe 'left } "unicode" in { DottedName.fromString("à") shouldBe 'left DottedName.fromString("ਊ") shouldBe 'left } "colon" in { DottedName.fromString("foo:bar") shouldBe 'left } } "rejects empty segments" in { DottedName.fromString(".") shouldBe 'left DottedName.fromString(".foo.") shouldBe 'left DottedName.fromString(".foo") shouldBe 'left DottedName.fromString("foo.") shouldBe 'left DottedName.fromString("foo..bar") shouldBe 'left } "accepts good segments" - { "dollar" in { DottedName .fromString("$.$blAH9.foo$bar.baz$") .getOrElse(sys.error("expect right found left")) .segments shouldBe ImmArray("$", "$blAH9", "foo$bar", "baz$") } "underscore" in { DottedName .fromString("_._blAH9.foo_bar.baz_") .getOrElse(sys.error("expect right found left")) .segments shouldBe ImmArray("_", "_blAH9", "foo_bar", "baz_") } } } "QualifiedName" - { "rejects no colon" in { QualifiedName.fromString("foo") shouldBe 'left } "rejects multiple colons" in { QualifiedName.fromString("foo:bar:baz") shouldBe 'left } "rejects empty dotted names" in { QualifiedName.fromString(":bar") shouldBe 'left QualifiedName.fromString("bar:") shouldBe 'left } } "Party and PackageId" - { val simpleChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_ " "accepts simple characters" in { for (c <- simpleChars) { Party.fromString(s"the character $c is simple") shouldBe 'right PackageId.fromString(s"the character $c is simple") shouldBe 'right } } "rejects the empty string" in { Party.fromString("") shouldBe 'left PackageId.fromString("") shouldBe 'left } "rejects non simple US-ASCII characters" in { for (c <- '\u0001' to '\u007f' if !simpleChars.contains(c)) { Party.fromString(s"the US-ASCII character $c is not simple") shouldBe 'left PackageId.fromString(s"the US-ASCII character $c is not simple") shouldBe 'left } } "rejects no US-ASCII characters" in { for (c <- '\u0080' to '\u00ff') { Party.fromString(s"the character $c is not US-ASCII") shouldBe 'left PackageId.fromString(s"the character $c is not US-ASCII") shouldBe 'left } for (s <- List( "español", "東京", "Λ (τ : ⋆) (σ: ⋆ → ⋆). λ (e : ∀ (α : ⋆). σ α) → (( e @τ ))" )) { Party.fromString(s) shouldBe 'left PackageId.fromString(s) shouldBe 'left } } } }
gaborh-da/daml
ledger/sandbox/src/main/scala/com/digitalasset/platform/sandbox/SandboxMain.scala
<reponame>gaborh-da/daml // Copyright (c) 2019 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.digitalasset.platform.sandbox import java.util.concurrent.atomic.AtomicBoolean import com.digitalasset.platform.sandbox.cli.Cli import org.slf4j.LoggerFactory import scala.util.control.NonFatal object SandboxMain extends App { private val logger = LoggerFactory.getLogger(this.getClass) private lazy val sandboxServer: SandboxServer = Cli.parse(args).fold(sys.exit(1))(config => SandboxServer(config)) private val closed = new AtomicBoolean(false) private def closeServer(): Unit = { if (closed.compareAndSet(false, true)) sandboxServer.close() } try { Runtime.getRuntime.addShutdownHook(new Thread(() => closeServer())) sandboxServer } catch { case NonFatal(t) => { logger.error("Shutting down Sandbox application because of initialization error", t) closeServer() } } }
gaborh-da/daml
ledger/sandbox/src/main/scala/com/digitalasset/ledger/server/LedgerApiServer/ApiServices.scala
// Copyright (c) 2019 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.digitalasset.ledger.server.LedgerApiServer import akka.stream.ActorMaterializer import com.digitalasset.api.util.TimeProvider import com.digitalasset.daml.lf.data.Ref import com.digitalasset.daml.lf.engine.{Engine, EngineInfo} import com.digitalasset.grpc.adapter.ExecutionSequencerFactory import com.digitalasset.ledger.api.v1.command_completion_service.CompletionEndRequest import com.digitalasset.ledger.api.v1.ledger_configuration_service.LedgerConfiguration import com.digitalasset.ledger.backend.api.v1.LedgerBackend import com.digitalasset.ledger.client.services.commands.CommandSubmissionFlow import com.digitalasset.platform.api.grpc.GrpcApiUtil import com.digitalasset.platform.sandbox.config.{SandboxConfig, SandboxContext} import com.digitalasset.platform.sandbox.services._ import com.digitalasset.platform.sandbox.services.transaction.SandboxTransactionService import com.digitalasset.platform.sandbox.stores.ledger.CommandExecutorImpl import com.digitalasset.platform.server.api.validation.IdentifierResolver import com.digitalasset.platform.server.services.command.ReferenceCommandService import com.digitalasset.platform.server.services.identity.LedgerIdentityServiceImpl import com.digitalasset.platform.server.services.testing.{ReferenceTimeService, TimeServiceBackend} import com.digitalasset.platform.services.time.TimeProviderType import io.grpc.BindableService import io.grpc.protobuf.services.ProtoReflectionService import org.slf4j.LoggerFactory import scala.collection.immutable import scala.concurrent.{ExecutionContext, Future} trait ApiServices extends AutoCloseable { val services: Iterable[BindableService] def withServices(otherServices: immutable.Seq[BindableService]): ApiServices } private case class ApiServicesBundle(services: immutable.Seq[BindableService]) extends ApiServices { override def close(): Unit = services.foreach { case closeable: AutoCloseable => closeable.close() case _ => () } override def withServices(otherServices: immutable.Seq[BindableService]): ApiServices = copy(services = services.++:(otherServices)) } object ApiServices { private val logger = LoggerFactory.getLogger(this.getClass) def create( config: SandboxConfig, ledgerBackend: LedgerBackend, engine: Engine, timeProvider: TimeProvider, optTimeServiceBackend: Option[TimeServiceBackend])( implicit mat: ActorMaterializer, esf: ExecutionSequencerFactory): ApiServices = { implicit val ec: ExecutionContext = mat.system.dispatcher val context = SandboxContext.fromConfig(config) val packageResolver = (pkgId: Ref.PackageId) => Future.successful(context.packageContainer.getPackage(pkgId)) val identifierResolver: IdentifierResolver = new IdentifierResolver(packageResolver) val submissionService = SandboxSubmissionService.createApiService( context.packageContainer, identifierResolver, ledgerBackend, config.timeModel, timeProvider, new CommandExecutorImpl(engine, context.packageContainer) ) logger.info(EngineInfo.show) val transactionService = SandboxTransactionService.createApiService(ledgerBackend, identifierResolver) val identityService = LedgerIdentityServiceImpl(ledgerBackend.ledgerId) val packageService = SandboxPackageService(context.sandboxTemplateStore, ledgerBackend.ledgerId) val configurationService = LedgerConfigurationServiceImpl( LedgerConfiguration( Some(GrpcApiUtil.durationToProto(config.timeModel.minTtl)), Some(GrpcApiUtil.durationToProto(config.timeModel.maxTtl))), ledgerBackend.ledgerId ) val completionService = SandboxCommandCompletionService(ledgerBackend) val commandService = ReferenceCommandService( ReferenceCommandService.Configuration( ledgerBackend.ledgerId, config.commandConfig.inputBufferSize, config.commandConfig.maxParallelSubmissions, config.commandConfig.maxCommandsInFlight, config.commandConfig.limitMaxCommandsInFlight, config.commandConfig.historySize, config.commandConfig.retentionPeriod, config.commandConfig.commandTtl ), // Using local services skips the gRPC layer, improving performance. ReferenceCommandService.LowLevelCommandServiceAccess.LocalServices( CommandSubmissionFlow( submissionService.submit, config.commandConfig.maxParallelSubmissions), r => completionService.service .asInstanceOf[SandboxCommandCompletionService] .completionStreamSource(r), () => completionService.completionEnd(CompletionEndRequest(ledgerBackend.ledgerId)), transactionService.getTransactionById, transactionService.getFlatTransactionById ) ) val activeContractsService = SandboxActiveContractsService(ledgerBackend, identifierResolver) val reflectionService = ProtoReflectionService.newInstance() val timeServiceOpt = optTimeServiceBackend.map { tsb => ReferenceTimeService( ledgerBackend.ledgerId, tsb, config.timeProviderType == TimeProviderType.StaticAllowBackwards ) } new ApiServicesBundle( timeServiceOpt.toList ::: List( identityService, packageService, configurationService, submissionService, transactionService, completionService, commandService, activeContractsService, reflectionService )) } }
gaborh-da/daml
ledger/ledger-api-integration-tests/src/test/itsuite/scala/com/digitalasset/platform/tests/integration/ledger/api/PackageServiceIT.scala
<reponame>gaborh-da/daml // Copyright (c) 2019 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.digitalasset.platform.tests.integration.ledger.api import java.util.UUID import com.digitalasset.ledger.api.testing.utils.{ AkkaBeforeAndAfterAll, IsStatusException, SuiteResourceManagementAroundAll } import com.digitalasset.ledger.api.v1.package_service.PackageServiceGrpc.PackageService import com.digitalasset.ledger.api.v1.package_service.PackageStatus import com.digitalasset.ledger.client.services.pkg.PackageClient import com.digitalasset.platform.apitesting.MultiLedgerFixture import io.grpc.Status import org.scalatest.concurrent.AsyncTimeLimitedTests import org.scalatest.time.Span import org.scalatest.time.SpanSugar._ import org.scalatest.{AsyncWordSpec, Matchers, OptionValues} @SuppressWarnings(Array("org.wartremover.warts.Any")) class PackageServiceIT extends AsyncWordSpec with MultiLedgerFixture with AkkaBeforeAndAfterAll with SuiteResourceManagementAroundAll with AsyncTimeLimitedTests with Matchers with OptionValues { override def timeLimit: Span = 5.seconds private def client(stub: PackageService): PackageClient = { client(stub, config.assertStaticLedgerId) } private def client(stub: PackageService, ledgerId: String): PackageClient = { new PackageClient(ledgerId, stub) } private def getARegisteredPackageId(stub: PackageService) = client(stub).listPackages().map(_.packageIds.headOption.value) "Package Service" when { "asked for the list of registered packages" should { "return it" in allFixtures { context => client(context.packageService).listPackages() map { _.packageIds.size shouldEqual 3 // package, stdlib, daml-prim } } "fail with the expected status on a ledger Id mismatch" in allFixtures { context => client(context.packageService, "not " + config.assertStaticLedgerId) .listPackages() .failed map { IsStatusException(Status.NOT_FOUND)(_) } } } "asked to get a package" should { "return it if it's registered" in allFixtures { context => getARegisteredPackageId(context.packageService) .flatMap(client(context.packageService).getPackage(_)) map { _.archivePayload.size() should be > 0 } } "return a NOT_FOUND error if it's not registered" in allFixtures { context => client(context.packageService).getPackage(UUID.randomUUID().toString).failed map { IsStatusException(Status.NOT_FOUND)(_) } } "fail with the expected status on a ledger Id mismatch" in allFixtures { context => getARegisteredPackageId(context.packageService) .flatMap( client(context.packageService, "not " + config.assertStaticLedgerId) .getPackage(_) .failed) map { IsStatusException(Status.NOT_FOUND)(_) } } } "asked to check a package's status" should { "return true if it's registered" in allFixtures { context => getARegisteredPackageId(context.packageService) .flatMap(client(context.packageService).getPackageStatus(_)) map { _.packageStatus shouldEqual PackageStatus.REGISTERED } } "return false if it's not registered" in allFixtures { context => client(context.packageService).getPackageStatus(UUID.randomUUID().toString) map { _.packageStatus shouldEqual PackageStatus.UNKNOWN } } "fail with the expected status on a ledger Id mismatch" in allFixtures { context => getARegisteredPackageId(context.packageService) .flatMap( client(context.packageService, "not " + config.assertStaticLedgerId) .getPackageStatus(_) .failed) map { IsStatusException(Status.NOT_FOUND)(_) } } } } override protected def config: Config = Config.default }
gaborh-da/daml
ledger/ledger-api-integration-tests/src/test/lib/scala/com/digitalasset/platform/apitesting/MultiLedgerFixture.scala
<filename>ledger/ledger-api-integration-tests/src/test/lib/scala/com/digitalasset/platform/apitesting/MultiLedgerFixture.scala // Copyright (c) 2019 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.digitalasset.platform.apitesting import com.digitalasset.ledger.api.testing.utils.Resource import com.digitalasset.platform.PlatformApplications import com.digitalasset.platform.apitesting.LedgerFactories.SandboxStore import com.digitalasset.platform.esf.TestExecutionSequencerFactory import com.digitalasset.platform.testing.{LedgerBackend, MultiResourceBase} import org.scalatest.AsyncTestSuite trait MultiLedgerFixture extends MultiResourceBase[LedgerBackend, LedgerContext] with TestExecutionSequencerFactory { self: AsyncTestSuite => protected type Config = PlatformApplications.Config protected def Config: PlatformApplications.Config.type = PlatformApplications.Config protected def config: Config protected def basePort = 6865 /** Overriding this provides an easy way to narrow down testing to a single implementation. */ override protected def fixtureIdsEnabled: Set[LedgerBackend] = Set(LedgerBackend.SandboxInMemory, LedgerBackend.SandboxSql) override protected def constructResource( index: Int, fixtureId: LedgerBackend): Resource[LedgerContext] = { fixtureId match { case LedgerBackend.SandboxInMemory => LedgerFactories.createSandboxResource(config, SandboxStore.InMemory) case LedgerBackend.SandboxSql => LedgerFactories.createSandboxResource(config, SandboxStore.Postgres) } } }
gaborh-da/daml
ledger/ledger-api-common/src/main/scala/com/digitalasset/platform/api/v1/event/EventOps.scala
// Copyright (c) 2019 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.digitalasset.platform.api.v1.event import com.digitalasset.ledger.api.domain.{ContractId, EventId} import com.digitalasset.ledger.api.v1.event.Event.Event.{Archived, Created, Empty} import com.digitalasset.ledger.api.v1.event.{CreatedEvent, Event, ExercisedEvent} import com.digitalasset.ledger.api.v1.transaction.TreeEvent import com.digitalasset.ledger.api.v1.transaction.TreeEvent.Kind.{ Created => TreeCreated, Exercised => TreeExercised } import scalaz.Tag import scalaz.syntax.tag._ object EventOps { private val eventIndexFromIdRegex = """.*[-:](\d+)$""".r implicit class EventOps(val event: Event) extends AnyVal { def eventIndex: Int = event.event.eventIndex def eventId: EventId = event.event.eventId def witnesses: Seq[String] = event.event.witnesses def contractId: ContractId = event.event.contractId def templateId: String = event.event.templateId def withWitnesses(witnesses: Seq[String]): Event = Event(event.event.withWitnesses(witnesses)) } implicit class EventEventOps(val event: Event.Event) extends AnyVal { def eventIndex: Int = getEventIndex(event.event.eventId.unwrap) def eventId: EventId = event match { case Archived(value) => EventId(value.eventId) case Created(value) => EventId(value.eventId) case Empty => throw new IllegalArgumentException("Cannot extract Event ID from Empty event.") } def witnesses: Seq[String] = event match { case c: Created => c.value.witnessParties case a: Archived => a.value.witnessParties case Empty => Seq.empty } def templateId: String = event match { case c: Created => c.templateId case a: Archived => a.templateId case Empty => throw new IllegalArgumentException("Cannot extract Template ID from Empty event.") } def contractId: ContractId = event match { case Archived(value) => ContractId(value.contractId) case Created(value) => ContractId(value.contractId) case Empty => throw new IllegalArgumentException("Cannot extract contractId from Empty event.") } def withWitnesses(witnesses: Seq[String]): Event.Event = event match { case c: Created => Created(c.value.copy(witnessParties = witnesses)) case a: Archived => Archived(a.value.copy(witnessParties = witnesses)) case Empty => Empty } } def getEventIndex(eventId: String): Int = { eventIndexFromIdRegex .findFirstMatchIn(eventId) .fold { throw new IllegalArgumentException( s"Event ID $eventId does not match regex $eventIndexFromIdRegex") } { _.group(1).toInt } } implicit class TreeEventKindOps(kind: TreeEvent.Kind) { def fold[T](exerciseHandler: ExercisedEvent => T, createHandler: CreatedEvent => T) = kind match { case e: TreeExercised => exerciseHandler(e.value) case c: TreeCreated => createHandler(c.value) case tk => throw new IllegalArgumentException(s"Unknown TreeEvent type: $tk") } } implicit class TreeEventOps(val event: TreeEvent) { def eventId: EventId = event.kind.fold(e => EventId(e.eventId), c => EventId(c.eventId)) def children: Seq[EventId] = event.kind.fold(e => Tag.subst(e.childEventIds), _ => Nil) def witnessParties: Seq[String] = event.kind.fold(_.witnessParties, _.witnessParties) } }