<?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 tech.mia on Medium]]></title>
        <description><![CDATA[Stories by tech.mia on Medium]]></description>
        <link>https://medium.com/@tech.mia?source=rss-62c558d0cfb1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*N0DPbCQ7S_WuqYT0RWaEzw.jpeg</url>
            <title>Stories by tech.mia on Medium</title>
            <link>https://medium.com/@tech.mia?source=rss-62c558d0cfb1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 05:22:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tech.mia/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[From Zero to Service — Retrieving and Storing Data Using Hibernate, MySQL, and Spring Boot]]></title>
            <link>https://medium.com/javarevisited/from-zero-to-service-retrieving-and-storing-data-using-hibernate-mysql-and-spring-boot-46a4dd0be995?source=rss-62c558d0cfb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/46a4dd0be995</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[tech.mia]]></dc:creator>
            <pubDate>Mon, 22 Mar 2021 06:33:14 GMT</pubDate>
            <atom:updated>2021-03-22T06:33:14.954Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Zero to Service — Retrieving and Storing Data Using Hibernate, MySQL, and Spring Boot</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*n9-pR-ibIDLW6k6S" /><figcaption>Photo by <a href="https://unsplash.com/@joshstyle?utm_source=medium&amp;utm_medium=referral">JOSHUA COLEMAN</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In my <a href="https://medium.com/javarevisited/from-zero-to-service-a-guide-on-creating-an-api-using-java-spring-boot-88080b54a597"><strong>first post of<em> Zero to Service</em></strong></a>, we went over how to build an API using Spring Boot. All of the actions of adding items in this first post were done in memory. In this second post, we’ll be going over how to configure your service so that you can now add and retrieve records from a <a href="https://medium.com/javarevisited/top-5-courses-to-learn-mysql-in-2020-4ffada70656f"><em>MySQL database</em></a>.</p><p>For this task, we will be using a popular framework called <a href="https://hibernate.org/"><strong><em>Hibernate</em></strong></a>. Hibernate is an ORM (Object-Relational Mapping) framework that allows you to interact with your database in an Object-Oriented fashion while providing many more tools at your disposal.</p><p>To achieve this task, we will be dividing this task into three parts.</p><ol><li><strong>Service Configuration</strong> — Configure your service so that it connects to your database server.</li><li><strong>Database Mapping</strong> — Create and map your database table in your service.</li><li><strong>Data Storage and Retrieval</strong> — This is the final step. Here we’ll be able to retrieve and store data to/from our table(s).</li></ol><h4>#1 — Service Configuration</h4><p>The first thing you’ll have to do is to update your pom.xml file to include the MySQL connector and <a href="https://medium.com/javarevisited/top-5-hibernate-online-training-courses-for-beginners-and-advance-java-programmers-469460596b2b"><em>Hibernate</em></a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16b50d413c4b21f8105f5f289fd4b007/href">https://medium.com/media/16b50d413c4b21f8105f5f289fd4b007/href</a></iframe><p>After you’ve done this, we will need to create a new class which we’ll name DatabaseConfigBuilder. This class will contain a method that includes the following three items:</p><ol><li>Database connection information, such as credentials, and database server’s address.</li><li>Basic Hibernate configuration.</li><li>Mappings for all your database tables.</li></ol><p>Once you’ve created this class, you’ll need to implement a method, which we’ll name buildConfiguration. This method returns an object of type Configuration. For now, we’ll create a new instance of the Configuration object and returning it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/821e6d98eea342072991d32a16433a21/href">https://medium.com/media/821e6d98eea342072991d32a16433a21/href</a></iframe><p>Let’s begin by configuring our database configuration information. For this, you’ll make a chain of calls to the setProperty method.</p><p>The first call will have a key of Environment.URL as the first parameter to the setProperty method and the value will be a string with the snippet below. This snippet contains the host, port, and database name. Feel free to change these if any of these values are different.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afdea3bc4b8b16e8ae52e6a49b5d9046/href">https://medium.com/media/afdea3bc4b8b16e8ae52e6a49b5d9046/href</a></iframe><p>Next, call setProperty with the Environment.USER and Environment.PASS and pass in the username and password required to connect to your database server.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e4b180139898ba7da9e941a076737b8/href">https://medium.com/media/9e4b180139898ba7da9e941a076737b8/href</a></iframe><p>Once we’ve configured our database connection, we are ready to configure <a href="https://medium.com/javarevisited/top-5-books-to-learn-hibernate-for-java-developers-b2cb4b16ccd6?source=---------14------------------">Hibernate</a> correctly. Let’s go ahead now and configure your buildConfiguration to have the second block of properties you see below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/614a7f7270ffebb5c9797fa62dfb5287/href">https://medium.com/media/614a7f7270ffebb5c9797fa62dfb5287/href</a></iframe><p>Feel free to review what are the correct values for your application on these properties and identify new ones you might need by visiting this page.</p><p><a href="https://docs.jboss.org/hibernate/orm/3.5/reference/en/html/session-configuration.html">Chapter 3. Configuration</a></p><p>The final step in our configuration builder is to map every class that represents a database table. We’ll be doing this in the next section.</p><h4>#2 — Database Mapping</h4><p>In this example, we’ll be creating a table that stores cars. This table will have an idand makecolumns.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad9933099ef4ded0030fa236f735fa73/href">https://medium.com/media/ad9933099ef4ded0030fa236f735fa73/href</a></iframe><p>For you to access the data from this table, you’ll need a Java class that maps these fields and the table itself. These classes are called entity classes and are annotated with the @Entity annotation at a class level. This annotation expects the table&#39;s name as a parameter.</p><p>You will need to add all the columns you want to map from your table and use the correct data types for these (int for id and String for make).</p><p>Finally, you’ll need to annotate your <a href="https://www.java67.com/2015/12/difference-between-primary-and-foreign.html"><em>primary key</em></a> property with the @Id annotation. Your class should look like this by now.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/669f1023b4aa5f3903ed51f8d7d5e713/href">https://medium.com/media/669f1023b4aa5f3903ed51f8d7d5e713/href</a></iframe><p>After you’ve created the entity class, you’ll need to add it to your DatabaseConfigBuilder class. Every time a new entity class is created, for Hibernate to perform the mapping on your service, you’ll need to add it using the addAnnotatedClass method. As a parameter, you’ll need to pass the type of entity.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bec63d06ae41eef49570808413b4bb1b/href">https://medium.com/media/bec63d06ae41eef49570808413b4bb1b/href</a></iframe><h4>#3 — Data Storage and Retrieval</h4><p>At this point, you have a database with the table, you’ve configured <a href="https://www.java67.com/2016/02/top-20-hibernate-interview-questions.html">Hibernate </a>and <a href="https://dev.to/javinpaul/10-free-php-and-mysql-courses-for-beginners-5eg2">MySQL</a>, now we are ready to retrieve data from the database.</p><p>For this task, you will need to create a repository class. This class needs to be annotated with the @Repository annotation at a class level.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1aff2e5954683e7577f6adf28119f0e/href">https://medium.com/media/c1aff2e5954683e7577f6adf28119f0e/href</a></iframe><p>We will need to implement a new method that returns a Session object. This task can be achieved by calling the buildConfiguration method from the DatabaseConfigBuilder class.</p><p>After calling this method, call the buildSessionFactory method. This method will return a SessionFactory object, which you will use in your repository class to make queries and store data to the database.</p><p>Make sure to store the SessionFactory is a static object in your repository class.</p><blockquote><a href="https://medium.com/javarevisited/the-time-i-should-have-used-the-singleton-design-pattern-and-everything-went-wrong-bb1ab107051e">I’ve personally learned that I had to do this, and ended up having my Spring Boot service crashing. Ultimately, creating multiple session factories might result in a memory leak.</a></blockquote><p>Once you are done, get the current session object by calling the getCurrentSession method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d5644c2b92181c57539a97345b2149e/href">https://medium.com/media/3d5644c2b92181c57539a97345b2149e/href</a></iframe><p>A potential enhancement here is to have some type of parent repository class from which all repository classes inherit from. For simplicity purposes of this post, I’ll keep things simple and add everything in the same class.</p><p>Ok, so now… we can connect to the <a href="https://medium.com/javarevisited/7-free-courses-to-learn-database-and-sql-for-programmers-and-data-scientist-e7ae19514ed2">database</a>, using the credentials you’ve specified before, let’s implement the method that returns the cars from the database. A few things on what this new method will do</p><ol><li>Retrieve the session by calling the getSession method you just implemented</li><li>Wrap this call in a try/catch</li><li>Begin a transaction on the session</li><li>From the session object, call the createQuery method where the first argument is the query and the second one is the type that will be returned. For the query, you write your query using SQL syntax except for the SELECT part of it.</li><li>On your catch block, make sure to roll back your transaction in case an exception is thrown.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6f66c578bfd3f3ed456d8751133c565/href">https://medium.com/media/f6f66c578bfd3f3ed456d8751133c565/href</a></iframe><p>Now that we can retrieve data, let’s go over storing data in our database table. This task is quite simple in <a href="https://javarevisited.blogspot.com/2018/01/top-5-hibernate-and-jpa-courses-for-java-programmers-learn-online.html#axzz610sfezGT">hibernate</a>, let’s begin by creating a new method in our repository class called saveCar.</p><p>In this method, we’ll need to follow these steps</p><ol><li>Get the session by calling the getSession method</li><li>Begin a transaction</li><li>Save the car object</li><li>Flush (Synchronize) and commit the transaction</li><li>Rollback in case of a failure</li><li>Close the session on a finally block</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c7b72a5feaa3b3bbb5e268b609a5f91/href">https://medium.com/media/1c7b72a5feaa3b3bbb5e268b609a5f91/href</a></iframe><p>The last step on this puzzle is to call the repository class from your <a href="https://javarevisited.blogspot.com/2017/11/difference-between-component-service.html">controller</a>. Because you annotated your repository class with the @Repository annotation, you can just auto-wire it.</p><p>In our controller, we will now be able to call the getCars and saveCar methods.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/774ecface2132a4c527f258c5c1ca415/href">https://medium.com/media/774ecface2132a4c527f258c5c1ca415/href</a></iframe><h4>Common Errors</h4><p>Finally, as with any new technology, there will be errors you face as you set things up. Let’s quickly go over a few common exceptions you might encounter as you work on setting up Hibernate on your <a href="https://medium.com/hackernoon/top-5-spring-boot-and-spring-cloud-books-for-java-developers-75df155dcedc?source=---------23------------------">Spring Boot</a> service.</p><p><strong>QuerySyntaxException: Entity is not mapped</strong></p><p>If you ever encounter this error, this could mean one of three things.</p><ol><li>You are missing to add this entity to your configuration by using the addAnnotatedClass method.</li><li>The entity name in your @Entity annotation is incorrect. An example could be you entered @Entity(name = &quot;CarX&quot;) instead of @Entity(name = &quot;Car&quot;).</li><li>The name of the table inside your createQuery method call is incorrect or does not exist.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2325a3609e8bf90683dded3e1758420/href">https://medium.com/media/d2325a3609e8bf90683dded3e1758420/href</a></iframe><p><strong>CJException: Access denied for user</strong></p><p>Verify your credentials. This might mean that the username and/or password are incorrect. Try using the command line to <a href="https://www.java67.com/2013/02/how-to-connect-mysql-database-from-java.html">connect to MySQL first </a>with these credentials to validate that they are correct.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be8026c77c845c703cd889ebbd05c5bf/href">https://medium.com/media/be8026c77c845c703cd889ebbd05c5bf/href</a></iframe><p><strong>AnnotationException: No identifier specified for entity</strong></p><p>This exception is thrown when your entity does not have at least one field annotated with the @Id annotation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4195a7bbe688f83c2f74a6b06b6926b/href">https://medium.com/media/b4195a7bbe688f83c2f74a6b06b6926b/href</a></iframe><p><strong>MappingException: Composite-id class must implement Serializable</strong></p><p>This exception is thrown when you have an entity that should have more than one field annotated with the @Id annotation as your table has a <a href="https://www.java67.com/2012/10/difference-between-primary-vs-unique-key-table-sql.html">composite primary key.</a> In this case, annotate the fields with the @Id annotation, but also implement the Serializable interface on your entity class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5435528f781da07b79e46c7e10d2951b/href">https://medium.com/media/5435528f781da07b79e46c7e10d2951b/href</a></iframe><p><strong>SQLSyntaxErrorException: Unknown column</strong></p><p>This exception is thrown when you either have a typo on your column, or the column does not exist in the table. In this case, we named the column idX instead of id.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3040bed627974dec4c3154842e3d9471/href">https://medium.com/media/3040bed627974dec4c3154842e3d9471/href</a></iframe><p><strong>HibernateException: Calling method ‘createQuery’ is not valid without an active transaction</strong></p><p>The description of this exception is self-explanatory. Before you call createQuery, you missed beginning the transaction.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ed672b67b00bbb5785d31fef9de4aa0/href">https://medium.com/media/0ed672b67b00bbb5785d31fef9de4aa0/href</a></iframe><p><strong>IllegalArgumentException: Type specified for typedQuery is incompatible with query return type</strong></p><p>When this exception is thrown, most likely you ended up adding the wrong type to the createQuery method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b554a4ad97a5161a1761241da9fe1e2d/href">https://medium.com/media/b554a4ad97a5161a1761241da9fe1e2d/href</a></iframe><p>In this case, I ended up using the CreateCarRequest class to map the results from the query instead of using the correct CarEntity class for this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e34e75f848c85df9ae6fd2aef7f2d2e5/href">https://medium.com/media/e34e75f848c85df9ae6fd2aef7f2d2e5/href</a></iframe><p>I hope that this post has helped you feel more familiar with how to setup Hibernate, and how to leverage it for your database interactions on your service. Enjoy!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46a4dd0be995" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/from-zero-to-service-retrieving-and-storing-data-using-hibernate-mysql-and-spring-boot-46a4dd0be995">From Zero to Service — Retrieving and Storing Data Using Hibernate, MySQL, and Spring Boot</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Zero to Service — A Guide on Creating an API using Java Spring Boot]]></title>
            <link>https://medium.com/javarevisited/from-zero-to-service-a-guide-on-creating-an-api-using-java-spring-boot-88080b54a597?source=rss-62c558d0cfb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/88080b54a597</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[tech.mia]]></dc:creator>
            <pubDate>Sun, 28 Feb 2021 15:02:40 GMT</pubDate>
            <atom:updated>2021-02-28T15:02:40.045Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Zero to Service — A Guide on Creating an API using Java Spring Boot</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mvKbADp4T5f-_X2m" /><figcaption>Photo by <a href="https://unsplash.com/@tegethoff?utm_source=medium&amp;utm_medium=referral">Mark Tegethoff</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this post, we’ll go through all the steps required to get a Java Spring Boot service up and running. At a pretty high level, Spring Boot is an open-source framework that simplifies tasks such as dependency injection and assists with building APIs.</p><h4>The Goal</h4><p>We will be implementing a service that will take care of creating, updating, and retrieving cars from an inventory. In this example, if we follow HTTP and REST standards, we can implement this using two API requests.</p><ol><li>For the request to retrieve all cars in the inventory, we will use a method of <strong>GET</strong>. Its route will be /v1/cars and it will return a list of cars.</li><li>For the request to create and update cars, we will use a method of <strong>PUT</strong>. Its route will be /v1/cars/{carId}, where the {carId} parameter is the car&#39;s unique identifier. This request will have as part of its request body the full definition of the car you are going to create or update. For simplicity purposes, a car will only have a make and an id property.</li></ol><h4>The Project</h4><p>We will proceed now to create our service. One of the simplest ways to achieve this task is to go to <a href="https://start.spring.io./">https://start.spring.io.</a> Here you can download an empty project that will come with the right dependencies and basic scaffolding.</p><p>For purposes of this post, we will be using <a href="https://maven.apache.org/what-is-maven.html">Maven</a>, Java 11, and Spring Boot 2.4.3. Select these options on the page and feel free to fill out the project’s metadata with the details that are specific to your project. By the time you read this post, the Spring Boot version might have changed, feel free to pick at that point whatever the latest version is.</p><p>On the <strong>Dependencies</strong> section, select <strong>Spring Web</strong> and then click the <strong>Generate</strong> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yiM3Zy3DW6wtn6bGDRwtRA.png" /></figure><p>Once you download this project, start by unzipping it and opening it using your favorite Java IDE. When you open the project, you’ll find a <em>.java</em> file named <em>/YOUR_PROJECT_NAME/Application.java</em>. Where, YOUR_PROJECT_NAME is the name you gave to this project. This file is the entry point that contains the main method for Spring Boot applications.</p><h4>Controllers and Endpoints</h4><p>Let’s start by creating a model and a request class. Our model class will represent a car in our project. The request class will be used for HTTP requests for creating a new car.</p><p>Our model class will have one property called make of type String and a property called id of type int. Make sure to add getters, setters, equals, and hashCode methods.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff1bc1a0e776c638863bd480396a6032/href">https://medium.com/media/ff1bc1a0e776c638863bd480396a6032/href</a></iframe><p>For the request class, we will only be adding a property named make of type String. As you did with the model class, make sure to add getters, setters, equals, and hashCode methods.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee59735bb80e3114aa178a6922b68837/href">https://medium.com/media/ee59735bb80e3114aa178a6922b68837/href</a></iframe><p>Now that you know how a car should look like in your service, it is time to create the API. Let’s start by creating what is known as a REST Controller. REST controllers in Spring Boot have methods that map to API requests which you can call via HTTP from a client.</p><p>For you to create your first controller, you can go ahead and create a new file named <strong>CarController.java</strong>.</p><p>Controllers should be annotated with the @RestController annotation at a class level. As of now, your controller class should look like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/719f4479435da4c2defa3ae58da19f2e/href">https://medium.com/media/719f4479435da4c2defa3ae58da19f2e/href</a></iframe><p>The next step will be to add a method per HTTP request you are going to create. In this case, we’ll start by first creating a method for our <strong>GET</strong> request.</p><p><strong>GET</strong> request methods should be annotated with the @GetMapping annotation. In this example, you will pass an argument of type String the name of the route, which in our example is /v1/cars.</p><p>Now you can go ahead and specificy the method return type for this request. This method should return an object of type ResponseEntity where you pass in as its generic type, your object&#39;s type. This method should have a return type ofResponseEntity&lt;Set&lt;Car&gt;&gt; as we&#39;ll be returning a set of cars.</p><p>As of now, your controller class should look like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e14eece6cc0afe7d016fd76f98d8ac8c/href">https://medium.com/media/e14eece6cc0afe7d016fd76f98d8ac8c/href</a></iframe><p>For simplicity purposes, in this post, we’ll be adding and removing cars from a Set object that is in memory. Given this, our next step should be to add this object as an instance variable on your controller class.</p><p>Finally, our <strong>‌GET</strong> method will be returning a new ResponseEntity object where you pass in as the first argument the cars object and as a second argument, the HTTP status code of OK, by using HttpStatus.OK.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c89c51c9b9ab3318fbe6e2959e2c886/href">https://medium.com/media/2c89c51c9b9ab3318fbe6e2959e2c886/href</a></iframe><p>The second endpoint we will be creating will be adding a car to our cars set. In this case, we&#39;ll be using the <strong>‌PUT</strong> HTTP method. As you might have guessed, the annotation will be @PutMapping for this method.</p><p>There are a few things we need to do as part of this request.</p><p><strong><em>1 — Path Variable</em></strong></p><p>The path variable is part of your request’s route. In the example of the <strong>PUT</strong> request, it is the car’s id in /v1/cars/{carId}.</p><p>Path variables in Spring Boot are parameters to your requests, which are annotated with the @PathVariable annotation. In this case, you will need to add to your method a parameter of type int called carId annotated with the @PathVariable annotation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f70953011dcf613264d206541b459247/href">https://medium.com/media/f70953011dcf613264d206541b459247/href</a></iframe><p>It is important to mention that the name on the route for your parameter should match the property’s name.</p><p><strong><em>2 — Request Body</em></strong></p><p>The second thing you’ll do as part of this method is to add a parameter of type CreateCarRequest to this method.</p><p>Next, you’ll have to annotate this parameter with the @RequestBody annotation. This will result in your API&#39;s consumers being able to send the car information to be added as part of the HTTP request&#39;s body.</p><p>In your method, you’ll need to map the object to an object of type Car. Then, you will need to add it to your cars set.</p><p>Finally, you will need to return a ResponseEntity object with the status code of ACCEPTED using HttpStatus.ACCEPTED.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e90a5dbbef405d14e9fc113f75d60657/href">https://medium.com/media/e90a5dbbef405d14e9fc113f75d60657/href</a></iframe><h4>Running the service and consuming the API</h4><p>Now that we are done implementing our API, how do I make requests to my service?</p><p>It is easy, first of all, once you run the service, you need to know that it will be running, by default on port 8080.</p><p>You can either use command-line utilities such as cURL, or a UI-based application such as Postman for this.</p><p>For you to create/update cars, you will need to construct your request with the following:</p><p><strong>Route</strong>: <a href="http://localhost:8080/v1/cars/001">http://localhost:8080/v1/cars/001</a> <br><strong>Method</strong>: PUT <br><strong>Request Headers</strong>: Content-Type: application/json <br><strong>Request Body</strong>: { make: &quot;My car&#39;s make&quot; }</p><p>You should expect back getting a 202 Status Code, and the car to be added to your Set.</p><p>To verify that the car was added, let’s call the <strong>‌GET</strong> request. This request should return the full list of all cars that have been added to the inventory.</p><p><strong>Route</strong>: <a href="http://localhost:8080/v1/cars">http://localhost:8080/v1/cars</a> <br><strong>Method</strong>: GET</p><p>You should expect back getting a 202 Status Code, along with a list of cars.</p><p>Hopefully, by now you’ve been able to get an idea of how to create a simple API service using Java Spring Boot. Enjoy!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88080b54a597" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/from-zero-to-service-a-guide-on-creating-an-api-using-java-spring-boot-88080b54a597">From Zero to Service — A Guide on Creating an API using Java Spring Boot</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn How to Write End to End Automation Using Cypress]]></title>
            <link>https://javascript.plainenglish.io/learn-how-to-write-end-to-end-automation-using-cypress-ed2f6bcbdba1?source=rss-62c558d0cfb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed2f6bcbdba1</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[tech.mia]]></dc:creator>
            <pubDate>Sat, 27 Feb 2021 07:25:01 GMT</pubDate>
            <atom:updated>2021-02-27T07:25:01.322Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gq-MZ2FwPPccoaxt" /><figcaption>Photo by <a href="https://unsplash.com/@plhnk?utm_source=medium&amp;utm_medium=referral">Paul Hanaoka</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>The Problem</h4><p>Automated testing is a crucial part of high-quality software development. There are several dos and don’ts and pros and cons with every level of automated testing.</p><p>If you are not familiar with the different levels of automation, you can go from testing a unit of code (ex. a class), to test the integration of these units (ex. multiple classes), to the whole system. Testing is all about the risks and picking the right compromises. Given this, you should attempt to have a fairly balanced test suite so you don’t end up with days of running automation and you can have a fast and reliable feedback loop.</p><p>In this post, I’ll be focusing on a testing framework that currently helps with testing the whole system from a web browser. These types of tests are usually called UI tests, end-to-end tests, or system tests. While system tests are great, as they exercise the system from a user’s perspective, there are a few issues with these.</p><ul><li><strong>Reliability</strong>: These types of tests tend to fail a lot as you need the whole system up, and very brittle. Any minor hiccups, without the right level of retries, could cause a test failure.</li><li><strong>Expensive to troubleshoot</strong>: Without the proper logging and monitoring, these types of tests could be difficult to troubleshoot. Take as an example, a login page that doesn’t work. What is the exact issue? Could it be a frontend issue? a network issue? or, a backend issue?</li><li><strong>Duration</strong>: Because they require a UI and the backend to be working, there could be complex setup and long-running tasks. This could result in minutes per test in many cases.</li><li><strong>Maintainability</strong>: For these types of tests you tend to use CSS selectors. Picking up the wrong type of selectors might result in a failing test even though nothing is functionally wrong.</li></ul><p>In this post, I’ll be going over a UI testing framework called Cypress. Cypress is a very easy-to-use end-to-end testing framework. If you’ve with Selenium-based testing frameworks before, Cypress doesn’t use Selenium. They also claim that it “runs in the same run-loop as the application.”</p><p>Based on my experience so far, writing my end-to-end automation using Cypress has resulted in easy to write, easy to debug, fast, and more reliable tests. In the end, no UI testing framework is bulletproof and you should really attempt to make responsible choices when picking what to automate, what your preconditions for your tests should be, and how often you should run these tests.</p><h4>Setting up the project</h4><p>Let’s get started with the setup required for you to be able to run these tests. In this post, we’ll be creating a brand new project that will only contain these tests.</p><p>The first thing you do is to create a brand new npm project and install Cypress.</p><pre>npm init<br>npm install --save-dev cypress@latest</pre><p>By now, your project structure should have a package.json file, a package-lock.json file, and the node_modules folder.</p><p>Your next step will be to create your cypress configuration file. At the root of your project, add a file named cypress.json with the following contents.</p><pre>{<br>  &quot;integrationFolder&quot;: &quot;tests&quot;,<br>  &quot;defaultCommandTimeout&quot;: 15000,<br>  &quot;pageLoadTimeout&quot;: 30000,<br>  &quot;video&quot;: true<br>}</pre><p>Let’s start by going over what each one of these values represents.</p><ol><li>integrationFolder: This is the folder where all of your tests will be on. Here, we are expecting all of your tests to be inside the tests folder which is located at the root of the project. You can put any value, just make sure that the folder exists and that it contains your tests.</li><li>defaultCommandTimeout: This is the amount of time (in milliseconds) it will take until a specific command fails. For example, if you click on an element, if that element doesn&#39;t show up on the screen, it will keep retrying for this amount of time.</li><li>pageLoadTimeout: This is the amount of time (in milliseconds) it will take for the testing framework to wait until a page has loaded successfully.</li><li>video: Setting this to true will enable video recording of all your tests.</li></ol><p>Looking for more configuration flags? you can look for more here <a href="https://docs.cypress.io/guides/references/configuration.html">https://docs.cypress.io/guides/references/configuration.html</a></p><h4>Writing your first test</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZgbaeZyG2mFFb913" /><figcaption>Photo by <a href="https://unsplash.com/@jamesponddotco?utm_source=medium&amp;utm_medium=referral">James Pond</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Writing tests using Cypress is quite easy. To begin, start by creating a new JavaScript file inside the tests folder (or whatever folder you&#39;ve set to be in your integrationFolder folder).</p><p>Every test is wrapped by a describe block and tests are inside these blocks are wrapped by it blocks.</p><pre>describe(&#39;my first test suite`, () =&gt; {<br>    it(&#39;my first test&#39;, () =&gt; {<br>    <br>    });<br>});</pre><p>Now before writing our first test, let’s go over the most basic commands. These Cypress commands will help you with most of the tasks you need to achieve when writing UI test automation.</p><h4>Visit a specific URL</h4><p>The first step on almost all of your tests will be visiting a specific URL. This will take care of opening the browser and navigating to the URL you’ve provided. For this, you will use the visit command, and pass as an argument the URL to visit.</p><pre>cy.visit(&#39;url to visit...&#39;);</pre><h4>Retrieving elements</h4><p>If you want to perform actions on elements from the DOM, you are going to always need to retrieve the element from the DOM first. For example, if your HTML page has something like this:</p><pre>&lt;div id=&quot;the-item&quot;&gt;Text goes here&lt;/div&gt;</pre><p>You are going to want to select by the ID. This will result in a selector of #the-item.</p><p>Cypress provides a method that retrieves an element from the DOM. This method is called .get and you provide as an argument the CSS selector that uniquely identifies that element.</p><p>In this example, you’ll use the following in order to retrieve the element and perform an action on it on your test.</p><pre>cy.get(&#39;#the-item&#39;)</pre><h4>Actions on DOM elements</h4><p>If you want to verify if an element is visible or not, you are going to want to use the should commands and pass in one of the following arguments:</p><ol><li>The &#39;be.visible&#39; argument for when you want to verify if an element is visible to a user.</li><li>The &#39;not.be.visible&#39; argument for when you want to verify if an element is not visible to a user.</li></ol><pre>cy.get(selector).should(&#39;be.visible&#39;);<br>cy.get(selector).should(&#39;not.be.visible);</pre><p>There are other basic tasks that you can perform with Cypress. These are typing on input elements, verifying if elements contain a specific text, or clicking on elements.</p><p>If you want to type on an input element, you will need to first get this element, then use the type function. As an argument to the type function, you&#39;ll need to pass the text you want to enter on your element.</p><pre>cy.get(selector).type(text);</pre><p>For you to verify if an element contains a text, you will need to use the contains method. You will need to pass as an argument the text you want to verify that the element contains.</p><pre>cy.get(selector).contains(text);</pre><p>Finally, if you want to click on an element, you will need to call the click method, which doesn&#39;t require you to pass any arguments for this action.</p><pre>cy.get(selector).click();</pre><h4>Tying everything together</h4><p>As you might have realized by now, your test automation will consist of a combination of commands and not a single command.</p><p>As an example, you might want to visit a page, type something on a form, click a submit button, and verify the text of an element on the screen. This simple scenario will be written the following way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/191e27e2312f4fc683a809bfb9add5a1/href">https://medium.com/media/191e27e2312f4fc683a809bfb9add5a1/href</a></iframe><h4>Running the tests</h4><p>The final topic we’ll cover is, how to run your tests? As part of your package.json file, add to the scripts object the following script. The value cypress.json is the configuration file you’ve previously created.</p><pre>&quot;test&quot; : &quot;cypress run --config-file=cypress.json&quot;</pre><p>If you want to leverage Cypress’s user interface and be able to run specific tests and see the details of your test runs, add this script.</p><pre>&quot;test:open”: “cypress open -C cypress.json”</pre><p>Hope you’ve gotten a better understanding of this great test automation framework. Enjoy!</p><p><strong>Resources</strong></p><p><a href="https://www.cypress.io/how-it-works/">End to End Testing Framework</a></p><p><em>Get more content at </em><a href="https://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed2f6bcbdba1" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/learn-how-to-write-end-to-end-automation-using-cypress-ed2f6bcbdba1">Learn How to Write End to End Automation Using Cypress</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying a Java Spring Service to a Virtual Machine Using Github Actions]]></title>
            <link>https://medium.com/javarevisited/deploying-a-java-spring-service-to-a-virtual-machine-using-github-actions-d7d4c2398cbb?source=rss-62c558d0cfb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7d4c2398cbb</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[deployment-automation]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[github-actions]]></category>
            <dc:creator><![CDATA[tech.mia]]></dc:creator>
            <pubDate>Mon, 22 Feb 2021 06:45:59 GMT</pubDate>
            <atom:updated>2021-02-22T06:45:59.250Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lq7BpJMPfTpHg7vU" /><figcaption>Photo by <a href="https://unsplash.com/@floriankrumm?utm_source=medium&amp;utm_medium=referral">Florian Krumm</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>While it is true that there are some clear benefits to deploying your applications using containers over virtual machines, in some cases due to costs or other requirements you might prefer to deploy to a virtual machine.</p><p>In this post, we’ll go through the steps required for you to be able to deploy a Java Spring service to a virtual machine using <a href="https://github.com/features/actions">GitHub Actions</a>.</p><p>Let’s begin with a few assumptions we’ll be making before we begin:</p><ol><li>The virtual machine that we’ll be using has already been created</li><li>The virtual machine already has some version of the OpenJDK installed</li><li>You are able to SSH into this virtual machine</li></ol><h4>When to Deploy the Service?</h4><p>Let’s start with the most critical question. When should we deploy our application?</p><p>Well, you have a few options... Do you want to deploy your application when you check-in code to a specific branch? or, do you want to have more control and deploy it manually?</p><p>With GitHub Actions, all of these are possible. You can either be more creative and do things like, deploy the application when a ticket is created or when a release is created.</p><p>In this post, we’ll be going over what it takes to deploy your application manually. Even if this doesn’t satisfy the needs of your application, trust me, changing the event under which this workflow gets triggered is pretty simple.</p><h4>Let’s Begin!</h4><p>The first step will be for you to create file your workflow file. GitHub Actions requires you to create a YAML file under the .github/workflows folder.</p><p>Workflow files must contain a name, which will be the first property you declare on it.</p><p>You should follow this with the on property where you specify what event will trigger this action. The workflow_dispatch action should be used when triggering workflows manually. After this, you have the option of providing inputs to your action which can be set to be required or not. These inputs can be validated to contain certain values or can be added purely for documentation purposes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30de614403034ca7b850665f22baa715/href">https://medium.com/media/30de614403034ca7b850665f22baa715/href</a></iframe><h3>Next Steps</h3><h4>Let’s store the secrets! Shh…</h4><figure><a href="https://www.java67.com/2012/09/10-linux-and-unix-interview-questions-answers-wipro-tcs-capegemini.html"><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9Tb-nctH8nQq0ll2" /></a><figcaption>Photo by <a href="https://unsplash.com/@benwhitephotography?utm_source=medium&amp;utm_medium=referral">Ben White</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Before we start, the first step will be to upload all the secrets to your Github account. What are the secrets? These are the values you shouldn’t share with anyone or have in plaintext in order to authenticate with your virtual machine.</p><p>For purposes of this deployment, we’ll consider as secrets your server’s IP address, username, and SSH key.</p><p>For you to store these values, you’ll need to go to your GitHub project’s <strong><em>Settings </em></strong>tab, then go to the <strong><em>Secrets</em></strong> menu option. Here you will click on the <strong><em>New repository secret</em></strong> button.</p><figure><a href="https://javarevisited.blogspot.com/2019/05/10-free-websites-to-learn-git-online.html"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uLh1lJMbPE0UEV5Rguu-Kw.png" /></a></figure><p>This will take you to the screen where you end up adding your secrets. Each secret contains a <strong><em>Name</em></strong> and a <strong><em>Value</em></strong>. The name will be the name you will use in your GitHub workflow to refer to this secret. An example here will be <strong><em>SERVER_IP_ADDRESS</em></strong> will be the name, and the value will be your virtual machine’s public IP address.</p><figure><a href="https://javarevisited.blogspot.com/2018/01/5-free-git-courses-for-programmers-to-learn-online.html#axzz6nBECW4NQ"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VkuSJBzpuQUBeeo77kMJEQ.png" /></a></figure><p>Feel free to proceed to store the three values (IP Address, username and SSH key) as secrets in here.</p><p>Once we have the secrets stored for our virtual machine, we can proceed with building the workflow file.</p><h4>Building the GitHub Workflow</h4><p>As you can see on this diagram, getting your Java service up and running is a very simple five-step process.</p><figure><a href="https://javarevisited.blogspot.com/2018/01/5-free-git-courses-for-programmers-to-learn-online.html#axzz6nBECW4NQ"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bEZNI2EamP8JqTk0_f90Og.png" /></a><figcaption>Deployment Process</figcaption></figure><p><strong><em>Steps #1 and #2 — Check out Code and Build your App</em></strong></p><p>First, you need to check out your code, then build your application’s JAR file.</p><p>For this step, you will use the actions/checkout@v2 action and the actions/setup-java@v1 action. Finally, you’ll need another job that will contain the scripts required to be able to build your application.</p><p>With this, you’ll be able to checkout your code, using <a href="https://www.java67.com/2018/08/top-10-free-java-courses-for-beginners-experienced-developers.html">Java 11</a> and build your JAR file. In this example, we’ve encapsulated the required scripts for building your application inside script-to-build.sh, but this can easily be a maven task or something else.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8bf70ad5fe992e0651ad4596515076de/href">https://medium.com/media/8bf70ad5fe992e0651ad4596515076de/href</a></iframe><p>Depending on your use case, you might consider replacing the building of your application with downloading your application from somewhere else (as it was already built). If this is the case, feel free to replace the contents of these two steps with something else.</p><p><strong><em>Steps #3 —Copy application to the server (Upload JAR)</em></strong></p><p>After we have our JAR file, we need to proceed with authenticating with our server and uploading it.</p><p>For this, you can use the appleboy/scp-action@master action. This action takes care of copying files to the server you specify and uses the credentials you&#39;ve stored on your GitHub repository secrets.</p><p>For this example, there are six parameters you need to provide for this action. The first three come from your secrets, which are:</p><ol><li><em>Server’s IP address</em></li><li><em>Username</em></li><li><em>SSH key</em></li></ol><p>The last three will need to be manually entered:</p><ol><li>Port number (22)</li><li>Your application’s location on the GitHub worker</li><li>The target folder on the virtual machine</li></ol><p>Whenever you use secrets that you add to <a href="https://medium.com/javarevisited/7-best-courses-to-master-git-and-github-for-programmers-d671859a68b2?source=---------9------------------">GitHub</a>, you can refer to these by enclosing them in ${{ }}. Your secret will be prefixed with the word secrets, a period, and the name you gave your secret when storing it. In the example provided before, you will do ${{ secrets.SERVER_IP_ADDRESS}}.</p><p>At this point, this new job you are adding to your workflow should look like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ab3ef69b882a7cf1a661e6d9ec4f82f/href">https://medium.com/media/8ab3ef69b882a7cf1a661e6d9ec4f82f/href</a></iframe><p><strong><em>Steps #4 and #5— Stop Old Service and Start New Service</em></strong></p><p>For us to be able to install our J<a href="https://javarevisited.blogspot.com/2018/05/the-springbootapplication-annotation-example-java-spring-boot.html">ava Spring Boot application</a>, I’ll be following Spring’s recommendations on installing the service as an init.d service.</p><p><a href="https://docs.spring.io/spring-boot/docs/current/reference/html/deployment.html#deployment-initd-service">Deploying Spring Boot Applications</a></p><p>Let’s get your application up and running now. For this, we’ll need to SSH into the server. For SSH’ing into a virtual machine, we can use the appleboy/ssh-action@master action.</p><p>The parameters for this action are very similar to the previous one. You will need to provide an <em>IP address</em>, <em>username</em>, <em>SSH key</em>, and <em>port number</em> (22).</p><p>Because this action is SSH’ing into your server, you will need to write down inside the script object in your workflow file, the commands you want to run. The steps to install and get running your application will be quite simple.</p><p><strong><em>First:</em></strong> we’ll stop the currently running service (as you will be doing this process multiple times throughout the lifetime of your application).</p><p><strong><em>Second:</em></strong> we will rename the old and new JARs. This is so that our running application’s JAR is always named my-app.jar and the old one is always named my-app-old.jar .</p><p><strong><em>Third: </em></strong>Once we are done with this, we will be creating and starting the init.d service.</p><p><strong><em>And the last step:</em></strong> Remove the old JAR (optional!)</p><p>Now, your service should be up and running! At this point, your new job should look similar to this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7ea1667e5b03ab3bf0a690d418bb5fc/href">https://medium.com/media/a7ea1667e5b03ab3bf0a690d418bb5fc/href</a></iframe><h4>Wrapping everything up</h4><p>So far we’ve been able to incrementally create jobs within a single GitHub Actions file that help us achieve the tasks of</p><ul><li>Checking out our code</li><li>Building our application</li><li>Uploading it to a virtual machine</li><li>And… installing it as a service.</li></ul><p>The final workflow file should look similar to this one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62ece457d7a881c9f6d56656a76ccb1b/href">https://medium.com/media/62ece457d7a881c9f6d56656a76ccb1b/href</a></iframe><p>Hope this post helps you automate your deployment workflow for your Spring Boot application. Enjoy!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7d4c2398cbb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/deploying-a-java-spring-service-to-a-virtual-machine-using-github-actions-d7d4c2398cbb">Deploying a Java Spring Service to a Virtual Machine Using Github Actions</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Write Less Code in Java 11 Using Lombok]]></title>
            <link>https://medium.com/javarevisited/how-to-write-less-code-in-java-11-using-lombok-90bcc255ee1f?source=rss-62c558d0cfb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/90bcc255ee1f</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[lombok]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[tech.mia]]></dc:creator>
            <pubDate>Mon, 10 Aug 2020 04:58:57 GMT</pubDate>
            <atom:updated>2020-08-10T12:28:58.687Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn how to not have to implement getters, setters, and other methods for your Java applications by only using a few annotations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iwGS5nG44rCkstye0F9e0g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@razvanux?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">razvanux</a> on <a href="https://unsplash.com/s/photos/lombok-island?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Developing in Java can sometimes feel a little bit verbose. As programmers, we are always eager to write more code but wanting to do less at the same time.</p><p>Coming from a <a href="https://medium.com/javarevisited/9-free-c-c-sharp-courses-and-tutorials-for-beginners-and-intermediate-programmers-best-of-lot-dc8c793aab31">C#</a> background, when I started programming in Java, I’ve always asked myself: <em>How can I avoid having to write all these setters and getters? </em>One day I was introduced to <a href="https://projectlombok.org/"><strong>Project Lombok</strong></a>.</p><p>Project Lombok is an open-source library that helps you write less code in a few areas. Just to mention a few… you can avoid having to implement:</p><ul><li>Getters and setters</li><li>Default or all argument constructors</li><li>toString methods</li><li>equals methods</li><li>hashCode methods</li></ul><p>In this article, I’ll be going over a few of these annotations to help you get a better idea of how Project Lombok might be included as part of your <a href="https://medium.com/javarevisited/10-books-java-developers-should-read-in-2020-e6222f25cc72">Java</a> application.</p><h4>Setup</h4><p>The first step will be to import Lombok to your application. In this example, I’ll be using <a href="https://maven.apache.org/what-is-maven.html"><strong>maven</strong></a> for dependency management. I’ll be adding Lombok as one of my application’s dependencies. As of the writing of this article, 1.18.12 is the latest stable version.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79149aaa7633a7de78102d11de6e04ab/href">https://medium.com/media/79149aaa7633a7de78102d11de6e04ab/href</a></iframe><p>In order for you to be able to compile your code, your next step will be for you to configure your IDE. I’ve been using <a href="https://www.jetbrains.com/idea/"><strong>IntelliJ IDEA</strong></a>, and the setup is pretty straightforward. On the plugins section, you will have to search for the Lombok plugin. Once you’ve done this, you can install it and restart your IDE.</p><figure><a href="https://medium.com/javarevisited/7-best-courses-to-learn-intellij-idea-for-beginners-and-experienced-java-programmers-2e9aa9bb0c05"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xdn2tNstjT4JjHxopqNHsw.png" /></a></figure><p><a href="https://dev.to/javinpaul/5-best-courses-to-learn-intellij-idea-for-java-developers-5e6n">IntelliJ IDEA</a> is not the only IDE supported by Project Lombok. According to their webpage, it also supports <a href="https://medium.com/javarevisited/top-10-courses-to-learn-eclipse-junit-and-mockito-for-java-developers-4de1e8d62b96">Eclipse</a>, Netbeans, and VS Code just to mention a few.</p><h4>Getters and Setters</h4><p>Let’s start with the biggest win that I was able to achieve with Lombok. Not having to implement getters or setters. Life before Lombok looked like this code snippet for me. To be perfectly honest, it wasn’t terrible, as IntelliJ has a way to autogenerate these. But… it gets lengthy once you have a handful of properties in your class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/001ee1d31ee8d7a4e054feefbec5df5d/href">https://medium.com/media/001ee1d31ee8d7a4e054feefbec5df5d/href</a></iframe><p>In Lombok, you will need to annotate your properties with the @Getter and @Setter annotations. These will add getters and setters to your class.</p><p>In Lombok, you just need to annotate your properties with the @Getter and @Setter annotations. These will add getters and setters to your class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50a8a5238634daa358b31dbc2c08f4d8/href">https://medium.com/media/50a8a5238634daa358b31dbc2c08f4d8/href</a></iframe><p>For you to call the getters or setters for this class is quite easy. For non-boolean data types, in camel-case, you need to call the method prefixed with get or set. As an example, for the name property, it will be setName andgetName.</p><p>When it comes to boolean properties, things are slightly different. For setters, we follow the same rules as before. For getters, the method will be prefixed withis followed by the property&#39;s name. In this example, the suv property getter will be isSuv and the setter will be setSuv.</p><h4>Constructors</h4><p>This one is a smaller win, but worth sharing it too. You can use the @NoArgsConstructor, @AllArgsConstructor or @RequiredArgsConstructor.</p><p>While the names of the <a href="https://www.java67.com/2019/04/top-10-spring-mvc-and-rest-annotations-examples-java.html">annotations</a> are self-explanatory, I’ll go over each one of them.</p><ul><li>@NoArgsConstructor - Implements a public constructor with no arguments.</li><li>@AllArgsConstructor - Implements a public constructor with all the properties for your class as arguments.</li><li>@RequiredArgsConstructor - Implements a public constructor with all <a href="https://javarevisited.blogspot.com/2016/09/21-java-final-modifier-keyword-interview-questions-answers.html">final</a> properties and those marked with the @NonNull annotation only.</li></ul><p>For you to leverage any of these, you will add these annotations to your class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5eb81668997afa8a0cca22f980851b2c/href">https://medium.com/media/5eb81668997afa8a0cca22f980851b2c/href</a></iframe><p>The default access modifier for these annotations is public. You can change the access modifier for any of these constructor types with the access element. In this example, I will pass in a value of AccessLevel.PRIVATE. This will make the no-args constructor be private.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40b2597547141e054d54763f4d9119ac/href">https://medium.com/media/40b2597547141e054d54763f4d9119ac/href</a></iframe><h4>Equals and HashCode</h4><p>If you are required to implement equals and hashCode methods for your class, Lombok provides one annotation for these two methods.</p><p>The equals and hashCode methods are easy targets for you to forget about when updating the properties for your classes. With Lombok&#39;s @EqualsAndHashCode annotation, you can annotate your class and forget about having to implement these methods.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5125f214a271d157b30b89f866a755dd/href">https://medium.com/media/5125f214a271d157b30b89f866a755dd/href</a></iframe><h4>Builder</h4><p>If you need a builder for your class, you need to add the @Builder annotation to your class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d39ad62ba10af6cbc9e6dcf36359c04/href">https://medium.com/media/3d39ad62ba10af6cbc9e6dcf36359c04/href</a></iframe><p>From a consumer’s perspective, you will need to call the static builder() method on your class.</p><pre>Car.builder()</pre><p>After you’ve done this, for each one of the properties you want to set a value for, there will be a method accessible with the property’s name.</p><p>Because of the fluent syntax of the <a href="http://javarevisited.blogspot.sg/2012/06/builder-design-pattern-in-java-example.html">builder pattern</a>, you can just chain these method calls as it will return an object of the same type. In order to finally build the object of type Car, you will need to call the .build() method at the end.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b46d29e1993584ef902c66fdb023cc31/href">https://medium.com/media/b46d29e1993584ef902c66fdb023cc31/href</a></iframe><h4>Data and Value: The annotations of annotations</h4><p>According to <a href="https://projectlombok.org/features/all"><strong>Lombok’s documentation</strong></a>, the @Data annotation will take care of adding</p><blockquote>@ToString, @EqualsAndHashCode, @Getter on all fields, and @Setter on all non-final fields, and @RequiredArgsConstructor</blockquote><p>In other words, instead of you having to do this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd34a9d9878fd1124d345c8c253e0721/href">https://medium.com/media/dd34a9d9878fd1124d345c8c253e0721/href</a></iframe><p>You can just add the @Data annotation on your class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1022f93413df71c8d919bb184a98cee7/href">https://medium.com/media/1022f93413df71c8d919bb184a98cee7/href</a></iframe><h4>Things to watch out about</h4><p>As you’ve seen so far, an IDE is crucial in this process. This might become a limitation if you are wanting to use an IDE that is not supported by Lombok.</p><p>I’ve had a Java <a href="https://medium.com/javarevisited/10-free-spring-boot-tutorials-and-courses-for-java-developers-53dfe084587e?source=collection_home---4------7-----------------------">Spring Boot</a> project with 50k+ lines of code for the past 4 years using Lombok. So far, I haven’t had any complaints about it. It suits the needs of my application and makes me more productive. While it has worked for me, this should be evaluated on a case by case basis.</p><p>Not everything has been happy times though, here are a few things I’ve encountered during this experience:</p><ul><li>I’ve had a few issues when I decided to upgrade from Java 8 all the way to 11. After some research, I realized a <a href="https://projectlombok.org/features/configuration"><strong>new configuration file</strong></a> was needed for my project to make Lombok work.</li><li>There have been a few cases where I’ve upgraded my IDE and encountered a few compilation problems. Whenever there is a new version of the <a href="https://itnext.io/top-5-intellijidea-and-android-studio-courses-for-java-and-android-programmers-afcc27309b60">IDE</a>, there’s a chance that there’s a plugin update too. In those cases, my application wouldn’t compile. An upgrade of the plugin is required and it starts working.</li></ul><p>On the other side, a few words of advice:</p><ul><li>You could easily get annotation happy. I’ve been a victim of this. I’ve added @Data everywhere. It might not be a good idea to add this annotation everywhere without realizing everything that you are bringing in to your classes.</li><li>You might be stuck with a Java version for a little bit because Lombok doesn’t have support for a new one yet.</li><li>There are <a href="https://artofcode.wordpress.com/2018/12/18/dont-use-lombok/"><strong>some concerns</strong></a> shared around where some people say that Lombok might not be a good idea for your project due to how it actually is implemented and due to potential compatibility issues.</li></ul><h4>Not so sure if you want to use Lombok?</h4><p>If you are not sure if you want to commit or not to Lombok. IntelliJ currently offers an option to <em>Delombok</em>. To <em>Delombok</em> your application is really to undo all these annotations and convert them to plain Java code.</p><p>Let’s take as an example this code, where we have a no-args constructor, all args constructor, and getters/setters for our properties.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5eb81668997afa8a0cca22f980851b2c/href">https://medium.com/media/5eb81668997afa8a0cca22f980851b2c/href</a></iframe><p>You can <em>Delombok</em> your application by going to the <em>Refactor</em> menu option and clicking on <em>Delombok</em>, followed by <em>All lombok annotations</em>. Doing this will result in your code to look like the following snippet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d6e698a8f83e097ace2bfa848b1c394/href">https://medium.com/media/6d6e698a8f83e097ace2bfa848b1c394/href</a></iframe><p>While I&#39;ve never needed to do this, it is good to know it exists as this is a good backup plan in case one day you no longer want to use Lombok.</p><p>If after all of this, you are feeling uneasy about using Lombok, keep also in mind that some IDEs can autogenerate many of these things for you too. You will just need to maintain this code that gets generated for you and make sure it is always up to date.</p><p>Enjoy!</p><h4>Additional reading resources</h4><ul><li><a href="https://projectlombok.org/">Project Lombok</a></li><li><a href="https://www.oracle.com/corporate/features/project-lombok.html">Project Lombok: Clean, Concise Java Code</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90bcc255ee1f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/how-to-write-less-code-in-java-11-using-lombok-90bcc255ee1f">How to Write Less Code in Java 11 Using Lombok</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reactive Forms in Angular 10 — How to Create a Login Form Using Reactive Forms]]></title>
            <link>https://javascript.plainenglish.io/reactive-forms-in-angular-10-how-to-create-a-login-form-using-reactive-forms-c979e2b86135?source=rss-62c558d0cfb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c979e2b86135</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[reactive-forms]]></category>
            <dc:creator><![CDATA[tech.mia]]></dc:creator>
            <pubDate>Wed, 05 Aug 2020 21:02:45 GMT</pubDate>
            <atom:updated>2020-08-05T21:02:45.601Z</atom:updated>
            <content:encoded><![CDATA[<h3>Reactive Forms in Angular 10 — How to Create a Login Form Using Reactive Forms</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o8eKqQzO-VmNQ-qZq0Hpyg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@mr_williams_photography?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Micah Williams</a> on <a href="https://unsplash.com/s/photos/login?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><strong><em>Reactive forms</em></strong> are an alternative to creating forms in Angular. Most of the heavy lifting for creating reactive forms happens in the component class instead of the template (HTML file).</p><p>One of the big benefits of using reactive forms is that it makes testing easier. The reason for this is that all the code related to your form lives in the component class. Given this, you don’t need to access the template on your tests to test your form. Instead, you can simply write a unit test.</p><p><strong>Module setup</strong></p><p>The first step to implement a reactive form will be to import ReactiveFormsModule to your application’s module. This module can be imported from @angular/forms.</p><p>For simplicity purposes, as part of this example, I’ll be writing all the form related code inside the AppComponent. The following code snippet shows how to include the ReactiveFormsModule for you to start creating your first reactive form.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd8d0f7a835e2b25b46b70a789a78f66/href">https://medium.com/media/dd8d0f7a835e2b25b46b70a789a78f66/href</a></iframe><h4>Creating a reactive form</h4><p>Before we start, there are two important concepts we need to go over: <strong><em>form groups</em></strong> and <strong><em>form controls</em></strong>.</p><p>Each control in your form will be of type FormControl. A form control could represent something like a user&#39;s first name, date of birth, or country of birth. From a user&#39;s perspective, these could be input fields, text areas, or dropdown lists. Form controls keep track of the value, validations, and events in a control. A FormGroup contains a group of form controls.</p><p>For you to add controls to your form, you will first instantiate an object of type FormGroup. When building reactive forms, for you to to create your form, the first step is to create a FormGroup.</p><p>Let’s start by creating the form group. Once you’ve done this, you will need to pass in as a parameter an object where:</p><ul><li>The keys define your control’s names</li><li>The values will be objects of type FormControl</li></ul><p>In this example, if we have a username and password, you will create an object with keys of username and password. As values, you will be providing, for now, new form controls.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd736c5a726ef2e27012970ed6dcf2a6/href">https://medium.com/media/cd736c5a726ef2e27012970ed6dcf2a6/href</a></iframe><p>As your forms become more complex, there is a simpler way of building them by using the FormBuilder class. For this, you can start by injecting the FormBuilder class and calling the group method.</p><p>As a parameter to the group method, you will pass in an object where</p><ul><li>The keys define your control’s names</li><li>The values, for now, are empty arrays</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c67f63b858ff21948f5e82e8fcb12d2/href">https://medium.com/media/5c67f63b858ff21948f5e82e8fcb12d2/href</a></iframe><p>So far we are done with the component class. Let’s go over what needs to be done in the template.</p><p>From your template, you can go ahead and wrap your input fields that represent your form controls in a form tag. Your next step should be to add the formGroup directive to your form tag. As a value to the formGroup directive, pass in the form group you just instantiated on the component class.</p><p>Finally, for each one of your controls, add a formControlName directive. As a value, you will pass in a string with the name your form controls that you used in the component class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c12101413aaeb35899be6a7cf4c3db3c/href">https://medium.com/media/c12101413aaeb35899be6a7cf4c3db3c/href</a></iframe><h4>Form control default values</h4><p>If for some reason, you need to provide default values to your form controls, you can pass these as the first value to the empty arrays on your form controls. If you were to want to set helloworld as the default username in your control, you will need to do the following.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6aa33c96d4ddd5f90c18d384d474327f/href">https://medium.com/media/6aa33c96d4ddd5f90c18d384d474327f/href</a></iframe><h4>Setting default values to form controls</h4><p>Sometimes you are going to need to set default values to your forms. This might be because you have an edit form where the user is going to edit some type of information. The methods `setValue` and `patchValue` will let you update values on your forms. As an argument, you will need to pass in an object. The keys for this object will be the form control names. The values will be the values for each one of your form controls.</p><p>If you want to set only a specific form control, you might want to call patchValue. The patchValue method lets you update one or more fields from your form. Take as an example a form that contains a username and password form controls. In this case, if you want to set only a default value for the username you could do the following.</p><pre>this.form.patchValue({ username: &#39;username&#39; });</pre><p>On the other hand, the setValue method will need you to pass in an object with all the controls for your form. In other words, if you try to only set the username form control, this will result in a runtime error like this one: <em>Must supply a value for form control with name: ‘password’</em>.</p><p>This is an example of the correct usage of the setValue method for this form.</p><pre>this.form.setValue({ <br>  username: &#39;username&#39;,<br>  password: &#39;password&#39;<br>});</pre><h4>Form submission</h4><p>We’ve created so far a form, but we can’t do that much with it until you submit it. The next step will be to add a submit button and retrieve the values for every control.</p><p>To add the submit button, add a button element with a type of submitin the template. After you&#39;ve done this, you are going to want to add an ngSubmit handler on your form tag. As an argument to this handler, you will call a submitForm function you will be creating in your component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8b477fc60389c45b0e9a0ca38a3d1d5/href">https://medium.com/media/e8b477fc60389c45b0e9a0ca38a3d1d5/href</a></iframe><p>In your component class, you will now implement the submitForm function. It is important to mention that you can give any name to this function.</p><p>Inside this function, you are going to retrieve the value of your form controls by calling this.form.getRawValue().</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ca63cd0995ad3923fae15e180792351/href">https://medium.com/media/4ca63cd0995ad3923fae15e180792351/href</a></iframe><p>The getRawValue method call will return an object where the key is the name of the control and the value is the form control&#39;s value. As an example, if for username the user entered helloworld and password for the password, this object will look like this:</p><pre>{<br>  username: &quot;helloworld&quot;,<br>  password: &quot;password&quot;<br>}</pre><h4>Validating form controls</h4><p>Validators are functions that let you add validations to each one of your form controls. These validations can be something as simple as making a field on your form required or verifying the user entered valid e-mail address.</p><p>While you can create your validators, Angular provides a few validators out of the box. These are a few of the validators provided by Angular:</p><ul><li>RequiredValidator- Validates that a form control has a value and marks it as required</li><li>EmailValidator - Validates that a form control has a valid e-mail address</li><li>MinLengthValidator - Validates that the length of the text in a form control is greater than or equal to the value</li><li>MaxLengthValidator - Validates that the length of the text in a form control is less than or equal to the value</li><li>MaxValidator - Validates that a number in a form control is less than or equal to the value</li><li>MinValidator - Validates that a number in a form control is larger than the min or equal to the value</li><li>PatternValidator - Validates that text in a form control matches a specific regular expression</li></ul><p>For you to add a validator, you will need to add it as part of the form control’s initialization. All validators offered by Angular can be imported from the Validators class in @angular/forms.</p><p>Let’s say we are going to make the username and password fields to be required. For this, we&#39;ll be using the RequiredValidator, and we&#39;ll be adding Validators.required to both controls as a second value to the form control’s array.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9206565e7a54d5a0619a7ba14d04a3d5/href">https://medium.com/media/9206565e7a54d5a0619a7ba14d04a3d5/href</a></iframe><p>If you want to add multiple validators to your form control, you’ll need to pass them inside an array as the second value to the form control’s value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36a9c3bc845f515ae5cac4fbd78459c5/href">https://medium.com/media/36a9c3bc845f515ae5cac4fbd78459c5/href</a></iframe><h4>Custom validators</h4><p>As you have seen, Angular provides a pretty good set of default validators for your forms. The big question is, what if you need your own validator. Good news, this is something pretty simple to do.</p><p>Let’s say you want to have a validator that validates that a password is not the word password. For you to create your custom validator, you will have to create a function that verifies this. As an argument, you will take in an object of type FormControl. Next, you will get the value from your form control and return an error if one exists.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93ab0b499328072763d99ceb2e8954f0/href">https://medium.com/media/93ab0b499328072763d99ceb2e8954f0/href</a></iframe><p>The next step will be for you to consume this custom validator on your form control. For you to do this, you will just add it to your list of validators when building the FormGroup.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d46fba936c7ac913e4cc1c980ca35d41/href">https://medium.com/media/d46fba936c7ac913e4cc1c980ca35d41/href</a></iframe><h4>Verify a form is valid</h4><p>So far you have a form control and have added a validator to it. The next step will be to verify that the form is valid by the time a user clicks on the submit button.</p><p>It is quite simple to do this, you only need to get the value from the valid property inside your form group. In this case, inside your submitForm method, you can do a conditional statement where you verify if this.form.valid is true, then you move forward and do some other type of action with this data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c75fb6ecc31475a26faafdc4c319631d/href">https://medium.com/media/c75fb6ecc31475a26faafdc4c319631d/href</a></iframe><h4>Disabling submit button</h4><p>Depending on your application’s requirements, under certain conditions, you might want to disable the submit button of your form.</p><p>A typical use case for this is that you want to disable the submit button when the form is not in a valid state. For this, you can add the disabled attribute to your submit button. As a value, you will pass in !form.valid to disable it only when the form is not valid.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2a2eb5ba9c6bb66ddbb001490e0badd/href">https://medium.com/media/b2a2eb5ba9c6bb66ddbb001490e0badd/href</a></iframe><h4>Displaying errors</h4><p>For you to display errors on the template, you will need to get the form control from the form first. For you to do this, on your template you need to call form.get(&#39;formControlName&#39;), where formControlName is the name of your control.</p><p>In this case, we’ll be adding this validation for the username control. After doing this, you can call the hasError method, where you will pass in the name of the error. Whenever you use Validators.required, the error name will be required. The hasError method will return a boolean value.</p><p>Given this, you can use the *ngIf structural directive in your template to determine if you want to display an error message or not.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bff1c2647e8c5e23b16634d35d6660d1/href">https://medium.com/media/bff1c2647e8c5e23b16634d35d6660d1/href</a></iframe><h4>Form States</h4><p>Angular forms and their controls can have different states such as:<br>- <strong><em>Pristine</em></strong>: User has not changed the values of the form control<br>- <strong><em>Dirty</em></strong>: Opposite of pristine<br>- <strong><em>Touched</em></strong>: User has visited the form control and exited it<br>- <strong><em>Untouched</em></strong>: Opposite of touched</p><p>These states help you enhance the way your forms behave. As an example, you wouldn’t want to show an error message if the username has not entered by the user.</p><p>One option is that you might consider displaying an error when the user clicks on the submit button without doing anything to the form. Additionally, you might want to only show the error message if the user <strong><em>touched</em></strong> the form control.</p><p>The reason for this is that it might be annoying for your users to land on a form full of errors. By default when the form loads, it might not have a username. A friendlier approach will be to display the error only if the user has interacted with the form controls.</p><p>For you to retrieve the state of your form controls, you’ll need to first get your form control usingform.get(&#39;formControlName&#39;). After doing this, you can call any of the following boolean properties on your form control.</p><ul><li>dirty</li><li>pristine</li><li>touched</li><li>untouched</li></ul><p>Let’s go over a few scenarios to get a better idea of how form states work in Angular.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jin7WHdKFeU8IOHc6Mb1wg.png" /><figcaption>Form States Scenario #1 — User enters a value on form control</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n2qj05YZ9Sy6TdqhuBhUoQ.png" /><figcaption>Form States Scenario #2 — User enters a value and erases it from form control</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c_0OB3lEyK8EHbsecdhBIg.png" /><figcaption>Form States Scenario #3 — User visits form control without entering a value</figcaption></figure><p>As you can see in the following example, we added an *ngIf where we conditionally display the error message. If the error exists and if the form control is dirty, then we show an error message to the user.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af71724b27e1dc4d805b4dd2ecdeb2b7/href">https://medium.com/media/af71724b27e1dc4d805b4dd2ecdeb2b7/href</a></iframe><p>I hope this post helps you get a better idea of how to get started with Angular Reactive Forms. Enjoy!</p><h4>JavaScript In Plain English</h4><p>Enjoyed this article? If so, get more similar content by <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>subscribing to Decoded, our YouTube channel</strong></a><strong>!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c979e2b86135" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/reactive-forms-in-angular-10-how-to-create-a-login-form-using-reactive-forms-c979e2b86135">Reactive Forms in Angular 10 — How to Create a Login Form Using Reactive Forms</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Software Design Patterns — Decorator Pattern]]></title>
            <link>https://blog.devgenius.io/design-patterns-decorator-design-pattern-332e7870a5c5?source=rss-62c558d0cfb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/332e7870a5c5</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[decorator-pattern]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[tech.mia]]></dc:creator>
            <pubDate>Wed, 22 Jul 2020 18:54:12 GMT</pubDate>
            <atom:updated>2020-08-01T13:24:49.973Z</atom:updated>
            <content:encoded><![CDATA[<h3>Software Design Patterns — Decorator Pattern</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RTP9_9ytPYO-AVy7KIM9DA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@icons8">Icons8 Team</a></figcaption></figure><h4>Introduction</h4><p>The decorator design pattern is a software design pattern that helps you add responsibilities to an object at runtime. This pattern is considered to be a structural design pattern. This type of pattern focuses on the relationships between classes and how they can help solve specific problems.</p><p>The Gang of Four, in their book <a href="https://en.wikipedia.org/wiki/Design_Patterns">Design Patterns: Elements of Reusable Object-Oriented Software</a>, defined the intent of decorator pattern like this:</p><blockquote><strong>Intent:</strong> Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.</blockquote><p>One of the key characteristics of this design pattern is that it follows the <em>Single Responsibility Principle (SRP)</em>. This is because each “decoration” you add to an object, will be encapsulated within a class. This class’s responsibility will be to handle everything related to adding that decoration to that object.</p><h4>Time to assemble a 🍔</h4><p>For purposes of learning the decorator pattern, let’s assume you want to create an object of type Hamburger.</p><p>How a hamburger is assembled varies. According to Burger King, there are <a href="https://en.wikipedia.org/wiki/Whopper">221,184 possible ways to order a Whopper</a>. It will take you at least 200 years to eat these many hamburgers if you were to eat one hamburger for breakfast, lunch, and dinner! The possibilities are endless.</p><p>In a world without the decorator pattern, an approach you might take is to create a parent Hamburger class and then subclasses for the different types of hamburgers. This could easily become a maintenance headache as it will make troubleshooting more difficult due to the complexity of multiple levels of inheritance.</p><h4>The Pattern</h4><p>In a scenario like this one is where the decorator pattern becomes handy. The first step is to <em>define a contract</em>. You need to be able to answer the question. When assembling a hamburger, what are the things you need a hamburger object to be able to do?</p><ul><li>Add toppings</li><li>Add condiments</li><li>Retrieve the total number of calories</li><li>Retrieve total cost</li></ul><p>You will have an interface with what the contract for aHamburger is. Everything a hamburger has, this parent class will have it. Every new element you add to it will end up being its own class.</p><p>After this… at runtime, you will start adding more elements to it. Need a hamburger with tomatoes? Just add tomatoes at runtime!</p><p>For you to implement this pattern, we need to go over what are the classes and interfaces required for you to implement the decorator design pattern.</p><p>1 — <strong>Interface</strong> — The first thing will be to create an interface that defines the contract for the objects you will be creating. If we follow the example of a hamburger, think about what a hamburger interface needs to expose to other classes. In this case, maybe we need to expose what are the toppings we’ve added or what is the total number of calories.</p><p>2 — <strong>Plain class implementing the interface</strong> — This class will end up implementing all the methods from interface. It will represent a plain hamburger. If you create a plain hamburger, what should it have? You will most likely need to start with bread only. Everything else will be considered toppings.</p><p>3 — <strong>Decorator abstract class</strong> — This abstract class implements the interface too. It will take care of taking as an argument in its constructor the plain hamburger object. This class will act as a proxy, it will end up delegating the function calls to the plain hamburger.</p><p>4 — <strong>Decorations extending the decorator</strong> — Each type of new decoration you want to add to your object, will need a new class. In our example, we will be creating one class for adding lettuce, one for tomato, and so on.</p><p>Now that you know what are all the classes and interfaces that are needed for the decorator pattern, you can go ahead and implement these. The following diagram contains a representation of the classes you will need to implement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xoh5or_Uj4jXWiouAVXwzQ.png" /><figcaption>Decorator Pattern Diagram</figcaption></figure><h4>How to implement it</h4><p>You will start first by creating an interface that defines the definition of your object. If you have a hamburger, what do you need? toppings and calories?</p><pre>public interface Hamburger {<br>    List&lt;String&gt; getToppings();<br>    double getTotalCalories();<br>}</pre><p>Once you’ve done this, you should proceed with implementing the class for the plain hamburger. As mentioned before, it will only have bread.</p><pre>public class PlainHamburger implements Hamburger {<br>    @Override<br>    public List&lt;String&gt; getToppings() {<br>        List&lt;String&gt; toppings = new ArrayList&lt;&gt;();<br>        toppings.add(&quot;Bread&quot;);<br>        return toppings;<br>    }<br>        <br>    @Override<br>    public double getTotalCalories() {<br>        return 100.0;<br>    }<br>}</pre><p>The next step will be to create your decorator class. As mentioned before, this class will take as an argument in its constructor the plain hamburger. It will then delegate all calls to this object.</p><pre>public abstract class HamburgerDecorator implements Hamburger {<br>    private Hamburger h;<br>    <br>    public HamburgerDecorator(Hamburger h){<br>        this.h = h;<br>    }<br>    <br>    @Override<br>    public List&lt;String&gt; getToppings() {<br>        return this.h.getToppings();<br>    }<br>        <br>    @Override<br>    public double getTotalCalories() {<br>        return this.h.getTotalCalories();<br>    }<br>}</pre><p>Once you are done with the decorator class, it is time to implement your topping classes.</p><pre>public class HamburgerWithLettuce extends HamburgerDecorator {<br>    public HamburgerWithLettuce(Hamburger h) {<br>        super(h);<br>    }</pre><pre>    @Override<br>    public List&lt;String&gt; getToppings() {<br>        List&lt;String&gt; toppings = super.getToppings();<br>        toppings.add(&quot;Lettuce&quot;);<br>        return toppings;<br>    }</pre><pre>    @Override<br>    public double getTotalCalories() {<br>        return 25.0 + super.getTotalCalories();<br>    }<br>}</pre><p>Now, let’s visit how it will look like from a consumer perspective to assemble your hamburger. You will start by creating an object of type PlainHamburger. After you do this, you will now create an object of type HamburgerWithLettuce and pass in as an argument your plain hamburger.</p><pre>Hamburger plainHamburger = new PlainHamburger();<br>Hamburger withLettuce = new HamburgerWithLettuce(plainHamburger);</pre><p>You should now be able to extend your hamburger assembling by adding more classes that represent each one of the toppings you want to add to your hamburger. Easy enough right? Something to keep in mind now is that for each topping there will be a class, therefore more code to maintain. As with everything there are pros and cons that you should evaluate. Enjoy!</p><h4>Resources</h4><p><a href="https://en.wikipedia.org/wiki/Design_Patterns">Gamma, Erich. Design Patterns: Elements of Reusable Object-Oriented Software (Adobe Reader). Pearson Education.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=332e7870a5c5" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/design-patterns-decorator-design-pattern-332e7870a5c5">Software Design Patterns — Decorator Pattern</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Server-side rendering (SSR) in Angular applications]]></title>
            <link>https://javascript.plainenglish.io/server-side-rendering-ssr-in-angular-applications-f3f141e44ebf?source=rss-62c558d0cfb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3f141e44ebf</guid>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[tech.mia]]></dc:creator>
            <pubDate>Mon, 13 Jul 2020 17:42:31 GMT</pubDate>
            <atom:updated>2020-07-13T17:42:31.110Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_heXqQ9V1rUdtKeNilQXtw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@tvick">Taylor Vick</a></figcaption></figure><h4>Server-side rendering and Client-side rendering</h4><p>Angular applications by default rely on the browser to compile all the code. Even though this is the behavior, there is a way to change this. You can change your application to compile on a server instead of the client’s browser.</p><p>This discussion comes down to client-side rendering (CSR) vs server-side rendering (SSR). In this article, I’ll be going over what SSR and CSR are, their pros and cons, and how to convert your application to do SSR.</p><p>In simple terms, CSR relies on the client’s browser to compile the code. On the other hand, SSR relies on a server to compile the code which then gets returned already compiled to the client.</p><p>It is well known that there is no perfect solution for any problem in software development. As it is with everything else, there are pros and cons to these two options.</p><h4>Let’s start with an example</h4><p>First, start by creating an Angular application. You can do this by running the following command ng init my-application.</p><p>After this, start your application by running npm run start.</p><p>If you open an instance of your terminal and run curl http://localhost:4200, you will end up retrieving something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WpTJrbfOtvUCx8aFRe9B0w.png" /></figure><p>What is wrong with this? Nothing. If you take a look, you will notice that there’s only &lt;app-root&gt; and nothing inside it. But your page does have other contents, correct? Where is the rest?</p><p>If you were to go to a browser and access this page, you will see something completely different. As you can see, you do see the contents of your app-root component. This is because the browser was the one that compiled your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*tkpZnjsghYStfTfPiCq2YQ.png" /></figure><p>Some developers might leverage Angular’s APIs for SEO optimization too. For example, you could set meta or title tags programmatically. In the following example, you can set the title and a few meta tags for this page.</p><pre>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.css&#39;]<br>})<br>export class AppComponent {<br>  constructor(<br>    private readonly titleService: Title,<br>    private readonly meta: Meta) {<br>      this.meta.addTag({ name: &#39;description&#39;, content: &#39;My description&#39; });<br>      this.meta.addTag({ name: &#39;author&#39;, content: &#39;author name&#39; });<br>      this.meta.addTag({ name: &#39;keywords&#39;, content: &#39;Angular, SSR&#39; });<br>      this.titleService.setTitle(&#39;My App!&#39;);<br>  }<br>}</pre><p>If you run curl http://localhost:4200 this page, you will retrieve the following, again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WpTJrbfOtvUCx8aFRe9B0w.png" /></figure><p>On the other hand, inspecting the DOM from the browser will end up containing all the content from your application. This includes the meta and title tags you added in your app-root component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*RcuZhx9W6K3s_AuTyShtkw.png" /></figure><p>As you can see, the browser is a key player in this process to be able to compile your Angular code.</p><h4>Pros and cons of SSR</h4><p>Because the code compiles in the server, this is a win for low performing devices. Servers can do all the hard work so that your user’s devices don’t have to.</p><p>The other big winner with this approach is Search Engine Optimization (SEO). When search engines crawl your website, all the contents of your page will come in on that first load. SEO works better with SSR.</p><p>On the other hand, if you expect spikes of high traffic on your server, you can end up needing a more performant one. This could end up resulting in higher costs, or, if you didn’t account for these spikes, on a low performing server.</p><p>Because you now had to add code to enable your page to do SSR, you will have higher complexity on your codebase. Additionally, this results in a larger codebase.</p><h4>Pros and cons of CSR</h4><p>CSR, for its cons, will have the opposite of benefits of SSR. It isn’t SEO friendly and poor performing devices won’t benefit from it as they will have to do all the hard work for compiling your page.</p><p>Regarding the benefits of CSR, there will be less complexity on your application as you don’t need more code for this. In addition to this, there is more room for reusability on your frontend code when using CSR. The reason for this is because if you have a few JavaScript files that are shared across components, these will be cached on the browser.</p><h4>Convert Angular applications to do SSR</h4><p>Let’s go over the steps required to convert your application to do server-side rendering. This is a very simple process. As of Angular 10, you will just need to run the following command.</p><pre>ng add @nguniversal/express-engine</pre><p>After you’ve run this command, you will see that a few files were generated as part of this. If you go to package.json, you will see that there are new scripts added. These scripts are dev:ssr, serve:ssr, build:ssr, and prerender.</p><p>If you want to build and run your application, run npm run dev:ssr. Your application will be running on port 4200.</p><p>If you run on the terminal curl http://localhost:4200, you will now see the contents of your page as if you were inspecting from the browser. Server-side rendering to the rescue here!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UERsR-arHtnhKu4UoxEweQ.png" /></figure><p>Now that your application can do server-side rendering, you can take advantage of all the benefits that it now brings to your application.</p><p>Based on my personal experience, I’ve noticed better SEO results on the applications I’ve changed to do SSR. But, at the same time, I have experienced additional server costs to have a performant web application.</p><p>Hope that this article helps you get a clear idea of the pros and cons of CSR and SSR. Enjoy!</p><h4>Resources</h4><p><a href="https://angular.io/guide/universal">Angular</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3f141e44ebf" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/server-side-rendering-ssr-in-angular-applications-f3f141e44ebf">Server-side rendering (SSR) in Angular applications</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CI/CD — Automating your development workflow with GitHub Actions]]></title>
            <link>https://blog.devgenius.io/github-actions-basics-aa553e04fd5c?source=rss-62c558d0cfb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa553e04fd5c</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[continuous-deployment]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <dc:creator><![CDATA[tech.mia]]></dc:creator>
            <pubDate>Fri, 10 Jul 2020 07:26:05 GMT</pubDate>
            <atom:updated>2021-02-21T20:10:05.044Z</atom:updated>
            <content:encoded><![CDATA[<h3>Automating your development workflow with GitHub Actions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IGPpohYNfISFaKPqd-1R2A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jamesponddotco">James Pond</a></figcaption></figure><h4>What is it? And why would you need it?</h4><p>You might be familiar with CI tools such as TeamCity, Jenkins, Concourse, Travis CI to mention a few. Well, this time we’ve got a new neighbor in town.</p><p>This new neighbor offers new capabilities to automating your workflows: <a href="https://github.com/features/actions">GitHub Actions</a>.</p><p>GitHub Actions provides different ways to automate development tasks. Some of the things you could do are:</p><ul><li>Build your applications and run tests on every code check-in</li><li>Deploy your application to your production servers</li><li>Perform different types of automated tasks when a pull request is created</li><li>Monitor the health of your application at a defined time interval</li></ul><p>These are just a few ideas, but as you can see, possibilities are endless….</p><p>In this article, I’ll be going over how you create a workflow to build your application.</p><h4>Workflows, events, and a cup of coffee!</h4><p>The first step will be to create a GitHub workflow file at the root of your project under .github/workflows. You will need to create a YAML file inside this path.</p><p>Once you’ve created your workflow file, you can go ahead and start by adding a name using the name property.</p><pre>name: my-application</pre><p>GitHub Actions is not your regular CI tool… it is very powerful as your actions can get triggered by different types of events. I’ll start with the most common one, which is when pushing to a branch.</p><p>First, start by adding the on property inside your workflow file. Because we are going to want this to trigger once you push to a branch, we&#39;ll add the push property.</p><p>Next step? Specify what branches you want to trigger this action on. You can provide specific names such as master or provide wildcards such as feature/**. The feature/** wildcard will cover any branches that start with feature/.</p><pre>name: my-project</pre><pre>on:<br>  push:<br>    branches:<br>      - master<br>      - &#39;feature/**&#39;</pre><p>Another event that can trigger this workflow could be when you push to a pull request. In this case, you will end up using the pull_request property instead of push.</p><pre>name: my-project</pre><pre>on:<br>  pull_request:<br>    branches:<br>      - master<br>      - &#39;feature/**&#39;</pre><p>You can create actions when someone comments on an issue, a release is published, an issue is opened and even you can schedule cronjobs. For these and more events you can visit this <a href="https://docs.github.com/en/actions/reference/events-that-trigger-workflows">page</a>.</p><p>So far your workflow has a name and an event, now… there are three more things to learn about… jobs, steps, and runners.</p><h4>Runners and jobs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7egUJ4EIaT6v_1kT2ksVkw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@bruno_nascimento">Bruno Nascimento</a></figcaption></figure><p>The next step will be to create what are known as jobs. Jobs contain multiple steps and they are executed inside what is known as a runner.</p><blockquote>“A runner picks up a job and it runs the job’s actions and reports the progress, logs, and final results back to GitHub.”</blockquote><p>Now that I’ve gone over some of the required terminologies, let’s go over how we create jobs.</p><p>For you to create a job, you will need to add the job property and provide a name to your job. Once you&#39;ve done this, you will need to specify what operating system you need. For this, you&#39;ll be adding the runs-on property after your job&#39;s name. You will now need to specify the operating system and the version. Some valid values here could be ubuntu-latest, ubuntu-18.04, windows-latest or macos-10.15.</p><pre>name: my-project</pre><pre>on:<br>  push:<br>    branches:<br>      - master<br>      - &#39;feature/**&#39;</pre><pre>jobs:<br>  my-application:<br>    runs-on: ubuntu-18.04</pre><p>You must go over the pricing for the different operating systems as they can significantly vary amongst these. You can verify for more information on the prices <em>here</em>.</p><h4>Next stop: Steps!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Pns7OMKhg8jcS8W-Y5kLw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@fabster74">Fabian Fauth</a></figcaption></figure><p>A step is an individual command you run on your action. This action could be running tests or building your application. You can add one or more steps to your job. Your first step will be to add the steps array property to your job. You should add a name and an id to your job. The name will be what displays on the UI when it is running the job. The id will help you refer to any output that comes from this step on other steps.</p><p>If you add the run property and add a pipe | you will be able to run all your commands on the next lines. In this case, the</p><pre>name: my-project</pre><pre>on:<br>  push:<br>    branches:<br>      - master<br>      - &#39;feature/**&#39;</pre><pre>jobs:<br>  my-application:<br>    runs-on: ubuntu-18.04<br>    steps:<br>      - name: build<br>        id: build<br>        run: |<br>          echo &quot;Building application...!&quot;<br>          sh scripts/build-app.sh</pre><h4>The last one: Checking out your code and specifying your runtime</h4><p>So far if you’ve followed the steps above, you might not have a working solution. The reason for this is because you need to check out your code. For you to do this, you just need to add another step, called actions/checkout@v2.</p><pre>- uses: actions/checkout@v2</pre><p>In addition to this, you are going to need the runtime of the program you are building. Let’s assume your program needs node. In this case, you will need another step after checking out the code where you bring in the version of node you want. Doing this is simple… Just provide a name to the step and use actions/setup-node@v1 and you can specify the node version in the node-version property.</p><pre>- name: Node &#39;12.15&#39;<br>  uses: actions/setup-node@v1<br>  with:<br>    node-version: &#39;12.15&#39;</pre><p>If you were to be working on an application that uses Java, you could have brought in Java using the actions/setup-java@v1 and specifying the version on the java-version attribute.</p><pre>- name: Java Version 11<br>  uses: actions/setup-java@v1<br>  with:<br>    java-version: 11</pre><p>Finally, your workflow file should look like this.</p><pre>name: my-project</pre><pre>on:<br>  push:<br>    branches:<br>      - master<br>      - &#39;feature/**&#39;</pre><pre>jobs:<br>  my-application:<br>    runs-on: ubuntu-18.04<br>    steps:<br>      - uses: actions/checkout@v2<br>      - name: Node &#39;12.15&#39;<br>        uses: actions/setup-node@v1<br>        with:<br>          node-version: &#39;12.15&#39;<br>      - name: build<br>        id: build<br>        run: |<br>          echo &quot;Building application...!&quot;<br>          sh scripts/build-app.sh</pre><p>By now, you should have your application being built every time you check in code to the master or feature branches for your project. If you get any invalid syntax issues, feel free to use a YAML linter online such as <a href="http://www.yamllint.com/">this one</a>. This will help identify any small issues you’ve had related to formatting or spacing.</p><p>I hope that this article helped provide you an overview of what GitHub Actions is and how to create a very simple workflow to build your application. Enjoy!</p><h4>References</h4><ul><li><a href="https://docs.github.com/en/actions/getting-started-with-github-actions/core-concepts-for-github-actions">Core concepts for GitHub Actions</a></li><li><a href="https://docs.github.com/en/actions/reference/workflow-syntax-for-github-actions#jobsjob_idruns-on">Workflow syntax for GitHub Actions - GitHub Docs</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa553e04fd5c" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/github-actions-basics-aa553e04fd5c">CI/CD — Automating your development workflow with GitHub Actions</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Stream API — int, long and double operations]]></title>
            <link>https://blog.devgenius.io/java-stream-api-int-double-and-long-operations-e1743ce2d77a?source=rss-62c558d0cfb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1743ce2d77a</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[stream]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[tech.mia]]></dc:creator>
            <pubDate>Thu, 25 Jun 2020 12:56:17 GMT</pubDate>
            <atom:updated>2020-07-05T15:46:09.482Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java Stream API — int, long and double operations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*esfEJ9dwHOyCf7l2j6OpWg.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@nick-bondarev?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">ArtHouse Studio</a> from <a href="https://www.pexels.com/photo/rocky-shore-of-mountain-river-in-fog-4337894/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>If you were to have to do the sum of integer values inside a stream of objects, you will consider a few options such as leveraging the reduce stream function. Or… the most known one: loop through all the objects and keep a variable with the running sum of values</p><p>The Stream API offers a very simple way of calculating sum, finding min or max, and calculating the average for a stream of objects.</p><p>Depending on your numeric data type (int, double or long) you might need to use IntStream, DoubleStream or LongStream. I’ll focus only on the IntStream class given that everything is very similar across the three different data types.</p><p>According to Java’s documentation, an IntStream is defined as</p><blockquote>A sequence of primitive int-valued elements supporting sequential and parallel aggregate operations. This is the int primitive specialization of Stream.</blockquote><h4>How to build an IntStream?</h4><p>You have two ways of building an IntStream. You can build an IntStream by using the builder method from the IntStream</p><pre>IntStream<br>    .builder()<br>    .add(1)<br>    .add(3)<br>    .build();</pre><p>You can also build a new IntStream by using an existing stream and map it to an IntStream. You can achieve this by calling the mapToInt function.</p><pre>IntStream intStream = cars<br>  .stream()<br>  .mapToInt(car -&gt; car.getNumberOfSeats());</pre><p>If you were to use a DoubleStream or a LongStream, the methods will be mapToDouble and mapToLong.</p><h4>What can I do with an IntStream?</h4><p>Once you&#39;ve built an IntStream, you have the option of calling one of these methods: <br>1 - sum <br>2 - min <br>3 - max <br>4 - average <br>5 - count</p><p>The names are pretty self-explanatory. These methods let you add, get the minimum value, get the maximum value, calculate the average, or count the number of elements in a stream.</p><p>Assuming you need to get the average value of all the integers in a stream, you could easily do something like this:</p><pre>cars<br>    .stream()<br>    .mapToInt(car -&gt; car.getNumberOfSeats())<br>    .average();</pre><p>One big benefit of doing this is that it now simplifies your coding to perform this action and underneath the hood, it takes care of little things that you can easily miss such as handling scenarios for dividing by zero when calculating the average for an empty stream.</p><p>It is important to point out that the average method will not return a double, it will return an object of type OptionalDouble. The OptionalDouble class offers a similar interface to the one from the Optional class.</p><p>If you want to extract the value for the result of the average, you need to call the getAsDouble() method. The only problem with this might be, what happens if the stream is empty and there’s no average? Your code might end up throwing an exception.</p><p>A simple alternative to this might be to call the isPresent() method on your optional object, and if the returns true, then call getAsDouble().</p><pre>OptionalDouble optionalAverage = Stream<br>        .<em>of</em>(1, 2, 3)<br>        .mapToInt(car -&gt; car)<br>        .average();</pre><pre>if (optionalAverage.isPresent()) {<br>    double average = optionalAverage.getAsDouble();<br>}</pre><p>As you might have figured out by now, not all of the other methods will return an int. Let’s quickly go over all of their return types</p><p>1 - sum — Returns an int. If there are no elements will return zero.<br>2 - min — Returns an OptionalInt. Verify using isPresent() first, then call getAsInt().<br>3 - min — Returns an OptionalInt. Verify using isPresent() first, then call getAsInt().<br>4 - average — Returns an OptionalDouble. Verify using isPresent() first, then call getAsDouble().<br>5 - count — Returns a long.</p><h4>Summary statistics</h4><p>Once you’ve built an IntStream, you can now retrieve an object of type IntSummaryStatistics. This object will give you access to the sum, min, max, count, and average.</p><p>You might ask, what is the benefit of this when you have direct access through the IntStream class to retrieve all of this information. One of the benefits from the IntSummaryStatistics class comes in when combining it with other data’s summary statistics.</p><p>Let’s evaluate this by looking at this example where we have initially two lists, one called suvs and another one called sedans. We will map both to an IntStream based on the value of the property numberOfSeats from these objects.</p><pre>IntSummaryStatistics statisticsForSUVs = suvs.stream()<br>    .mapToInt(x -&gt; x.getNumberOfSeats())<br>    .summaryStatistics();</pre><pre>IntSummaryStatistics statisticsForSedans = sedans.stream()<br>    .mapToInt(x -&gt; x.getNumberOfSeats())<br>    .summaryStatistics();</pre><p>After we’ve done this, you will be now able to combine the results from these two IntSummaryStatistics with minimal effort and get the combined statistics for these.</p><p>By you invoking now the combine method, it will combine both statistics into a single one and compute all of these statistics for you automatically. Your average now is for the combined statistics, same for min, max, sum and count.</p><pre>statisticsForSedans.combine(statisticsForSUVs);</pre><p>I hope that after reading this article you’ve been able to gather a better understanding of how you can leverage the Stream API to perform mathematical operations on your numeric streams.</p><p>Enjoy!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1743ce2d77a" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/java-stream-api-int-double-and-long-operations-e1743ce2d77a">Java Stream API — int, long and double operations</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>