<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nicu Ciobanu on Medium]]></title>
        <description><![CDATA[Stories by Nicu Ciobanu on Medium]]></description>
        <link>https://medium.com/@ciobanunicu.boris?source=rss-174367a9cbcc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RHGdu5ZUnxGH9xolqLG6sg.jpeg</url>
            <title>Stories by Nicu Ciobanu on Medium</title>
            <link>https://medium.com/@ciobanunicu.boris?source=rss-174367a9cbcc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 07:29:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ciobanunicu.boris/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Scala Chess Game]]></title>
            <link>https://medium.com/@ciobanunicu.boris/scala-chess-game-fd15796ec56b?source=rss-174367a9cbcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd15796ec56b</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[chess-game]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[Nicu Ciobanu]]></dc:creator>
            <pubDate>Fri, 28 Mar 2025 20:05:02 GMT</pubDate>
            <atom:updated>2025-03-28T20:05:02.559Z</atom:updated>
            <content:encoded><![CDATA[<p>♟️ <strong>A chess game application written in Scala</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qio6Gkmrv22xBbhW661oGg.jpeg" /></figure><p>At one of the companies I once applied to, I was given a take-home exercise requiring me to create a chess game program. 🤔 I found it an enjoyable task, which made me review the computer science course I took in high school. 👨‍🏫</p><p>The goal was to create a simple, easy-to-understand application in the shortest possible time.</p><p>This application will be a starting point from which you can make valuable improvements to your solution.</p><p><strong>Requirements:</strong></p><p>- The board should start in the standard chess starting state with all 16 pieces for each player;<br>- Play starts with player 1 (white), and each valid move alternates with the other player. On an invalid move, the existing player stays in control;<br>- All moves must have a piece on the starting square and either an opponent piece or nothing on the destination square. Anything else is invalid;<br>- Validate the move according to the moves allowed by the piece on the starting square:<br>◦ The <em>king</em> can move only 1 square, but in any direction;<br>◦ The <em>bishop</em> can move any number of squares but only diagonally;<br>◦ The <em>rook</em> can move any number of squares, but only horizontally or vertically;<br>◦ The <em>queen</em> can move any number of squares horizontally, vertically, or<br>diagonally;<br>◦ The <em>knight</em> can move in an L shape with sides of 2 and 1 squares<br>respectively. That is eight different possible moves. Unlike other pieces, it jumps over other pieces;<br>◦ The <em>pawn</em> can move one or two squares forward on its first move (when not taking an opponent’s piece);<br>◦ The <em>pawn</em> can move one square forward on subsequent moves (when not taking an opponent’s piece);<br>◦ The <em>pawn</em> can move one square forward diagonally if taking an opponent’s piece.<br>- After each successful move, render the board in simple ASCII form. It is suggested that player one is represented by upper-case characters and player two by lower-case characters. The conventional characters to use here are: Rook(R), Knight(N), Bishop(B), King(K), Queen(Q), Pawn(P). Lower-case characters will be the black and upper-case characters will be the white pieces;<br>- If the destination square contains an opponent piece, that piece is removed from the board unless that piece is a King, in which case the rules around check apply;<br>- Disallow the move for pieces other than the <em>knight</em> if any other pieces are between the start and end square;<br>- If a move ends with a player’s king under attack, that is “check”;<br>- A player cannot end their move in check;<br>- If a player starts their move in check, this should be displayed as “in check”.</p><p><strong>Implementation</strong>:</p><p>I started by creating chess pieces and case classes with the parameter “<em>c”</em>, representing the piece&#39;s color, which can be <em>white</em> or <em>black</em>.</p><p>The <em>symbol</em> method will hardcode the chess piece symbol, which can be <em>R</em>, N, <em>B,</em> <em>Q</em>, <em>K, </em>or <em>P.</em> In our case, it will be <em>B</em>.</p><pre>case class Bishop(c: Char) extends Piece { def symbol: Char = BishopSymbol }</pre><p>You can change the piece parameter to a type class and do the same thing with hardcoded values ​​from the symbol method. I chose the first option, which seemed faster to me. Or maybe I’m lazy 😳.</p><pre>sealed trait ChessColor {<br>  def color: Char = this match {<br>    case White =&gt; &#39;W&#39;<br>    case Black =&gt; &#39;B&#39;<br>  }<br>}<br>case object White extends ChessColor<br>case object Black extends ChessColor</pre><p>I repeated this step for each chess piece.</p><pre>case class King(c: Char) extends Piece { def symbol: Char = KingSymbol }<br><br>case class Knight(c: Char) extends Piece { def symbol: Char = KnightSymbol }<br><br>case class Pawn(c: Char) extends Piece { def symbol: Char = PawnSymbol }<br><br>case class Queen(c: Char) extends Piece { def symbol: Char = QueenSymbol }<br><br>case class Rook(c: Char) extends Piece { def symbol: Char = RookSymbol }</pre><p>The next step was to consider what the chessboard would look like and how to represent it. I chose a two-dimensional array, a matrix with eight rows and eight columns.</p><pre>type Board = Array[Array[Option[Piece]]]</pre><p>The squares on the chessboard should be of the optional type, on which chess pieces can be located or which can be empty (None).</p><pre>  def initBoard(): Board = {<br>    val board = Array.ofDim[Option[Piece]](8, 8)<br><br>    // Place white pieces (uppercase) at the bottom (rows 0-1)<br>    board(0)(0) = Some(Rook(White))   // a1<br>    board(0)(1) = Some(Knight(White)) // b1<br>    board(0)(2) = Some(Bishop(White)) // c1<br>    board(0)(3) = Some(Queen(White))  // d1<br>    board(0)(4) = Some(King(White))   // e1<br>    board(0)(5) = Some(Bishop(White)) // f1<br>    board(0)(6) = Some(Knight(White)) // g1<br>    board(0)(7) = Some(Rook(White))   // h1<br>    for (i &lt;- 0 until 8) board(1)(i) = Some(Pawn(White)) // a2-h2<br><br>    // Place black pieces (lowercase) at the top (rows 6-7)<br>    board(7)(0) = Some(Rook(Black))   // a8<br>    board(7)(1) = Some(Knight(Black)) // b8<br>    board(7)(2) = Some(Bishop(Black)) // c8<br>    board(7)(3) = Some(Queen(Black))  // d8<br>    board(7)(4) = Some(King(Black))   // e8<br>    board(7)(5) = Some(Bishop(Black)) // f8<br>    board(7)(6) = Some(Knight(Black)) // g8<br>    board(7)(7) = Some(Rook(Black))   // h8<br>    for (i &lt;- 0 until 8) board(6)(i) = Some(Pawn(Black)) // a7-h7<br><br>    // Fill the rest of the board with empty squares<br>    for {<br>      i &lt;- 2 until 6<br>      j &lt;- 0 until 8<br>    } board(i)(j) = None<br><br>    board<br>  }</pre><p>The <strong><em>initBoard</em></strong> method will initialize our chessboard, where the chess pieces will be placed in the initial position. White pieces will be represented in uppercase characters, and black pieces will be represented in lowercase characters.</p><p>We have the chessboard with the initialization method, and the chess pieces, and we need to validate the positions for each chess piece.</p><p>Validation methods will be added to the companion objects.</p><pre>object Bishop {<br><br>  // We check up to the second last position<br>  def isValidBishopMove(board: Board, from: (Int, Int), to: (Int, Int)): Boolean = {<br>    val (x1, y1) = from<br>    val (x2, y2) = to<br><br>    // Bishop moves diagonally<br>    if (Math.abs(x2 - x1) == Math.abs(y2 - y1)) {<br>      val stepX = if (x2 &gt; x1) 1 else -1<br>      val stepY = if (y2 &gt; y1) 1 else -1<br><br>      checkBishopMove(startX = x1 + stepX, startY = y1 + stepY, stopX = x2, stopY = y2, stepX = stepX, stepY = stepY, board = board)<br>    } else<br>      false<br>  }<br><br>  @tailrec<br>  private def checkBishopMove(startX: Int, startY: Int, stopX: Int, stopY: Int, stepX: Int, stepY: Int, board: Board): Boolean =<br>    if (startX == stopX &amp;&amp; startY == stopY) true<br>    else if (board(startX)(startY).isDefined) false<br>    else checkBishopMove(startX + stepX, startY + stepY, stopX, stopY, stepX, stepY, board)<br>}</pre><p>In short, each move has a starting and final position. The method ensures that we can move from the starting point to the final point without a piece of the same color or an opposing piece on our path.</p><p>The same principle will be applied to each piece.</p><pre>object King {<br><br>  def isValidKingMove(from: (Int, Int), to: (Int, Int)): Boolean = {<br>    val (x1, y1) = from<br>    val (x2, y2) = to<br><br>    // King moves one square in any direction<br>    Math.abs(x2 - x1) &lt;= 1 &amp;&amp; Math.abs(y2 - y1) &lt;= 1<br>  }<br>}</pre><pre>object Knight {<br><br>  def isValidKnightMove(from: (Int, Int), to: (Int, Int)): Boolean = {<br>    val (x1, y1) = from<br>    val (x2, y2) = to<br><br>    // Knight moves in an L-shape<br>    val dx = Math.abs(x2 - x1)<br>    val dy = Math.abs(y2 - y1)<br><br>    (dx == 2 &amp;&amp; dy == 1) || (dx == 1 &amp;&amp; dy == 2)<br>  }<br>}</pre><pre>object Pawn {<br><br>  def isValidPawnMove(board: Board, pawn: Pawn, from: (Int, Int), to: (Int, Int)): Boolean = {<br>    val (x1, y1) = from<br>    val (x2, y2) = to<br><br>    val direction            = if (pawn.color == White) 1 else -1<br>    val initialStartPosition = if (pawn.color == White) 1 else 6<br>    // When pawn moves two squares, check if there is no piece<br>    val squaresAreEmpty = (board(x1 + direction)(y1), board(x2)(y2)) match {<br>      case (None, None) =&gt; true<br>      case _            =&gt; false<br>    }<br>    val isVerticalDirection = y1 == y2<br><br>    if (isVerticalDirection) {<br>      if (x2 == x1 + direction &amp;&amp; board(x2)(y2).isEmpty) true<br>      // Moving vertically two squares<br>      else if (x2 == x1 + 2 * direction &amp;&amp; x1 == initialStartPosition &amp;&amp; squaresAreEmpty) true<br>      else false<br>    } else {<br>      if (Math.abs(y2 - y1) == 1 &amp;&amp; x2 == x1 + direction) board(x2)(y2).exists(_.color != pawn.color)<br>      else false<br>    }<br>  }<br>}</pre><pre>object Queen {<br><br>  def isValidQueenMove(<br>      board: Board,<br>      from: (Int, Int),<br>      to: (Int, Int),<br>      isValidRookMove: (Board, (Int, Int), (Int, Int)) =&gt; Boolean,<br>      isValidBishopMove: (Board, (Int, Int), (Int, Int)) =&gt; Boolean<br>  ): Boolean =<br>    // Queen can move like a rook or a bishop<br>    isValidRookMove.apply(board, from, to) || isValidBishopMove.apply(board, from, to)<br>}</pre><pre>object Rook {<br><br>  // Implement move validation for each piece type, we check up to the second last position<br>  def isValidRookMove(board: Board, from: (Int, Int), to: (Int, Int)): Boolean = {<br>    val (x1, y1) = from<br>    val (x2, y2) = to<br><br>    // Rook moves horizontally or vertically<br>    if (x1 == x2) {<br>      // Horizontal move<br>      val step = if (y2 &gt; y1) 1 else -1<br><br>      checkHorizontalRookMove(start = y1 + step, stop = y2, step = step, board = board, x = x2)<br><br>    } else if (y1 == y2) {<br>      // Vertical move<br>      val step = if (x2 &gt; x1) 1 else -1<br><br>      checkVerticalRookMove(start = x1 + step, stop = x2, step = step, board = board, y = y2)<br>    } else<br>      false<br>  }<br><br>  @tailrec<br>  private def checkHorizontalRookMove(start: Int, stop: Int, step: Int, board: Board, x: Int): Boolean =<br>    if (start == stop) true<br>    else if (board(x)(start).isDefined) false<br>    else checkHorizontalRookMove(start + step, stop, step, board, x)<br><br>  @tailrec<br>  private def checkVerticalRookMove(start: Int, stop: Int, step: Int, board: Board, y: Int): Boolean =<br>    if (start == stop) true<br>    else if (board(start)(y).isDefined) false<br>    else checkVerticalRookMove(start + step, stop, step, board, y)<br>}</pre><p>We have validated each piece’s move. Now, we will create a function that receives as parameters the chessboard, the initial position, and the final position of the piece we want to move.</p><p>We will use pattern matching to identify the piece in the starting position and the validation method from the previously created companion object.</p><p>All previously created validation methods, except for the Pawn, will check the path to the penultimate square, to the stopping position, which means we still need to check if there is an opposing piece on the last position that we can attack and occupy its position, or check if the square is empty.</p><pre>  def validateMove(board: Board, from: (Int, Int), to: (Int, Int)): Boolean = {<br>    val (x1, y1) = from<br>    val (x2, y2) = to<br><br>    // Check if the starting square has a piece<br>    board(x1)(y1) match {<br>      case None        =&gt; false<br>      case Some(piece) =&gt;<br>        // Check if the destination square is either empty or has an opponent&#39;s piece<br>        val destinationSquare                       = board(x2)(y2)<br>        val isOpponentPiece                         = destinationSquare.exists(_.color != piece.color)<br>        val isEmptyDestinationSquare                = destinationSquare.isEmpty<br>        val isEmptyDestinationSquareOrOpponentPiece = isOpponentPiece || isEmptyDestinationSquare<br><br>        // Validate the move based on the piece type<br>        piece match {<br>          case Rook(_)   =&gt; Rook.isValidRookMove(board, from, to) &amp;&amp; isEmptyDestinationSquareOrOpponentPiece<br>          case Knight(_) =&gt; Knight.isValidKnightMove(from, to) &amp;&amp; isEmptyDestinationSquareOrOpponentPiece<br>          case Bishop(_) =&gt; Bishop.isValidBishopMove(board, from, to) &amp;&amp; isEmptyDestinationSquareOrOpponentPiece<br>          case Queen(_) =&gt;<br>            Queen.isValidQueenMove(<br>              board,<br>              from,<br>              to,<br>              Rook.isValidRookMove,<br>              Bishop.isValidBishopMove<br>            ) &amp;&amp; isEmptyDestinationSquareOrOpponentPiece<br>          case King(_)        =&gt; King.isValidKingMove(from, to) &amp;&amp; isEmptyDestinationSquareOrOpponentPiece<br>          case pawn @ Pawn(_) =&gt; Pawn.isValidPawnMove(board, pawn, from, to) &amp;&amp; isEmptyDestinationSquareOrOpponentPiece<br>        }<br>    }<br>  }</pre><p>Check the <em>ChessLogicSpec</em> class to ensure the method works correctly. There, you can find the unit tests associated with the <strong><em>validateMove</em></strong> method and comments to help you better understand them.</p><p>Next, we will create the method for updating the chessboard with the new positions made by the pieces. It will only be used after we call validateMove, the previously created function.</p><pre>  def movePiece(board: Board, from: (Int, Int), to: (Int, Int)): Board = {<br>    val (x1, y1) = from<br>    val (x2, y2) = to<br><br>    board(x1)(y1) match {<br>      case Some(piece) =&gt;<br>        board(x2)(y2) = Some(piece)<br>        board(x1)(y1) = None<br>        board<br><br>      case _ =&gt; board<br>    }<br>  }</pre><p>We know we must display the message <em>check</em> when the opponent’s king is under attack or <em>checkmate</em> when we capture it ♟️🏁.</p><pre>  def findPiece(board: Board, piece: Piece): Option[(Int, Int)] = {<br>    @tailrec<br>    def parseAndFind(board: Board, piece: Piece, i: Int, j: Int, n: Int): Option[(Int, Int)] = {<br>      if (board(i)(j) == Some(piece)) Some((i, j))<br>      else if (j &lt; n - 1) parseAndFind(board, piece, i, j + 1, n)<br>      else if (i &lt; n - 1) parseAndFind(board, piece, i + 1, 0, n)<br>      else None<br>    }<br><br>    parseAndFind(board, piece, 0, 0, board.length)<br>  }<br><br><br>  def isPieceUnderAttack(board: Board, square: (Int, Int), opponentColor: Char): Boolean = {<br>    @tailrec<br>    def parseAndCheck(i: Int, j: Int, n: Int, board: Board, square: (Int, Int), color: Char): Boolean =<br>      if (validateMove(board = board, from = (i, j), to = square) &amp;&amp; isSamePieceColor(i, j, board, color)) true<br>      else if (j &lt; n - 1) parseAndCheck(i, j + 1, n, board, square, color)<br>      else if (i &lt; n - 1) parseAndCheck(i + 1, 0, n, board, square, color)<br>      else false<br><br>    parseAndCheck(i = 0, j = 0, n = board.length, board = board, square = square, color = opponentColor)<br>  }<br><br><br>  private def isSamePieceColor(x: Int, y: Int, board: Board, color: Char): Boolean =<br>    board(x)(y) match {<br>      case Some(piece) if piece.color == color =&gt; true<br>      case _                                   =&gt; false<br>    }</pre><p>The <strong><em>findPiece</em></strong> method will receive the chessboard and the chess piece we are looking for as parameters and return its position if it exists.</p><p>The <strong><em>isPieceUnderAttack</em></strong> function returns true if the current player can attack the piece at the position it receives as a parameter, or false if everything is fine. In our case, we will use this method to check if the opposite king is under attack.</p><p>We have almost all the methods created, so we can move on to creating our application.</p><pre>object ChessApp extends App {<br><br>  startGame(board = initBoard(), currentPlayer = White)<br><br>  private def startGame(board: Board, currentPlayer: Char): Unit = {<br>    val whitePlayerStr = &quot;1 (White)&quot;<br>    val blackPlayerStr = &quot;2 (Black)&quot;<br><br>    @tailrec<br>    def play(board: Board, currentPlayer: Char, isKingUnderAttack: Boolean, player: String): Unit = {<br>      // Draw the pieces on the chessboard<br>      println(renderBoard(board))<br><br>      val whiteKingPositionOpt = findPiece(board, King(White))<br>      val blackKingPositionOpt = findPiece(board, King(Black))<br><br>      // Game will continue only when both kins are on the chessboard<br>      if (whiteKingPositionOpt.isEmpty || blackKingPositionOpt.isEmpty) {<br>        // Checkmate - game is over<br>        println(s&quot;Checkmate - game is over, user &#39;$player&#39; won.&quot;)<br>      } else {<br>        // Print message to enter coordinates<br>        val updatedPlayer = printEnterMovesMsg(<br>          currentPlayer = currentPlayer,<br>          isKingUnderAttack = isKingUnderAttack,<br>          whitePlayerStr = whitePlayerStr,<br>          blackPlayerStr = blackPlayerStr<br>        )<br><br>        // Add moves from console<br>        enterMoves() match {<br>          case (Some((x1, y1)), Some((x2, y2))) =&gt;<br>            if (validateMove(board, (x1, y1), (x2, y2))) {<br>              // Identify opponent&#39;s color<br>              val opponentPlayerColor = if (currentPlayer == White) Black else White<br><br>              // Update board<br>              val updatedBoard = movePiece(board, (x1, y1), (x2, y2))<br><br>              val isOppKingUnderAttack =<br>                printAndCheckIfOpponentKingUnderAttack(updatedBoard, whiteKingPositionOpt, blackKingPositionOpt, opponentPlayerColor)<br><br>              play(<br>                board = updatedBoard,<br>                currentPlayer = opponentPlayerColor,<br>                isKingUnderAttack = isOppKingUnderAttack,<br>                player = updatedPlayer<br>              )<br>            } else {<br>              println(&quot;Invalid move. Please try again.&quot;)<br>              play(board = board, currentPlayer = currentPlayer, isKingUnderAttack = false, player = player)<br>            }<br><br>          case _ =&gt;<br>            play(board = board, currentPlayer = currentPlayer, isKingUnderAttack = false, player = player)<br>        }<br>      }<br>    }<br><br>    play(board = board, currentPlayer = currentPlayer, isKingUnderAttack = false, player = whitePlayerStr)<br>  }<br><br><br>  private def printAndCheckIfOpponentKingUnderAttack(<br>      board: Board,<br>      whiteKingPositionOpt: Option[(Int, Int)],<br>      blackKingPositionOpt: Option[(Int, Int)],<br>      opponentPlayerColor: Char<br>  ): Boolean =<br>    (whiteKingPositionOpt, blackKingPositionOpt) match {<br>      case (Some((wx1, wy1)), Some((bx1, by2))) =&gt;<br>        if (isPieceUnderAttack(board, (wx1, wy1), opponentPlayerColor)) {<br>          println(&quot;Check&quot;)<br>          true<br>        } else if (isPieceUnderAttack(board, (bx1, by2), opponentPlayerColor)) {<br>          println(&quot;Check&quot;)<br>          true<br>        } else false<br><br>      case _ =&gt; false<br>    }<br><br><br>  private def printEnterMovesMsg(<br>      currentPlayer: Char,<br>      isKingUnderAttack: Boolean,<br>      whitePlayerStr: String,<br>      blackPlayerStr: String<br>  ): String = {<br>    val player = if (currentPlayer == White) whitePlayerStr else blackPlayerStr<br><br>    if (isKingUnderAttack) {<br>      println(s&quot;In check!!! \nPlayer, $player enter your move (e.g., &#39;e2 e4&#39;):&quot;)<br>      player<br>    } else {<br>      println(s&quot;Player, $player enter your move (e.g., &#39;e2 e4&#39;):&quot;)<br>      player<br>    }<br>  }<br><br><br>  private def enterMoves(): (Option[(Int, Int)], Option[(Int, Int)]) = {<br>    val movementCoordinates = scala.io.StdIn.readLine().split(&quot; &quot;)<br><br>    if (movementCoordinates.length != 2) {<br>      println(&quot;Invalid input. Please enter two squares separated by a space.&quot;)<br>      (None, None)<br>    } else (parseSquare(movementCoordinates(0)), parseSquare(movementCoordinates(1)))<br>  }<br>}</pre><p>Let’s not forget about <strong><em>parseSquare</em></strong>, which will receive chars from the console representing the chessboard positions and return the chess pieces’ starting and final positions.</p><pre>  def parseSquare(square: String): Option[(Int, Int)] = {<br>    val x = 8 - square(1).asDigit   // array line position<br>    val y = square(0).toLower - &#39;a&#39; // array column position<br><br>    if (square.length != 2) None<br>    else if (x &gt;= 0 &amp;&amp; x &lt; 8 &amp;&amp; y &gt;= 0 &amp;&amp; y &lt; 8) Some((x, y))<br>    else None<br>  }</pre><p>In the test classes, you will find several test cases with comments to help us understand the cases.</p><p>Instructions for starting the application can be detailed in the <strong><em>README.md </em></strong>file.</p><p>One improvement would be to refactor the <strong><em>isPieceUnderAttack</em></strong> method so that you don’t have to go through the entire matrix every time until you find out if the king is in danger of attack.</p><p>In the <a href="https://github.com/nicuciobanu/scala-chess-application">code</a>, you will also find documentation for each method.</p><p>👋 Thank you for your attention, I hope the application will be helpful to you!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd15796ec56b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Akka-Streams processing with Redis]]></title>
            <link>https://medium.com/@ciobanunicu.boris/akka-streams-processing-with-redis-bb210598fa64?source=rss-174367a9cbcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb210598fa64</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[inmemory-cache]]></category>
            <category><![CDATA[akka-streams]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Nicu Ciobanu]]></dc:creator>
            <pubDate>Fri, 28 Feb 2025 13:24:48 GMT</pubDate>
            <atom:updated>2025-02-28T13:24:48.696Z</atom:updated>
            <content:encoded><![CDATA[<p>Processing of multiple streams with in-memory cache</p><p><a href="https://github.com/nicuciobanu/stream-processor-demo/tree/main">GitHub Repository</a></p><p><strong>Why Akka-Streams?</strong></p><p>Akka Streams is a powerful tool for building scalable, resilient, and efficient stream processing systems. Its support for backpressure, asynchronous processing, and composability makes it an excellent choice for modern, reactive applications. Whether dealing with high-throughput data or building complex processing pipelines.</p><p>Due to the benefits specified above, many companies use these technologies, so I wanted to build a solution for a real problem I had with one of my clients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*6PQWuumGCpmAiHSgvRURPw.jpeg" /></figure><p><strong>The problem:</strong></p><p>Our company creates charging stations for electric vehicles and deals with several data types, like charging<em> </em>and battery<em> </em>data 🔋⚡.</p><p>For that, we need to write a program that consumes those two sources of data, <em>charging data</em> (<em>timestamp</em>, <em>socketId</em>, <em>vehicleId</em>, and <em>powerInWatts</em>) and <em>battery data</em> (<em>timestamp</em>, <em>vehicleId</em>, and <em>stateOfChargeInPercent</em>). Then, they are combined and produce <em>output data</em> (<em>timestamp</em>, <em>socketId</em>, <em>vehicleId</em>, <em>powerInWatts</em>, and <em>stateOfChargeInPercent</em>).</p><p>Only emit output when charging data arrives. The output should be the last received timestamp for the same vehicle ID.</p><p><strong>The solution:</strong></p><p>To process data sources, we will use Akka-Streams. Our output will be built from battery and charging data with the exact vehicle ID.</p><p>We know the output should only be created when the charging data arrives, so we should save the battery data somewhere to compare it with the charging data. Here, we will use the Redis in-memory cache.</p><p>But what do we do if the battery data and charging data arrive simultaneously, or the charging data comes first and we didn’t cache the vehicle ID and timestamp from the battery data 🤯 ? We could apply a few seconds delay to the charging data stream to ensure that battery data is cached before charging data arrives.</p><p><strong>Model creation:</strong></p><pre>import spray.json.{DefaultJsonProtocol, JsonFormat}<br><br>sealed trait ChargingBattery<br>case class ChargingData(timestamp: String, socketId: String, vehicleId: String, powerInWatts: Int) extends ChargingBattery<br>case class BatteryData(timestamp: String, vehicleId: String, stateOfChargeInPercent: Int) extends ChargingBattery<br><br>case class OutputData(timestamp: String, socketId: String, vehicleId: String, powerInWatts: Int, stateOfChargeInPercent: Int)<br><br>object OutputData extends DefaultJsonProtocol {<br>  implicit val outputDataFormat: JsonFormat[OutputData] = jsonFormat5(OutputData.apply)<br>}</pre><p><strong>Service creation:</strong></p><p>Before we add our stream processing logic, we need to add the imports to be available to use Akka-Streams with the Redis client.</p><pre>...<br><br>val akkaVersion      = &quot;2.6.20&quot;<br>val fs2Version       = &quot;3.7.0&quot;<br>val scalaTestVersion = &quot;3.2.17&quot;<br>val mockitoVersion   = &quot;1.17.27&quot;<br><br>libraryDependencies ++= Seq(<br>  &quot;com.typesafe.akka&quot; %% &quot;akka-stream&quot;         % akkaVersion,<br>  &quot;redis.clients&quot;     %  &quot;jedis&quot;               % &quot;4.3.1&quot;,<br>  &quot;io.spray&quot;          %% &quot;spray-json&quot;          % &quot;1.3.6&quot;,<br>  // test libraries<br>  &quot;com.typesafe.akka&quot; %% &quot;akka-stream-testkit&quot; % akkaVersion % Test,<br>  &quot;org.scalatest&quot;     %% &quot;scalatest&quot;           % scalaTestVersion % Test,<br>  &quot;com.dimafeng&quot;      %% &quot;testcontainers-scala-scalatest&quot; % &quot;0.41.5&quot; % Test,<br>  &quot;com.dimafeng&quot;      %% &quot;testcontainers-scala-redis&quot; % &quot;0.41.5&quot; % Test,<br>)</pre><p>Now, we need to create our service. As I said above, we already know that battery data will arrive first; they must be saved in the cache and then matched with charging data, resulting in a delay.</p><p>We will save the<em> OutputData </em>as a value in our stor<em>e. </em>As for the key, we will use<em> vehicleId</em>, which only has data from battery data, <em>timestamp</em>, <em>vehicleId,</em> and <em>stateOfChargeInPercent.</em></p><pre>// imports<br><br><br>case class ChargingBatteryService(jedis: Jedis) {<br>  def process(chargingSource: Source[ChargingData, NotUsed], batterySource: Source[BatteryData, NotUsed]): Source[OutputData, NotUsed] = {<br>    // Combine the two sources into a single stream<br>    val combinedSource: Source[ChargingBattery, NotUsed] =<br>      Source<br>        .combine(chargingSource.delay(Charging_Source_Delay), batterySource)(Merge(_))<br>        .buffer(Buffer_Size, OverflowStrategy.dropHead)<br><br>    // Process the combined stream<br>    combinedSource<br>      .mapAsync(1)(data =&gt; updateLocalCache(jedis, data))<br>      .collect {<br>        case outputData: OutputData<br>            if outputData.socketId.nonEmpty &amp;&amp; outputData.powerInWatts != 0 &amp;&amp; outputData.stateOfChargeInPercent &gt; 0 =&gt;<br>          outputData<br>      }<br>  }<br><br>  private def updateLocalCache(jedis: Jedis, chargingBatteryData: ChargingBattery): Future[OutputData] =<br>    chargingBatteryData match {<br>      case chargingData: ChargingData =&gt;<br>        // Use timestamp as redis key<br>        val key         = chargingData.vehicleId<br>        val cachedValue = jedis.get(key)<br><br>        if (cachedValue != null) {<br>          // Key exists: Update the cached OutputData with ChargingData<br>          val combinedData = cachedValue.parseJson.convertTo[OutputData]<br><br>          val updatedCombinedData = combinedData.copy(<br>            socketId = chargingData.socketId,<br>            powerInWatts = chargingData.powerInWatts<br>          )<br><br>          // Use timestamp as the Redis key<br>          setKeyAndTtl(jedis, key, updatedCombinedData)<br><br>          Future.successful(updatedCombinedData)<br><br>        } else {<br>          // Key does not exist: Create a new OutputData with ChargingData<br>          val newCombinedData = OutputData(<br>            timestamp = chargingData.timestamp,<br>            socketId = chargingData.socketId,<br>            vehicleId = chargingData.vehicleId,<br>            powerInWatts = chargingData.powerInWatts,<br>            stateOfChargeInPercent = 0 // Default value<br>          )<br><br>          // Use timestamp as the Redis key<br>          setKeyAndTtl(jedis, key, newCombinedData)<br><br>          Future.successful(newCombinedData)<br>        }<br><br>      case batteryData: BatteryData =&gt;<br>        val outputData = OutputData(<br>          timestamp = batteryData.timestamp,<br>          socketId = &quot;&quot;,<br>          vehicleId = batteryData.vehicleId,<br>          powerInWatts = 0,<br>          stateOfChargeInPercent = batteryData.stateOfChargeInPercent<br>        )<br><br>        // Use timestamp as the Redis key<br>        setKeyAndTtl(jedis, batteryData.vehicleId, outputData)<br><br>        Future.successful(outputData)<br>    }<br><br>  private def setKeyAndTtl(jedis: Jedis, key: String, outputData: OutputData): Unit = {<br>    jedis.set(key, outputData.toJson.toString)<br>    // Set TTL for the key<br>    jedis.expire(key, Redis_TTL_Seconds)<br>  }<br>}</pre><p>We combined our streams and merged them. Then, we used the buffer with the dropHead strategy, in case our buffer is full, we drop the oldest elements.</p><p>Without a buffer, the entire stream might slow down to match the speed of the slowest component, reducing overall throughput.</p><p>It’s better to work with fixed-size batches because backpressure occurs when a downstream component is slower than the upstream producer. Without a buffer, the entire stream might slow down or block, waiting for the downstream to catch up.</p><p>If backpressure is not handled correctly, the system might run out of memory or other resources due to unbounded buffering.</p><p>We set up a one-hour time to live for redis key, which should be more than enough for our case.</p><p>After we process our streams, we should filter out the OutputData object with default values.</p><p>Testing:</p><p>To test the implementation, run the “<a href="https://github.com/nicuciobanu/stream-processor-demo/blob/main/src/main/scala/stream/demo/ChargingBatteryApp.scala">ChargingBatteryApp</a>” main class. There, we mocked our data and called the “process” method.</p><p>By the way, we should run a Redis docker container as we use an in-memory cache.</p><pre>docker run -d --name redis-stack-server -p 6379:6379 redis/redis-stack-server:latest</pre><p>If you don’t want to test like that, go and run our tests from “<a href="https://github.com/nicuciobanu/stream-processor-demo/blob/main/src/test/scala/stream/demo/ChargingBatteryServiceSpec.scala">ChargingBatteryServiceSpec</a>”.</p><pre>// imports <br><br><br>class ChargingBatteryServiceSpec<br>    extends TestKit(ActorSystem(&quot;ChargingBatteryServiceSpec&quot;))<br>    with AnyWordSpecLike<br>    with Matchers<br>    with ForAllTestContainer<br>    with BeforeAndAfterEach {<br><br>  override val container: RedisContainer = RedisContainer()<br>  var jedis: Jedis                       = _<br><br>  override def beforeEach(): Unit = {<br>    super.beforeEach()<br>    // Initialize the Jedis client with the Redis container&#39;s host and port<br>    jedis = new Jedis(container.containerIpAddress, container.mappedPort(6379))<br>  }<br><br>  override def afterEach(): Unit = {<br>    jedis.close() // Close the Jedis client<br>    super.afterEach()<br>  }<br><br>  &quot;ChargingBatteryService&quot; should {<br>    &quot;combine charging data and battery data into output data and cache&quot; in {<br>      val chargingBatteryService = ChargingBatteryService(jedis)<br>      // Mock data<br>      val chargingSource = Source(<br>        List(<br>          ChargingData(&quot;2023-11-02T17:08:49Z&quot;, &quot;s123&quot;, &quot;v123&quot;, 60),<br>          ChargingData(&quot;2023-11-02T17:09:00Z&quot;, &quot;s456&quot;, &quot;v456&quot;, 70)<br>        )<br>      )<br><br>      val batterySource = Source(<br>        List(<br>          BatteryData(&quot;2023-11-02T17:08:49Z&quot;, &quot;v123&quot;, 51),<br>          BatteryData(&quot;2023-11-02T17:09:00Z&quot;, &quot;v456&quot;, 55)<br>        )<br>      )<br><br>      // Combine the streams<br>      val outputStream = chargingBatteryService.process(chargingSource, batterySource)<br><br>      // Run the stream and collect results<br>      val result        = outputStream.runWith(Sink.seq)<br>      val outputResults = Await.result(result, 7.seconds)<br><br>      // Verify the results<br>      outputResults should contain theSameElementsAs Seq(<br>        OutputData(&quot;2023-11-02T17:08:49Z&quot;, &quot;s123&quot;, &quot;v123&quot;, 60, 51),<br>        OutputData(&quot;2023-11-02T17:09:00Z&quot;, &quot;s456&quot;, &quot;v456&quot;, 70, 55)<br>      )<br><br>      // Verify Redis cache<br>      val cachedValue1 = jedis.get(&quot;v123&quot;)<br>      cachedValue1 should not be null<br><br>      val cachedOutputData1 = cachedValue1.parseJson.convertTo[OutputData]<br>      cachedOutputData1 shouldEqual OutputData(&quot;2023-11-02T17:08:49Z&quot;, &quot;s123&quot;, &quot;v123&quot;, 60, 51)<br><br>      val cachedValue2 = jedis.get(&quot;v456&quot;)<br>      cachedValue2 should not be null<br><br>      val cachedOutputData2 = cachedValue2.parseJson.convertTo[OutputData]<br>      cachedOutputData2 shouldEqual OutputData(&quot;2023-11-02T17:09:00Z&quot;, &quot;s456&quot;, &quot;v456&quot;, 70, 55)<br>    }<br><br>    &quot;cache charging with and battery data and return empty outut&quot; in {<br>      val chargingBatteryService = ChargingBatteryService(jedis)<br>      // Mock data<br>      val chargingSource = Source(<br>        List(<br>          ChargingData(&quot;2023-11-02T17:08:49Z&quot;, &quot;s123&quot;, &quot;v124&quot;, 60),<br>          ChargingData(&quot;2023-11-02T17:09:00Z&quot;, &quot;s456&quot;, &quot;v351&quot;, 70)<br>        )<br>      )<br><br>      val batterySource = Source(<br>        List(<br>          BatteryData(&quot;2023-11-02T17:08:49Z&quot;, &quot;v189&quot;, 51),<br>          BatteryData(&quot;2023-11-02T17:09:00Z&quot;, &quot;v567&quot;, 55)<br>        )<br>      )<br><br>      // Combine the streams<br>      val outputStream = chargingBatteryService.process(chargingSource, batterySource)<br><br>      // Run the stream and collect results<br>      val result        = outputStream.runWith(Sink.seq)<br>      val outputResults = Await.result(result, 7.seconds)<br><br>      // Verify the results<br>      outputResults shouldBe empty<br><br>      // Verify Redis cache<br>      val cachedValue1 = jedis.get(&quot;v124&quot;)<br>      cachedValue1 should not be null<br><br>      val cachedOutputData1 = cachedValue1.parseJson.convertTo[OutputData]<br>      cachedOutputData1 shouldEqual OutputData(&quot;2023-11-02T17:08:49Z&quot;, &quot;s123&quot;, &quot;v124&quot;, 60, 0)<br><br>      val cachedValue2 = jedis.get(&quot;v351&quot;)<br>      cachedValue2 should not be null<br><br>      val cachedOutputData2 = cachedValue2.parseJson.convertTo[OutputData]<br>      cachedOutputData2 shouldEqual OutputData(&quot;2023-11-02T17:09:00Z&quot;, &quot;s456&quot;, &quot;v351&quot;, 70, 0)<br><br>      val cachedValue3 = jedis.get(&quot;v189&quot;)<br>      cachedValue3 should not be null<br><br>      val cachedOutputData3 = cachedValue3.parseJson.convertTo[OutputData]<br>      cachedOutputData3 shouldEqual OutputData(&quot;2023-11-02T17:08:49Z&quot;, &quot;&quot;, &quot;v189&quot;, 0, 51)<br><br>      val cachedValue4 = jedis.get(&quot;v567&quot;)<br>      cachedValue4 should not be null<br><br>      val cachedOutputData4 = cachedValue4.parseJson.convertTo[OutputData]<br>      cachedOutputData4 shouldEqual OutputData(&quot;2023-11-02T17:09:00Z&quot;, &quot;&quot;, &quot;v567&quot;, 0, 55)<br>    }<br>  }<br>}</pre><p>Well done, folks. I wish you happy coding!</p><h4>Reference:</h4><ul><li><a href="https://doc.akka.io/libraries/akka-core/current/stream/operators/Source/combine.html">https://doc.akka.io/libraries/akka-core/current/stream/operators/Source/combine.html</a></li><li><a href="https://doc.akka.io/libraries/akka-core/current/stream/operators/Source-or-Flow/merge.html">https://doc.akka.io/libraries/akka-core/current/stream/operators/Source-or-Flow/merge.html</a></li><li><a href="https://github.com/redis/jedis">https://github.com/redis/jedis</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb210598fa64" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integration of Sprig Boot with Kafka and MySQL]]></title>
            <link>https://medium.com/@ciobanunicu.boris/integration-of-sprig-boot-with-kafka-and-mysql-b81313f37019?source=rss-174367a9cbcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/b81313f37019</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Nicu Ciobanu]]></dc:creator>
            <pubDate>Thu, 27 Feb 2025 21:48:36 GMT</pubDate>
            <atom:updated>2025-02-27T21:48:36.083Z</atom:updated>
            <content:encoded><![CDATA[<h4>Online Courses: Java Application with Kafka, Spring Boot, and MySQL</h4><p><a href="https://github.com/nicuciobanu/online-courses-app">GitHub Repository</a></p><p>In this article, we will build a <em>Java</em> application with <em>Spring Boot</em>, <em>Kafka</em>, and <em>MySQL</em>.</p><p>The application should allow us to register instructors with instructor details and courses. Each course can have multiple students, and a student can be subscribed to various classes. The student must be available to leave reviews.</p><p>API routes must be role-restricted, meaning that delete operations are performed by users with the “ADMIN” role, and create and update operations must be performed by users with the “MANAGER” and “ADMIN” roles. Users with the “EMPLOYEE” role can only access the view action for the instructor, student, and the other entities mentioned above. The actions of create, update, and delete must be sent to a Kafka topic, which will be used to develop the metrics/statistics dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*hQlXAGLkIEfgXjYS_FaSWg.jpeg" /></figure><p><strong>Technologies</strong>: Java, Spring Boot(Hibernate, JPA, REST, Security), MySQL, Postman, Kafka, and Docker.</p><p>To avoid struggling too much, the Spring team offers us the opportunity to initialize our Java project online at `<a href="https://start.spring.io/%60">https://start.spring.io/`</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7HT_xbSkry6nG1gWMhF5IA.jpeg" /></figure><p>There’s no need to write anything by hand, everything can be done faster than we thought.</p><p>If you want to implement the project step by step, choose the options above.</p><p><em>Spring Web - we use to build our API routes; <br>Spring Data JPA — will help us to query the DB;<br>Spring Security — is used secure our routes;<br>MySQL Driver — will be used to connect to our DB;<br>Spring Boot DevTools - helps us add changes to the app while we are running it;<br>Spring for Apache Kafka — gives the libraries to access Kafka.</em></p><p><strong>Setting up the DB:</strong></p><p>Go to the MySQL Workbench and log in to the root with the password you selected at the installation.<br> Go to “File” -&gt; Open SQL script, then select and execute the “001-create-mysql-user.sql” script.<br>After that, add a new connection with the “mysql” user and “mysql” password, and run the “002-create-online-courses-schema.sql” and “003-create-users-and-roles.sql” files.</p><p>The files are in “src/main/resources/db.migrations”</p><p><strong>Setting up the config:</strong></p><p>Add the database connection details to the “application.properties” file.</p><pre>spring.datasource.url=jdbc:mysql://localhost:3306/online-courses<br>spring.datasource.username=mysql<br>spring.datasource.password=mysql</pre><p><strong>Creating entities:</strong></p><p>Create entities for online courses.</p><pre><br>// imports<br><br>@Entity<br>@Table(name = &quot;course&quot;)<br>public class Course {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    @Column(name = &quot;id&quot;)<br>    private int id;<br><br>    @Column(name = &quot;title&quot;)<br>    private String title;<br><br>    @ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH, CascadeType.REFRESH})<br>    @JoinColumn(name=&quot;instructor_id&quot;)<br>    private Instructor instructor;<br><br>    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)<br>    @JoinColumn(name = &quot;course_id&quot;)<br>    private List&lt;Review&gt; reviews;<br><br>    @ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH})<br>    @JoinTable(name = &quot;course_student&quot;, joinColumns = @JoinColumn(name = &quot;course_id&quot;), inverseJoinColumns = @JoinColumn(name = &quot;student_id&quot;))<br>    private List&lt;Student&gt; students;<br><br>    public Course() {}<br><br>    public Course(String title) {<br>        this.title = title;<br>    }<br>    <br>    public void addReview(Review theReview) {<br>        if(reviews == null) {<br>            reviews = new ArrayList&lt;&gt;();<br>        }<br><br>        reviews.add(theReview);<br>    }<br><br>    public void addStudent(Student theStudent) {<br>        if(students == null) {<br>            students = new ArrayList&lt;&gt;();<br>        }<br><br>        students.add(theStudent);<br>    }<br><br>// Getters and Setters</pre><p>You will find the other classes in the “<a href="https://github.com/nicuciobanu/online-courses-app/tree/main/src/main/java/com/online_courses/entity">entity</a>” package.</p><p>You don’t need to add the “id” column when you create new entities. The value will be generated automatically. Use the “id” column only when you do an update.</p><pre>// create request - no id filed<br><br>curl --location &#39;localhost:8080/api/courses/instructors&#39; \<br>--header &#39;Content-Type: application/json&#39; \<br>--header &#39;Authorization: Basic Yn....&#39; \<br>--header &#39;Cookie: JSESSIONID=ECD18EEA68EC531C3D6CA239AA5D3A6B&#39; \<br>--data-raw &#39;{<br>    &quot;firstName&quot;: &quot;John&quot;,<br>    &quot;lastName&quot;: &quot;Smith&quot;,<br>    &quot;email&quot;: &quot;johns@gmail.com&quot;<br>}&#39;</pre><pre>// update request - use the id field with value of specific object<br><br>curl --location --request PUT &#39;localhost:8080/api/courses/instructors&#39; \<br>--header &#39;Content-Type: application/json&#39; \<br>--header &#39;Authorization: Basic c3...&#39; \<br>--header &#39;Cookie: JSESSIONID=ECD18EEA68EC531C3D6CA239AA5D3A6B&#39; \<br>--data-raw &#39;{<br>    &quot;id&quot;: 2,<br>    &quot;firstName&quot;: &quot;Timothy&quot;,<br>    &quot;lastName&quot;: &quot;Patterson&quot;,<br>    &quot;email&quot;: &quot;timp@gmail.com&quot;<br>}&#39;</pre><p>Find all the get, create, update, and remove requests for the project in the <a href="https://github.com/nicuciobanu/online-courses-app/blob/main/README.md">“README.md”</a> file.</p><p><strong>Note</strong>: respect the relationships between tables(<em>one-to-one</em>, <em>one-to-many</em>, <em>many-to-one</em>, …).</p><p><strong>DAO Layer:</strong></p><p>We will create an interface for each entity to interact with the databases. It is recommended that the DAO levels be separated. In my case, I made a single interface, which is “<a href="https://github.com/nicuciobanu/online-courses-app/blob/main/src/main/java/com/online_courses/dao/OnlineCoursesDAO.java">OnlineCoursesDAO</a>”. If you wish, you can create one interface for each table.</p><pre>// imports<br><br>public interface OnlineCoursesDAO {<br>    void saveInstructor(Instructor instructor);<br>    List&lt;Instructor&gt; findAllInstructors();<br>    Instructor findInstructorById(int id);<br>    Instructor describeInstructorById(int id);<br>    Instructor updateInstructor(Instructor instructor);<br>    void removeInstructorById(int id);<br>...<br>}</pre><p>In order to query our tables, we need the Repository class “<a href="https://github.com/nicuciobanu/online-courses-app/blob/main/src/main/java/com/online_courses/dao/OnlineCoursesDAOImpl.java">OnlineCoursesDAOImpl</a>”, where we will implement the methods from “OnlineCoursesDAO”.</p><pre><br>// imports<br><br>@Repository<br>public class OnlineCoursesDAOImpl implements OnlineCoursesDAO {<br><br>    private EntityManager entityManager;<br><br>    @Autowired<br>    public OnlineCoursesDAOImpl(EntityManager entityManager) {<br>        this.entityManager = entityManager;<br>    }<br><br>    @Override<br>    @Transactional<br>    public void saveInstructor(Instructor instructor) {<br>        entityManager.persist(instructor);<br>    }<br><br>    @Override<br>    public Instructor findInstructorById(int id) {<br>        return entityManager.find(Instructor.class, id);<br>    }<br><br>    @Override<br>    public List&lt;Instructor&gt; findAllInstructors() {<br>        TypedQuery&lt;Instructor&gt; query = entityManager.createQuery(&quot;FROM Instructor&quot;, Instructor.class);<br>        List&lt;Instructor&gt; instructors = query.getResultList();<br><br>        return instructors;<br>    }<br><br>    @Override<br>    public Instructor describeInstructorById(int id) {<br>        TypedQuery&lt;Instructor&gt; query = entityManager.createQuery(<br>                &quot;SELECT i FROM Instructor i &quot;<br>                        + &quot;JOIN FETCH i.courses &quot;<br>                        + &quot;JOIN FETCH i.instructorDetail &quot;<br>                        + &quot;WHERE i.id = :data&quot;, Instructor.class<br>        );<br><br>        query.setParameter(&quot;data&quot;, id);<br><br>        Instructor instructor = query.getSingleResult();<br><br>        return instructor;<br>    }<br><br>    @Override<br>    @Transactional<br>    public Instructor updateInstructor(Instructor instructor) {<br>        return entityManager.merge(instructor);<br>    }<br><br>// the remaining implementations ...<br><br>}</pre><p>Don’t forget to add “<a href="http://twitter.com/Transactional">@Transactional</a>” to the methods that will perform table manipulations.</p><p><strong>Business layer:</strong></p><p>It is a good practice that communications between routes in the controller and the DAO layer will be carried out through an additional layer, which is “<a href="https://github.com/nicuciobanu/online-courses-app/blob/main/src/main/java/com/online_courses/service/OnlineCourseService.java">OnlineCourseService</a>”.</p><pre><br>// imports<br><br><br>public interface OnlineCourseService {<br>    void createInstructor(Instructor instructor);<br>    List&lt;Instructor&gt; getAllInstructors();<br>    Instructor getInstructorById(int id);<br>    Instructor updateInstructor(Instructor instructor);<br>    void deleteInstructorById(int id);<br>...<br>}</pre><p>Let’s also add the “@Service” implementation.</p><pre><br>// imports<br><br><br>@Service<br>public class OnlineCourseServiceImpl implements OnlineCourseService {<br>    private final OnlineCoursesDAO onlineCoursesDAO;<br><br>    @Autowired<br>    public OnlineCourseServiceImpl(OnlineCoursesDAO onlineCoursesDAO) {<br>        this.onlineCoursesDAO = onlineCoursesDAO;<br>    }<br><br>    @Override<br>    public void createInstructor(Instructor instructor) {<br>        onlineCoursesDAO.saveInstructor(instructor);<br>    }<br><br>    @Override<br>    public List&lt;Instructor&gt; getAllInstructors() {<br>        return onlineCoursesDAO.findAllInstructors();<br>    }<br><br>    @Override<br>    public Instructor getInstructorById(int id) {<br>        return onlineCoursesDAO.findInstructorById(id);<br>    }<br><br>    @Override<br>    public Instructor updateInstructor(Instructor instructor) {<br>        return onlineCoursesDAO.updateInstructor(instructor);<br>    }<br><br>    @Override<br>    public void deleteInstructorById(int id) {<br>        onlineCoursesDAO.removeInstructorById(id);<br>    }<br><br>// the remaining implementations ...<br><br>}</pre><p><strong>REST layer</strong>:</p><p>Here, we will build our routes that will allow us to create, update, get, and delete objects from our database.</p><pre><br>// imports<br><br><br>@RestController<br>@RequestMapping(&quot;/api&quot;)<br>public class OnlineCourseRestController {<br>    private final OnlineCourseService onlineCourseService;<br><br>    public OnlineCourseRestController(OnlineCourseService onlineCourseService) {<br>        this.onlineCourseService = onlineCourseService;<br>    }<br><br>    /**<br>     * GET /api/courses/instructors<br>     * */<br>    @GetMapping(&quot;/courses/instructors&quot;)<br>    public List&lt;Instructor&gt; getAllInstructors() {<br>        return onlineCourseService.getAllInstructors();<br>    }<br><br>    /**<br>     * GET /api/courses/instructors/{id}<br>     * */<br>    @GetMapping(&quot;/courses/instructors/{id}&quot;)<br>    public Instructor getInstructorById(@PathVariable int id) {<br>        Instructor instructor = onlineCourseService.getInstructorById(id);<br><br>        if(instructor == null) {<br>            throw new NotFoundException(&quot;Instructor id not found - &quot; + id);<br>        }<br><br>        return instructor;<br>    }<br><br>    /**<br>     * POST /api/courses/instructors<br>     * */<br>    @PostMapping(&quot;/courses/instructors&quot;)<br>    public void createInstructor(@RequestBody Instructor instructorToStore) {<br>      onlineCourseService.createInstructor(instructorToStore);<br>    }<br><br>    /**<br>     * PUT /api/courses/instructors<br>     * */<br>    @PutMapping(&quot;/courses/instructors&quot;)<br>    public void updateInstructor(@RequestBody Instructor instructorToUpdate) {<br>       onlineCourseService.updateInstructor(instructorToUpdate);<br>    }<br><br>    /**<br>     * DELETE /courses/instructors/{id}<br>     * */<br>    @DeleteMapping(&quot;/courses/instructors/{id}&quot;)<br>    public void deleteInstructor(@PathVariable int id) {<br>        Instructor instructor = onlineCourseService.getInstructorById(id);<br><br>        if(instructor == null) {<br>            throw new UnexpectedException(&quot;Non-existent instructor id - &quot; + id);<br>        }<br><br>        onlineCourseService.deleteInstructorById(id);<br>    }<br><br>// the remaining implementations ...<br><br>}</pre><p>At each step, you must test each route from “<a href="https://github.com/nicuciobanu/online-courses-app/blob/main/src/main/java/com/online_courses/rest/OnlineCourseRestController.java">OnlineCourseRestController</a>”, I used Postman.</p><p><strong>Security layer:</strong></p><p>In the security layer, we need to configure our routes, calling the routes must be restricted to specific roles such as “ADMIN”, “MANAGER”, or “EMPLOYEE”.</p><p>Our users will be added to the “users” table and the roles to the “authorities” table. The default password is pswd12345, use the bcrypt algorithm before saving the password in the table.</p><p>A generation tool is available at: <a href="https://www.luv2code.com/generate-bcrypt-password">https://www.luv2code.com/generate-bcrypt-password</a></p><p>Let’s follow the code from the “<a href="https://github.com/nicuciobanu/online-courses-app/blob/main/src/main/java/com/online_courses/security/SecurityConfig.java">SecurityConfig</a>” class.</p><p><strong>Note</strong>: make sure you use the correct username and password to make Postman calls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X6JO663ZpQK-HWhX8dYIzg.jpeg" /></figure><p>To find the unit tests for instructor routes, go to “<a href="https://github.com/nicuciobanu/online-courses-app/blob/main/src/test/java/com/online_courses/controller/OnlineCourseRestControllerTest.java">OnlineCourseRestControllerTest</a>”.</p><p>Goooooood, if you’ve made it this far, you should be proud of yourself, a large part of the project has been done.</p><p><strong>Second part- the Kafka integration:</strong></p><p>We will save the “CREATE”, “UPDATE”, and “DELETE” actions in Kafka with the affected objects.</p><p>For this reason, we created “<a href="https://github.com/nicuciobanu/online-courses-app/blob/main/src/main/java/com/online_courses/kafka/model/OnlineCourseEvent.java">OnlineCourseEvent</a>” with two fields, the action of creation, refresh or delete, and the affected object.</p><pre><br>public class OnlineCourseEvent&lt;T&gt; implements ObjectType&lt;T&gt; {<br>    private ActionType action;<br>    private T object;<br><br>    public OnlineCourseEvent() {}<br><br>// constructors, setters and getters<br>}</pre><p>Next is the configuration of the Kafka producer. Add the bootstrap server and topic name in the “<a href="https://github.com/nicuciobanu/online-courses-app/blob/main/src/main/resources/application.properties">application.properties</a>” file.</p><pre>spring.kafka.producer.bootstrap-servers=localhost:9092<br>spring.kafka.producer.topic=online-courses-events</pre><p>Let’s implement the Kafka config.</p><pre><br>// imports<br><br>@Configuration<br>public class KafkaProducerConfig {<br><br>    @Value(&quot;${spring.kafka.producer.bootstrap-servers}&quot;)<br>    private String bootstrapAddress;<br><br>    @Bean<br>    public ProducerFactory&lt;String, OnlineCourseEvent&gt; producerFactory() {<br><br>        Map&lt;String, Object&gt; configProps = new HashMap&lt;&gt;();<br><br>        configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress);<br>        configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);<br>        configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class);<br><br>        return new DefaultKafkaProducerFactory&lt;&gt;(configProps);<br>    }<br><br>    @Bean<br>    public KafkaTemplate&lt;String, OnlineCourseEvent&gt; kafkaTemplate() {<br>        return new KafkaTemplate&lt;&gt;(producerFactory());<br>    }<br> }</pre><p><strong>Note</strong>: make sure that the “bootstrapAddress” macro value is the same as the one from the “application.properties” file.</p><pre>@Value(&quot;${spring.kafka.producer.bootstrap-servers}&quot;)</pre><p>We need to add “<a href="https://github.com/nicuciobanu/online-courses-app/blob/main/src/main/java/com/online_courses/kafka/KafkaTopicConfig.java">KafkaTopicConfig</a>”, the Kafka topic configuration.</p><pre><br>// imports<br><br>@Configuration<br>public class KafkaTopicConfig {<br>    @Value(value = &quot;${spring.kafka.producer.bootstrap-servers}&quot;)<br>    private String bootstrapAddress;<br><br>    @Value(value = &quot;${spring.kafka.producer.topic}&quot;)<br>    private String topicName;<br><br>    @Bean<br>    public KafkaAdmin kafkaAdmin() {<br>        Map&lt;String, Object&gt; configs = new HashMap&lt;&gt;();<br><br>        configs.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress);<br><br>        return new KafkaAdmin(configs);<br>    }<br><br>    @Bean<br>    public NewTopic onlineCoursesEventsTopic() {<br>        return new NewTopic(topicName, 2, (short) 2);<br>    }<br>}</pre><p>Now that we have the Kafka configurations, we can add the “<a href="https://github.com/nicuciobanu/online-courses-app/blob/main/src/main/java/com/online_courses/kafka/KafkaProducerService.java">KafkaProducerService</a>” service to send messages to the “online-courses-events” topic.</p><pre>public interface KafkaProducerService&lt;T&gt; {<br>    void sendMessage(T message);<br>}</pre><pre><br>// imports<br><br><br>@Service<br>public class KafkaProducerServiceImpl implements KafkaProducerService&lt;OnlineCourseEvent&gt; {<br>    private final KafkaProducerConfig kafkaProducerConfig;<br>    private final KafkaTopicConfig kafkaTopicConfig;<br><br>    @Autowired<br>    public KafkaProducerServiceImpl(KafkaProducerConfig kafkaProducerConfig, KafkaTopicConfig kafkaTopicConfig) {<br>        this.kafkaProducerConfig = kafkaProducerConfig;<br>        this.kafkaTopicConfig = kafkaTopicConfig;<br>    }<br><br>    @Override<br>    public void sendMessage(OnlineCourseEvent message) {<br>        kafkaProducerConfig.kafkaTemplate().send(kafkaTopicConfig.onlineCoursesEventsTopic().name(), message);<br>    }<br>}</pre><p>In “<a href="https://github.com/nicuciobanu/online-courses-app/blob/main/src/main/java/com/online_courses/kafka/KafkaProducerServiceImpl.java">KafkaProducerServiceImpl</a>” we implement the “sendMessage” method.</p><p>Let’s go back to “OnlineCourseRestController” and send our events to Kafka.</p><pre><br>// imports<br><br>@RestController<br>@RequestMapping(&quot;/api&quot;)<br>public class OnlineCourseRestController {<br>    private final OnlineCourseService onlineCourseService;<br>    private final KafkaProducerService kafkaProducerService;<br><br>    public OnlineCourseRestController(OnlineCourseService onlineCourseService, KafkaProducerService kafkaProducerService) {<br>        this.onlineCourseService = onlineCourseService;<br>        this.kafkaProducerService = kafkaProducerService;<br>    }<br><br>    /**<br>     * GET /api/courses/instructors<br>     * */<br>    @GetMapping(&quot;/courses/instructors&quot;)<br>    public List&lt;Instructor&gt; getAllInstructors() {<br>        return onlineCourseService.getAllInstructors();<br>    }<br><br>    /**<br>     * GET /api/courses/instructors/{id}<br>     * */<br>    @GetMapping(&quot;/courses/instructors/{id}&quot;)<br>    public Instructor getInstructorById(@PathVariable int id) {<br>        Instructor instructor = onlineCourseService.getInstructorById(id);<br><br>        if(instructor == null) {<br>            throw new NotFoundException(&quot;Instructor id not found - &quot; + id);<br>        }<br><br>        return instructor;<br>    }<br><br>    /**<br>     * POST /api/courses/instructors<br>     * */<br>    @PostMapping(&quot;/courses/instructors&quot;)<br>    public void createInstructor(@RequestBody Instructor instructorToStore) {<br>        // send online course create event to kafka topic<br>        sendOnlineCourseEvent(ActionType.CREATE, instructorToStore);<br><br>        onlineCourseService.createInstructor(instructorToStore);<br>    }<br><br>    /**<br>     * PUT /api/courses/instructors<br>     * */<br>    @PutMapping(&quot;/courses/instructors&quot;)<br>    public void updateInstructor(@RequestBody Instructor instructorToUpdate) {<br>        // send online course update event to kafka topic<br>        sendOnlineCourseEvent(ActionType.UPDATE, instructorToUpdate);<br><br>        onlineCourseService.updateInstructor(instructorToUpdate);<br>    }<br><br>    /**<br>     * DELETE /courses/instructors/{id}<br>     * */<br>    @DeleteMapping(&quot;/courses/instructors/{id}&quot;)<br>    public void deleteInstructor(@PathVariable int id) {<br>        Instructor instructor = onlineCourseService.getInstructorById(id);<br><br>        if(instructor == null) {<br>            throw new UnexpectedException(&quot;Non-existent instructor id - &quot; + id);<br>        }<br><br>        // send online course delete event to kafka topic<br>        sendOnlineCourseEvent(ActionType.DELETE, instructor);<br><br>        onlineCourseService.deleteInstructorById(id);<br>    }<br><br>// the remaining implementations ...<br><br>}</pre><p><strong>Testing</strong>:</p><p>Before running the project, don’t forget to run the SQL scripts. Also, run the “<a href="https://github.com/nicuciobanu/online-courses-app/blob/main/docker-compose.yml">docker-compose.yml</a>” file to start a Kafka docker container.</p><pre>Start kafka container:<br><br>- docker compose up<br><br>Create kafka topic:<br><br>- docker-compose exec kafka kafka-topics.sh --create --topic online-courses-events --partitions 1 --replication-factor 1 --bootstrap-server localhost:9092<br><br>Read kafka messages:<br><br>- docker-compose exec kafka kafka-console-consumer.sh --topic online-courses-events --from-beginning --bootstrap-server localhost:9092</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0JaexemB5TE4_mDuibgYVQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yIP7E9xbid8SwZvc23b4sg.jpeg" /></figure><p>In the “README.md” file, you can find all the requests you can play with.</p><p>Thank you for reading this article!!!</p><p><strong>References</strong>:<br>- <a href="https://luv2code.com/">https://luv2code.com/</a><br>- <a href="https://docs.spring.io/spring-kafka/reference/quick-tour.html">https://docs.spring.io/spring-kafka/reference/quick-tour.html</a><br>- <a href="https://spring.io/projects/spring-boot">https://spring.io/projects/spring-boot</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b81313f37019" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scala service combined with PostgreSQL, Flyway, Doobie, Ciris, IO(Cats Effects), Http4s…]]></title>
            <link>https://medium.com/@ciobanunicu.boris/scala-service-combined-with-postgresql-flyway-doobie-ciris-io-cats-effects-http4s-e78d75248118?source=rss-174367a9cbcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/e78d75248118</guid>
            <category><![CDATA[zio-json]]></category>
            <category><![CDATA[flyway]]></category>
            <category><![CDATA[doobie]]></category>
            <category><![CDATA[ciri]]></category>
            <category><![CDATA[http4s]]></category>
            <dc:creator><![CDATA[Nicu Ciobanu]]></dc:creator>
            <pubDate>Mon, 20 May 2024 13:27:21 GMT</pubDate>
            <atom:updated>2024-05-20T13:27:21.557Z</atom:updated>
            <content:encoded><![CDATA[<h3>Scala service combined with PostgreSQL, Flyway, Doobie, Hikari-CP, Ciris, IO(Cats Effects), Http4s, ZIO-JSON, and Cake Pattern.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cVXat21dNsGUEzZo-wm44A.jpeg" /></figure><p>Hello friends, this is my first post on Medium. May God help me do more.</p><p>At the beginning of my career, combining Scala technologies was complicated (and I still encounter difficulties). For this reason, I read many blogs that helped me finish my tasks. Now, I also want to support the generation of developers starting the Scala world.</p><p>We will lay the foundations of an <a href="https://github.com/nicuciobanu/library-management-system">application</a> that manages a library where we will combine Scala with technologies such as PostgreSQL, Flyway, Doobie, Ciris, IO(cats effects), Http4s, ZIO-JSON, and Cake Pattern.</p><h3>Loading Configurations</h3><p>Let’s start by adding the configurations to the <a href="https://github.com/nicuciobanu/library-management-system/blob/main/src/main/resources/application.conf"><em>application.conf</em></a>.</p><pre>app {<br>       api {<br>            port = 8080<br>            port = ${?API_PORT}<br>            host = &quot;localhost&quot;<br>            host = ${?API_HOST}<br>       }<br><br>       database {<br>            url = &quot;jdbc:postgresql://localhost:5432/postgres&quot;<br>            url = ${?DB_URL}<br>            user = &quot;postgres&quot;<br>            user = ${?DB_USER}<br>            password = &quot;postgres&quot;<br>            password = ${?DB_PASSWORD}<br>            max-pool-size = 10<br>            max-pool-size = ${?DB_MAX_POOL_SIZE}<br>            schema = &quot;public&quot;<br>            schema = ${?DB_SCHEMA}<br>          }<br>}</pre><p>To use our configurations, we have to load and materialize them into objects. We will use Ciris for this.</p><p><a href="https://cir.is/docs/quick-example">Ciri</a>s is a functional programming library for loading configurations.</p><p>Let’s add the dependency to the <em>build.sbt</em> file</p><pre>&quot;is.cir&quot;                %% &quot;ciris&quot;       % &quot;3.6.0&quot;</pre><p>After adding the dependency, we can load our configurations.</p><pre>  case class AppConfig(api: Api, database: Database)<br>  case class Api(port: Int, host: String)<br>  case class Database(url: String, user: String, password: String, maxPoolSize: Int, schema: String)</pre><pre><br>trait SettingsComponent {<br><br>  val config: Settings<br><br>  trait Settings {<br>    def appConfig: ConfigValue[Effect, AppConfig] = {<br>      for {<br>        api &lt;- (<br>          env(&quot;API_PORT&quot;).or(prop(&quot;app.api.port&quot;)).as[Int],<br>          env(&quot;API_HOST&quot;).or(prop(&quot;app.api.host&quot;)).as[String],<br>        ).parMapN(Api.apply)<br>        database &lt;- (<br>          env(&quot;DB_URL&quot;).or(prop(&quot;app.database.url&quot;)).as[String],<br>          env(&quot;DB_USER&quot;).or(prop(&quot;app.database.user&quot;)).as[String],<br>          env(&quot;DB_PASSWORD&quot;).or(prop(&quot;app.database.password&quot;)).as[String],<br>          env(&quot;DB_MAX_POOL_SIZE&quot;).or(prop(&quot;app.database.max-pool-size&quot;)).as[Int],<br>          env(&quot;DB_SCHEMA&quot;).or(prop(&quot;app.database.schema&quot;)).as[String]<br>        ).parMapN(Database.apply)<br>      } yield AppConfig(api, database)<br>    }<br>  }<br>}</pre><ul><li>use env and prop to load environment variables and system properties,</li><li>use or with fallback value when values are missing, accumulating errors,</li><li>use combinators like as on values,</li><li>use for yield to load a single value without accumulation of errors,</li><li>use parMapN to combine multiple values with error accumulation.</li></ul><h3><strong>Database Migrations</strong></h3><p>Let’s use Flyway for database version control. Using plain SQL, it offers robust schema evolution across all environments with ease and pleasure.</p><pre>CREATE TABLE IF NOT EXISTS book<br>(<br>    isbn TEXT PRIMARY KEY,<br>    name TEXT NOT NULL,<br>    subject TEXT NOT NULL,<br>    overview TEXT,<br>    publisher TEXT NOT NULL,<br>    publication_date Date NOT NULL,<br>    lang TEXT NOT NULL<br>);</pre><p>Remember, when creating the script name, use the <a href="https://www.red-gate.com/blog/database-devops/flyway-naming-patterns-matter">Flyway naming convention</a> and add the file <em>V0001__init.sq</em>l under the <em>resource/db.migration</em>.</p><p>To be able to run the script, we need to add our dependencies and the code required for migration.</p><pre>    &quot;org.flywaydb&quot;           % &quot;flyway-core&quot; % &quot;10.4.1&quot;,<br>    &quot;org.flywaydb&quot;           % &quot;flyway-database-postgresql&quot; % &quot;10.4.1&quot; % &quot;runtime&quot;</pre><pre><br>trait DbMigrationComponent {<br>  val migration: Migration<br><br>  trait Migration {<br>    def migrate(jdbcUrl: String, user: String, password: String): IO[MigrateResult] =<br>      IO.pure {<br>        Flyway<br>          .configure()<br>          .dataSource(jdbcUrl, user, password)<br>          .load()<br>          .migrate()<br>      }<br><br>  }<br>}</pre><p>Great, so far we have done an outstanding job!!!</p><h3>Database Connection</h3><p>We will interact with our tables using Doobie, a pure functional JDBC layer for Scala and Cats. I like Doobie because it provides a minimal but expressive high-level API.</p><p>We will use Hikari CP to create the database connection pool.</p><pre>    &quot;org.tpolecat&quot; %% &quot;doobie-core&quot;     % &quot;1.0.0-RC4&quot;,<br>    &quot;org.tpolecat&quot; %% &quot;doobie-postgres&quot; % &quot;1.0.0-RC4&quot;,<br>    &quot;org.tpolecat&quot; %% &quot;doobie-hikari&quot;   % &quot;1.0.0-RC4&quot;</pre><pre><br><br>trait DbTransactorComponent {<br>  this: SettingsComponent =&gt;<br>  val transactor: DbTransactor<br><br>  trait DbTransactor {<br>    def init(database: IO[Database]): Resource[IO, Transactor[IO]] =<br>      for {<br>        dbConfig &lt;- database.toResource<br>        hikariConfig &lt;- Resource.pure {<br>          val config = new HikariConfig()<br>          config.setDriverClassName(PostgresDriver)<br>          config.setJdbcUrl(dbConfig.url)<br>          config.setUsername(dbConfig.user)<br>          config.setPassword(dbConfig.password)<br>          config.setMaximumPoolSize(dbConfig.maxPoolSize)<br>          config<br>        }<br>        xa &lt;- HikariTransactor.fromHikariConfig[IO](hikariConfig)<br>      } yield xa<br>  }<br>}</pre><p>Let’s move on to writing the SQL query to add and select our data from the tables.</p><pre>  case class Book(isbn: String,<br>                  name: String,<br>                  subject: String,<br>                  overview: String,<br>                  publisher: String,<br>                  publicationDate: LocalDate,<br>                  lang: Language,<br>  )<br><br>  case class BookItem(barcode: String,<br>                      tag: UUID,<br>                      isbn: String,<br>                      subject: String,<br>                      title: String,<br>                      isReferenceOnly: Boolean,<br>                      lang: Language,<br>                      numberOfPages: Int,<br>                      format: Format,<br>                      borrowed: LocalDate,<br>                      loanPeriod: Int,<br>                      dueDate: LocalDate,<br>                      isOverdue: Boolean,<br>  )</pre><pre>import cats.effect.{IO, Resource}<br>import doobie.Transactor<br>import doobie.implicits._<br>import doobie.postgres.implicits._<br>import MetaMappings._<br>import library.management.system.com.model.Exceptions._<br>import library.management.system.com.model.Models.Book<br><br>trait BookRepositoryComponent {<br><br>  val bookRepository: BookRepository<br>  class BookRepository(resource: Resource[IO, Transactor[IO]]) {<br><br>    def createBook(book: Book): IO[Either[BookCreateError, String]] = {<br>      val createQuery =<br>        sql&quot;&quot;&quot;<br>          INSERT INTO book(<br>            isbn,<br>            name,<br>            subject,<br>            overview,<br>            publisher,<br>            publication_date,<br>            lang<br>          ) VALUES(<br>          ${book.isbn},<br>          ${book.name},<br>          ${book.subject},<br>          ${book.overview},<br>          ${book.publisher},<br>          ${book.publicationDate},<br>          ${book.lang}<br>          )<br>           &quot;&quot;&quot;<br>          .stripMargin<br>          .update<br>          .withUniqueGeneratedKeys[String](&quot;isbn&quot;)<br><br>      resource.use { tr =&gt;<br>        createQuery<br>          .transact(tr)<br>          .attempt<br>          .flatMap {<br>            case Left(value) =&gt;<br>              IO.pure(Left(BookCreateError(s&quot;Errors while creating book ${book.isbn} ${value.getMessage}&quot;)))<br>            case Right(value) =&gt; IO.pure(Right(value))<br>          }<br>      }<br>    }<br><br>    def getBook(isbn: String, subject: String): IO[Either[SearchError, Book]] = {<br>      ...<br>    }<br>}</pre><p>Even if IntelliJ suggests you delete the <em>import `import doobie.postgres.implicits._`</em>, don’t do it because you will get in trouble.</p><p>To make my life easier, I use monads as much as possible in Scala, <em>Either[BookCreateError, String].</em></p><h3>HTTP Interface</h3><p>I will use HTTP4s, a minimal, idiomatic Scala interface for HTTP services built on FS2, to create the routes. This streaming library allows for processing and emitting large payloads in constant space and implementing WebSockets.</p><p>To facilitate the efficient writing of JSON encoders and JSONB decoders, I will use ZIO-JSON.</p><pre>&quot;dev.zio&quot;      %% &quot;zio-json&quot; % &quot;0.6.2&quot;</pre><p>I prefer to add the default JSON encoders and decoders in the companion object to the models.</p><pre><br> case class BookRequest(isbn: String,<br>                         name: String,<br>                         subject: String,<br>                         overview: String,<br>                         publisher: String,<br>                         publicationDate: String,<br>                         lang: String,<br>  )<br><br>  object BookRequest {<br>    implicit val decoder: JsonDecoder[BookRequest] = DeriveJsonDecoder.gen[BookRequest]<br>    implicit val encoder: JsonEncoder[BookRequest] = DeriveJsonEncoder.gen[BookRequest]<br>    implicit def entityEncoder: EntityEncoder[IO, BookRequest] = jsonEncoderOf[IO, BookRequest]<br>  }</pre><pre>trait BookRoutesComponent {<br>  this: BookServiceComponent =&gt;<br><br>  val bookRoutes: BookRoutes<br><br>  trait BookRoutes {<br><br>    def routes: HttpRoutes[IO] = {<br>      val dsl = Http4sDsl[IO]<br>      import dsl._<br><br>      HttpRoutes.of[IO] {<br>        // books<br>        case request @ POST -&gt; Root / &quot;books&quot; =&gt;<br>          for {<br>            reqBody &lt;- request.as[BookRequest]<br>            book = BookRequest.toBook.apply(reqBody)<br>            createResponse &lt;- bookService.createBook(book)<br>            response &lt;- createResponse.fold(err =&gt; BadRequest(err.getMessage), isbn =&gt; Created(isbn.toJson))<br>          } yield response<br><br>        case _ @GET -&gt; Root / &quot;books&quot; / isbn / subject =&gt;<br>          for {<br>            storedBook &lt;- bookService.getBook(isbn, subject)<br>            response &lt;- storedBook.fold(_ =&gt; NotFound(), book =&gt; Ok(book.toJson))<br>          } yield response<br>      }<br>    }<br>  }<br>}</pre><p>As you can see, HTT4S supports Cats Effect IO, a data type for encoding side effects as pure values, capable of expressing synchronous and asynchronous computations.</p><p><em>With IO, you can reason about the results of asynchronous processes. Still, due to its purity and laziness, IO can be thought of as a specification (to be evaluated at the &quot;end of the world&quot;), yielding more control over the evaluation model and being more predictable, for example, when dealing with sequencing vs parallelism, when composing multiple IOs, or when dealing with failure.</em></p><h3>Combine All</h3><pre>object Main<br>    extends IOApp<br>     with SettingsComponent<br>     with DbMigrationComponent<br>     with DbTransactorComponent<br>     with BookRepositoryComponent<br>     with ItemRepositoryComponent<br>     with BookServiceComponent<br>     with BookRoutesComponent {<br><br>  override val config: Settings = new Settings {}<br>  override val migration: Migration = new Migration {}<br>  override val transactor: DbTransactor = new DbTransactor {}<br>  private val dbTransactor = transactor.init(config.appConfig.load[IO].map(_.database))<br>  override val bookRepository: BookRepository = new BookRepository(dbTransactor)<br>  override val itemRepository: ItemRepository = new ItemRepository(dbTransactor)<br>  override val bookService: BookService = new BookService {}<br>  override val bookRoutes: BookRoutes = new BookRoutes {}<br><br>  override def run(args: List[String]): IO[ExitCode] =<br>    for {<br>      appConfig &lt;- config.appConfig.load[IO]<br>      api = appConfig.api<br>      db = appConfig.database<br>      _ &lt;- migration.migrate(db.url, db.user, db.password)<br>      routes = bookRoutes.routes<br>      application: Kleisli[IO, Request[IO], Response[IO]] = Router(<br>        &quot;/api/v1&quot; -&gt; routes,<br>      ).orNotFound<br>      server &lt;- BlazeServerBuilder[IO]<br>        .bindHttp(api.port, api.host)<br>        .withHttpApp(application)<br>        .serve<br>        .compile<br>        .drain<br>        .as(ExitCode.Success)<br>    } yield server<br>}</pre><p>You can find the other components in my <a href="https://github.com/nicuciobanu/library-management-system">GitHub</a> repository.</p><p>If you don’t have CURL installed, I suggest you install a client to send requests to the application. I use Postman.</p><pre>#### Create book:<br>curl --location &#39;http://localhost:8080/api/v1/books&#39; \<br>--header &#39;Content-Type: application/json&#39; \<br>--data &#39;{<br>&quot;isbn&quot;:&quot;6bcbca1e-efd3-411d-9f7c-14b872444fce&quot;,<br>&quot;name&quot;:&quot;Zack Snyder&#39;\&#39;&#39;s Justice League&quot;,<br>&quot;subject&quot;:&quot;Fantasy&quot;,<br>&quot;overview&quot;:&quot;&quot;,<br>&quot;publisher&quot;:&quot;Zack Snyder&quot;,<br>&quot;publicationDate&quot;:&quot;2020-01-08&quot;,<br>&quot;lang&quot;:&quot;English&quot;<br>}&#39;<br><br>### Get book:<br>curl --location &#39;http://localhost:8080/api/v1/books/6bcbca1e-efd3-411d-9f7c-14b872444fce/Fantasy&#39; \<br>--data &#39;&#39;</pre><p>We have reached the end, thank you!!!</p><h3>Reference</h3><ul><li><a href="https://typelevel.org/cats-effect/docs/2.x/datatypes/io">https://typelevel.org/cats-effect/docs/2.x/datatypes/io</a></li><li><a href="https://cir.is/docs/quick-example">https://cir.is/docs/quick-example</a></li><li><a href="https://tpolecat.github.io/doobie/docs/14-Managing-Connections.html">https://tpolecat.github.io/doobie/docs/14-Managing-Connections.html</a></li><li><a href="https://tpolecat.github.io/doobie/">https://tpolecat.github.io/doobie/</a></li><li><a href="https://zio.github.io/zio-json/docs/interop/interop_http4s">https://zio.github.io/zio-json/docs/interop/interop_http4s</a></li><li><a href="https://http4s.org/v0.22/docs/dsl.html">https://http4s.org/v0.22/docs/dsl.html</a></li><li><a href="https://www.baeldung.com/scala/cake-pattern">https://www.baeldung.com/scala/cake-pattern</a></li><li><a href="https://alexn.org/blog/2020/11/15/managing-database-migrations-scala/">https://alexn.org/blog/2020/11/15/managing-database-migrations-scala/</a></li><li><a href="https://blog.rockthejvm.com/doobie/">https://blog.rockthejvm.com/doobie/</a></li><li><a href="https://medium.com/rahasak/hacking-with-http4s-doobie-and-cats-effects-4fc54068ea10">https://medium.com/rahasak/hacking-with-http4s-doobie-and-cats-effects-4fc54068ea10</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e78d75248118" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>