<?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 Alex Therrien on Medium]]></title>
        <description><![CDATA[Stories by Alex Therrien on Medium]]></description>
        <link>https://medium.com/@alexandre.therrien3?source=rss-d1484e3301ff------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*kaSYCkBIMscFPRgj.jpg</url>
            <title>Stories by Alex Therrien on Medium</title>
            <link>https://medium.com/@alexandre.therrien3?source=rss-d1484e3301ff------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 17:38:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alexandre.therrien3/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[Docker Compose for Integration Testing: A Practical Guide for Any Project]]></title>
            <link>https://medium.com/@alexandre.therrien3/docker-compose-for-integration-testing-a-practical-guide-for-any-project-49b361a52f8c?source=rss-d1484e3301ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/49b361a52f8c</guid>
            <category><![CDATA[integration-testing]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[docker-compose]]></category>
            <dc:creator><![CDATA[Alex Therrien]]></dc:creator>
            <pubDate>Fri, 26 Dec 2025 13:37:24 GMT</pubDate>
            <atom:updated>2025-12-26T13:37:24.182Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uPjc5_cJuJlD9TbR1VYNyQ.jpeg" /></figure><p>Running reliable integration tests often means dealing with complex environments: databases, migrations, seed data, and machine-specific configurations. Recently, I decided to move my integration tests entirely into Docker to make the testing environment fully reproducible and independent of my local machine setup.</p><p>While the concrete example in this article uses <strong>NestJS</strong>, the concepts and patterns described here are applicable to <strong>any backend project</strong>. The goal is not framework-specific magic, but a repeatable and clean integration testing setup using <strong>Docker Compose</strong>.</p><h3>Prerequisites</h3><p>Before diving in, you should be comfortable with the basics of Docker:</p><ul><li>How Docker images are built</li><li>The purpose of a Dockerfile</li><li>How containers differ from images</li></ul><p>I strongly recommend reading my earlier article before continuing:</p><p><strong>Dockerfile Checklist</strong>:<br> <a href="https://alexandre-therrien-it.dev/articles/dockerfileChecklist">https://alexandre-therrien-it.dev/articles/dockerfileChecklist</a></p><p>That article covers the basics for writing Dockerfiles, which will make this tutorial much easier to follow.</p><h3>Why Docker Compose for Integration Tests?</h3><p>The main motivation was <strong>environment independence</strong>.</p><p>I needed:</p><ul><li>A database that could be safely reset on every test run</li><li>A setup that didn’t interfere with any local databases</li><li>A repeatable workflow that works the same for every developer and in CI</li></ul><p>If I were using a local database filled with test data, wiping it on every integration test run would be unacceptable: I wouldn’t want to reset some added temporary test data every time. Docker Compose solves this by allowing us to spin up <strong>isolated services</strong> specifically for testing.</p><p>In this setup:</p><ul><li>One container runs the database</li><li>Another container runs the application and executes the tests</li><li>Everything is created, destroyed, and recreated as needed</li></ul><h3>Key Lessons Learned from Using Docker Compose</h3><p>Beyond Dockerfile fundamentals, here are a few important behaviors that are easy to overlook:</p><ul><li><strong>Docker images do not rebuild automatically</strong><br> Files copied using COPY are frozen at build time. If you change them locally, they won’t update in the container unless you rebuild the image.</li><li><strong>Docker Compose volumes control synchronization</strong><br> You can choose which folders are synced live with the container using volumes, and which ones remain static inside the image.</li><li><strong>The </strong><strong>CMD instruction always runs</strong><br> Docker recommends having only one CMD. You <em>can</em> chain commands using &amp;&amp;, which is exactly what we’ll do for our test workflow.</li></ul><h3>High-Level Architecture</h3><p>The approach is straightforward:</p><ol><li>Use a <strong>PostgreSQL image from Docker Hub</strong> as one container</li><li>Create a second container for the application</li><li>Let the application container:<br>3.1. Reset the database<br>3.2. Run migrations<br>3.3. Seed test data<br>3.4. Execute integration tests</li></ol><p>Docker Compose orchestrates everything and ensures services start in the correct order.</p><h3>The Application Dockerfile</h3><p>This Dockerfile is dedicated to integration testing and lives at:</p><pre>test/setup/app/Dockerfile</pre><p>Here is the script:</p><pre>FROM node:20-alpine AS deps<br>WORKDIR /app<br><br># Copy package files<br>COPY package.json pnpm-lock.yaml ./<br>COPY prisma ./prisma/<br><br># Copy app<br>COPY src ./src/<br><br># Copy tests<br>COPY test ./test/<br><br># Copy environment test as .env in container<br>COPY .env.test ./.env<br><br># Copy tsconfig<br>COPY tsconfig.json ./tsconfig.json<br><br># Install pnpm and tsx (for seed)<br>RUN npm install -g pnpm@9<br>RUN npm install -g tsx<br><br># Install dependencies<br>RUN pnpm install<br><br># Build project<br>RUN pnpm run build<br><br>EXPOSE 3000<br><br># Setup DB. Needs to happen once instance is started (otherwise don&#39;t have access to postgresql container)<br>CMD [&quot;sh&quot;, &quot;-c&quot;, &quot;pnpm db:reset &amp;&amp; pnpm db:generate &amp;&amp; pnpm db:migrate &amp;&amp; pnpm db:seed &amp;&amp; pnpm db:seed-test &amp;&amp; pnpm test:e2e&quot;]</pre><h3>What This Dockerfile Does</h3><p>In simple terms, it:</p><ul><li>Copies all required application and test files</li><li>Installs dependencies</li><li>Builds the project</li><li>Exposes the application port</li><li>Executes a chained command that:<br>1. Resets the database<br>2. Generates Prisma artifacts<br>3. Runs migrations<br>4. Seeds base data<br>5. Seeds test-specific data<br>6. Executes end-to-end tests</li></ul><p>The database-related commands must run <strong>after</strong> the database container is available, which is handled by Docker Compose. This explains why we cannot execute the database-related commands with a RUN instruction.</p><h3>Database Connection Configuration</h3><p>The database connection string looks like this:</p><pre>DATABASE_URL=&quot;postgresql://test:test@postgres:5432/postgres_db&quot;</pre><p>Breaking it down:</p><ul><li>test:test → database username and password</li><li>postgres → name of the database service in Docker Compose</li><li>5432 → exposed database port</li><li>postgres_db → database name defined in the compose file</li></ul><p>Note that the database configuration itself is not defined in Docker Compose for the app container (in this specific case… it might be different for you). Instead, .env.test is copied to .env inside the container, and the application reads environment variables from there. Also, this is a Postgres database: the url prefix ‘postgresql’ might be different in your case.</p><h3>Docker Compose Configuration</h3><p>The Docker Compose file lives at:</p><pre>test/docker-compose.yml</pre><p>Here is the script:</p><pre>services:<br>  postgres: # Name of the service to use in database URL<br>    image: postgres:18-alpine<br>    container_name: my_postgres<br>    restart: always<br>    environment:<br>      POSTGRES_USER: test<br>      POSTGRES_PASSWORD: test<br>      POSTGRES_DB: postgres_db<br>    ports:<br>      - &quot;5432:5432&quot; # Port number to use in database URL<br>    volumes:<br>      - postgres_data:/var/lib/postgresql/data<br>    networks:<br>      - app_network<br>    healthcheck:<br>      test: [&quot;CMD-SHELL&quot;, &quot;pg_isready -U test -d postgres_db&quot;]<br>      interval: 5s<br>      timeout: 5s<br>      retries: 5<br><br>  app: # Your app service<br>    build: <br>      context: ./../<br>      dockerfile: test/setup/app/Dockerfile # location dockerfile<br>    container_name: my_app<br>    # Ensure the app depends on and waits for postgres to be ready<br>    depends_on:<br>      postgres:<br>        condition: service_healthy<br>    ports:<br>      # Map application port (adjust as needed)<br>      - &quot;3000:3000&quot;<br>    volumes:<br>      # Optional: mount application code<br>      - ./../src:/app/src<br>      - ./../test:/app/test<br>      - ./../prisma:/app/prisma<br>    networks:<br>      - app_network<br><br>volumes:<br>  postgres_data:<br>    driver: local<br><br># Define networks to ensure inter-container communication<br>networks:<br>  app_network:<br>    driver: bridge</pre><h3>Understanding the Compose File</h3><h3>Service Communication and Networks</h3><p>The networks section allows containers to communicate with each other. While Docker Compose handles container interconnection automatically, explicitly defining a network is how I originally learned to structure multi-container setups—and it makes dependencies more obvious.</p><h3>Health Checks and Startup Order</h3><p>The healthcheck on the PostgreSQL service runs every five seconds to ensure the database is ready.</p><p>This is critical because the app service uses:</p><pre>depends_on:<br>  postgres:<br>    condition: service_healthy</pre><p>Without this, the application might attempt to reset or migrate the database before PostgreSQL is ready, causing the app service to crash.</p><h3>Volumes and File Synchronization</h3><ul><li>The PostgreSQL volume (postgres_data) persists database data between container restarts.</li><li>The application volumes map local folders into the container:<br>src<br>test<br>prisma</li></ul><p>Because docker-compose.yml is located inside the test/ folder, paths must go up one level (./../). These volumes allow live updates without rebuilding the image.</p><h3>Why the Build Context Goes Up One Folder</h3><p>The build context is set to ./../ because:</p><ul><li>The Docker Compose script is test-specific</li><li>The project already has another Dockerfile at the root</li><li>We need access to src/ and prisma/ without modifying or conflicting with the main Docker setup</li></ul><p>Without modifying the build context, we’ll have trouble accessing the project’s files (i.e. src/, package.json, etc.).</p><h3>Running the Integration Tests</h3><p>From the test/ directory, simply run:</p><pre>docker compose up</pre><p>Docker Compose will:</p><ul><li>Start PostgreSQL</li><li>Wait for it to become healthy</li><li>Start the app service</li><li>Reset the database and run the tests</li></ul><h3>Rebuilding When Files Change</h3><p>If you modify a file that is:</p><ul><li>Copied using COPY</li><li>Not mounted as a volume</li></ul><p>Then Docker will not pick up the change automatically.</p><p>To force a rebuild, run:</p><pre>docker compose build --no-cache</pre><p>This rebuilds both images, but since PostgreSQL uses a standard image, only your application image takes time.</p><h3>Final Thoughts</h3><p>Docker Compose is an incredibly powerful tool for integration testing. It allows you to:</p><ul><li>Create fully isolated environments</li><li>Eliminate machine-specific setup issues</li><li>Safely reset databases</li><li>Scale testing infrastructure as your project grows</li></ul><p>By moving integration tests into Docker Compose, you lay a solid foundation for both local development and CI pipelines.</p><p>If you haven’t considered Docker Compose for your tests yet, now is a great time.</p><p><strong>Go Docker today!</strong> 🐳</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49b361a52f8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Spring Tutorial: The Only Tutorial You Will Need to Get Started (VS Code)]]></title>
            <link>https://medium.com/@alexandre.therrien3/java-spring-tutorial-the-only-tutorial-you-will-need-to-get-started-vs-code-13413e661db5?source=rss-d1484e3301ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/13413e661db5</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[maven]]></category>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Alex Therrien]]></dc:creator>
            <pubDate>Sun, 31 Mar 2024 18:19:09 GMT</pubDate>
            <atom:updated>2024-03-31T18:19:09.684Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java Spring Tutorial: The Only Tutorial You Need to Get Started (VS Code)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9vXyccpmYFJQABBjL5l1pg.png" /><figcaption>Java Spring Tutorial using VS Code</figcaption></figure><p><strong>Date of publication</strong> : March 31st, 2024</p><p>I recently made a small project using Java Spring, and I was greatly surprised by the quantity of tutorials I had to get through to finally start coding. For the purpose of conciseness and sparing people’s time, this tutorial assembles all the information I have found on different websites into a single tutorial. First, we will go through the process of launching the Spring application and being able to generate a simple web page. Second, we will add front-end content to our application. Finally, we will link our application with a database.</p><p>I will be using VS Code (Visual Studio code IDE) to develop the Java Spring Application.</p><h3>Requirements</h3><ul><li>Java is installed (at the time of this writing, I have chosen Java 17)</li><li>Your database is installed and ready to use. For this tutorial, I am going to use MariaDB.</li><li>VS Code installed</li><li>Understanding of methods of HTTP (Request methods like GET, POST, …) and networking (localhost, ports)</li><li>Understanding of Java code (annotations, classes, functions)</li><li>Understanding of HTML, CSS, and JavaScript</li><li>Understanding of Autowired annotation</li></ul><h3>Table of Contents</h3><ol><li><a href="#df0e">Creating and Launching the Java Spring Application</a></li><li><a href="#e40b">Adding Front-End Content</a></li><li><a href="#10fa">Linking our Spring Application with a Database</a></li></ol><h3>Creating and Launching the Java Spring Application</h3><p>Using VS code, there is a very useful feature that allows you to setup your Spring application in seconds. However, to be able to do that, you first need to download plug-ins in your IDE. In case you do not remember how to download plug-ins, you first need to go to the section ‘Extensions’, and then you can search plug-ins to download them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*75kK_0HAo6e8E1M3Xj_txQ.png" /><figcaption>Opening Extensions tab in Visual Studio Code</figcaption></figure><p>You will need the ‘Spring Boot Extension Pack’. (Step 1) In the ‘Extensions’ window, type ‘spring’. You will see it in the results. (Step 2) Click on the ‘Spring Boot Extension Pack’. Once opened, you will see a button ‘Install’ (which I do not have in my screenshot, because it is already downloaded on my PC). Click on the button ‘Install’ to download the plug-in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NXBqWv1K6_IXzIqnZGwKbQ.png" /><figcaption>Downloading Spring Boot Extension Pack plugin</figcaption></figure><p>You will also need the ‘Extension Pack for Java’ (if you do not already have it). (Step 1) In the ‘Extensions’ window, type ‘java’. (Step 2) Click on the ‘Extension Pack for Java’. (Step 3) Click install.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wKAg1JkEq7Jaks38mvFZkA.png" /><figcaption>Downloading Extension Pack for Java plugin</figcaption></figure><p>Once this is done, you will be able to create a Spring application very easily. You can use the shortcut Ctrl+Shift+P to show the Command Palette. If that does not work, you can go to ‘View’ -&gt; ‘Command Palette…’ from your VS code task bar.</p><p>In the appearing Command Palette screen, type ‘Spring Initializr’. You will see in the results ‘Spring Initializr: Create Maven Project’. Click on that to create your Spring application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8642UMGU-P2paplUVMZnrg.png" /><figcaption>Selecting ‘Spring Initializr: Create Maven Project’ in Command Palette</figcaption></figure><p>From there, a series of prompts will appear. ‘Specify Spring Boot version.’ (Up to you. The most recent stable version is the first) ‘Specify project language.’ (Project language here is Java for the purpose of this tutorial), another prompt for ‘Input Group Id’ (maven related, I used com.tutorial.medium), ‘Input Artifact Id’ (maven related, I used demo), ‘Specify Packaging Type’ (Jar for the purpose of this tutorial), ‘Specify Java version.’ (17 for the purpose of this tutorial. I had difficulty making it work with versions 8 and 11), and ‘Search for dependencies.’ (Using Spring Web for this tutorial).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q-aWd11pPWohk1sCcTemcA.png" /><figcaption>Selecting Spring Web dependency for the Spring application</figcaption></figure><p>At this point, when you click ‘Enter’ to confirm the selection of dependencies (Spring Web was the only dependency needed), a hierarchy of files and folders is going to be generated.</p><h4>Additional Configuration of Spring</h4><p>In Spring, there is the concept of ‘Beans’. Beans are Java objects. There is something called ‘ComponentScan’ that is used to find the controllers, services, and data access objects (DAOs). This is important, because for the purpose of this tutorial, I will change the default configuration of the ComponentScan to change the scope of the scan. By default, the scope of the scan is too small for our usage.</p><p>A file has been generated inside your folder GroupID/ArtifactID. I chose ‘com.tutorial.medium’ for my group ID, and ‘demo’ as my artifact ID when generating the project. Thus, the file that launches the application can be found in ArtifactID/src/main/java/GroupID/ArtifactID/&lt;ArtifactID&gt;Application.java</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1srVx7xtfqTFxXsRlxdbjw.png" /><figcaption>DemoApplication.java file</figcaption></figure><p>Once you open this file, you notice the annotation ‘SpringBootApplication’. This annotation is actually the combination of three annotations:</p><ul><li>EnableAutoConfiguration</li><li>Configuration</li><li>ComponentScan</li></ul><p>I prefer putting other java files at the same level of hierarchy as the java file DemoApplication. For this purpose, we will change the SpringBootApplication annotation for the three individual annotations, and change the ComponentScan default value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JYh-ayTtnhBi_swlPiwDKA.png" /><figcaption>Replacing annotation SpringBootApplication</figcaption></figure><p>The annotation SpringBootApplication has been removed and replaced. Notice the value between the parentheses of the annotation ‘ComponentScan’: this value corresponds to one folder above the folder in which the file DemoApplication.java is currently in (DemoApplication.java is in com/tutorial/medium/demo, and the component scan starts in com/tutorial/medium). Also notice that there are periods in the value of ‘ComponentScan’, not forward slashes. This will allow all beans under ‘com/tutorial/medium’ to be noticed by Spring.</p><h4>Creating a Controller</h4><p>To create a controller, the annotation ‘Controller’ will be important.</p><p>First, create a file for your controller. I put that file under com/tutorial/medium/controllers/DemoController.java. This controller will simply return a string (‘Your first return’) which will appear when you will go to &lt;Prefix URL&gt;/index.html (“/index.html” is the value in the annotation RequestMapping). The &lt;Prefix URL&gt; value is, by default, “localhost:8080”. Since we do not have any port specific configuration, it will be the same Prefix URL for you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YWVH69pIYz6sFJw0ve9Cbg.png" /><figcaption>Controller file which has not been saved</figcaption></figure><p>Notice the annotation ‘ResponseBody’. Without it, you would receive an error. This annotation is important, because it will simply send the return of the function. Normally, without the annotation, Spring will attempt to find a template file with the same name as the string returned. In other words, it would attempt to find a file called ‘Your first return’ if it weren’t for ‘ResponseBody’.</p><p>Thus, when you will start your Spring application, you will be able to see ‘Your first return’.</p><p><strong>Important</strong>: Do not forget to save your files! (using File -&gt; Save or Ctrl + S on Windows) Otherwise, the next step will not work. You can determine if the file is not saved when there is a white dot next to the file name.</p><h4>Starting your Spring Application</h4><p>To start your Spring application, you will need to use the Spring Boot dashboard. This feature has been added with the installation of the Spring Boot Extension Pack. You can find the dashboard on the bottom left of your screen. Click on the Spring Boot dashboard icon to open its menu (Step 1). You can then launch your application with the Play or Play with debug buttons next to your application name (which is also the Artifact ID) (Step 2).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q7Kte2VmMRNYO9_a2E1gLw.png" /><figcaption>Spring Dashboard to Launch the Application</figcaption></figure><p>Notice the section ‘Beans’ of the Spring dashboard. For now, those are the Java files that are present in our project (only difference is they start with a lowercase character). Also notice the section ‘Endpoint Mappings’, which shows the URLs available from the Prefix URL ‘localhost:8080’.</p><p>Once you click on Play (or Play with debug), you will see the Terminal starts logging content. Once it reaches the line ‘Started DemoApplication in XXXX seconds’ (it might be a different name for you, most likely the name of the application file that contained the annotation ‘SpringBootApplication’ that we saw earlier), the application has been launched.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gZJf8pb3gGhVU9ELRVbrRQ.png" /><figcaption>Logs when the Application Starts</figcaption></figure><p>The ‘Terminal’ tab will pop up once you click ‘Play’ or ‘Play with debug’ (1). A log will confirm the port on which the application is running on (2), reminding us that the application is running on port 8080. Finally, a log will tell us that our application has launched (3).</p><p>Now, you can go to ‘localhost:8080/index.html’ in your browser, and you will see the string ‘Your first return’.</p><h3>Adding Front-End Content</h3><p>To be able to add front-end content (using HTML, CSS, and JavaScript), there are additional steps that need to be done.</p><p>First, we will need to add a dependency to our pom.xml file. I will be using Thymeleaf for this tutorial. To add the dependency, go to your pom.xml file and add (in the &lt;dependencies&gt; tag):</p><pre>&lt;!-- Dependency that allows display of html --&gt;<br>&lt;dependency&gt;<br> &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br> &lt;artifactId&gt;spring-boot-starter-thymeleaf&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>To make the changes ‘effective’ or ‘seen’ by VS code, you need to right click on ‘pom.xml’ file (step 1) and select ‘Reload Projects’ (step 2). This will officially add the thymeleaf dependency. This needs to be done for any new dependency added to the pom.xml (and possibly any changes to that file).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rd8p79jGsoAd8WO77fccmg.png" /><figcaption>Reload new dependencies in pom.xml</figcaption></figure><p>Second, we need to add a new mapping to our controller (to support a new URL). Let’s add to our controller (file DemoController.java for this tutorial):</p><pre>@RequestMapping(value=&quot;/home.html&quot;, method = RequestMethod.GET)<br>public String home(){<br>    return &quot;home.html&quot;;<br>}</pre><p>It goes without saying that this function must be within the scope of the class DemoController.java. Also, I could have changed the name of the RequestMapping to something else (like /home); it does not need to match the name of the html file. Moreover, the file returned does not need to be a html file.</p><p>Upon receival of the request ‘localhost:8080/home.html’ in your browser, this would show the file called ‘home.html’ (which we haven’t yet created).</p><p>Let us now create the file ‘home.html’.</p><p>Because the path to the html file is simply ‘home.html’, the file must be directly found under ‘com/tutorial/medium/resources/templates’. If you put the file under ‘com/tutorial/medium/resources/static’, it will not be found.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nlYIwS1piWb0m-hrd4dM_Q.png" /><figcaption>Path to home.html File</figcaption></figure><p>In the ‘home.html’ file, let us put this content:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H8VAwzUw1yjUO09yvrhkbA.jpeg" /><figcaption>home.html File Contents</figcaption></figure><p>Now, if you have saved all of your modified files and launch your Spring application, you will notice changes. Once your application is started, type ‘localhost:8080/home.html’ in the browser, and you will see a title ‘Home Page’ accompanied with a button that changes text when clicked (‘Click me’ to ‘You clicked me’, to ‘Click me’ again…).</p><h4>Adding CSS/JS to the Page from an External File</h4><p>If this is simply a small application and you wish to add CSS directly in your home.html, go ahead. It will work.</p><p>If you want to create new files for your CSS and JavaScript, the ideal location to put them is under the folder ‘static’.</p><p>Here is an example of linking those files. I have changed the home.html file to link JS code and CSS code from external files. With these new files, when I click on the button with value ‘Click me’, it changes color as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OYbVRuGtVPbmvUzn4Q-1Lg.jpeg" /><figcaption>home.html New Contents</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pzMPfVUTQPn7XI8dTALcdQ.jpeg" /><figcaption>home.js Contents (New File)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hwZ1XoriKea0skQVRZ2nGQ.jpeg" /><figcaption>test.css Contents (New File)</figcaption></figure><p>Notice that the CSS and JS files were put in folders ‘css’ and ‘js’ respectively, under the folder ‘static’.</p><h3>Linking our Spring Application with a Database</h3><p>Depending on the database, your configuration will be a little different. The only things that will change are:</p><ul><li>The dependency/dependencies added to the pom.xml</li><li>The url to the database (will be using a different prefix)</li></ul><h4>Before You Continue…</h4><p>Before starting this section, it would be better to create the database structure used below.</p><p>To follow this tutorial, create a new database with name ‘test’, and a table called ‘testtable’. This table will contain columns ‘idTestTable’ and ‘name’. Create an entry in this table (I will enter ‘idTestTable’ = 1, ‘name’ = “Alex”). The ‘name’ field is what we are going to display on our home.html page (from idTestTable = 1).</p><h4>Linking Your Database with the Application</h4><p>For this tutorial, I am using a MariaDB database. For this reason, I need to add these dependencies to my pom file:</p><pre>&lt;!-- Database dependencies --&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.mariadb.jdbc&lt;/groupId&gt;<br>   &lt;artifactId&gt;mariadb-java-client&lt;/artifactId&gt;<br>   &lt;version&gt;2.6.0&lt;/version&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-jdbc&lt;/artifactId&gt;<br>  &lt;/dependency&gt;</pre><p><strong>Important!</strong> Do not forget to right-click on the pom.xml file and select ‘Reload Projects’ for the dependencies to become effective after you have made the changes.</p><h4>Configuring the Properties File</h4><p>Now, we need to set the database information in the application.properties file to connect to our database. This file was created when we asked VS code to generate the Spring project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qDUXlqKc6DCvYyMlvISkxg.png" /><figcaption>application.properties File</figcaption></figure><p>The application.properties file is under the resources folder. All those properties that are seen in this file are important. We will be using them to connect to the database. The first one (spring.jpa.hibernate.ddl-auto) determines if an action needs to be taken when the application boots up. In our case, none is needed. In the second property ‘spring.datasource.url’, notice that after ‘jdbc’ we find ‘mariadb’. This is going to vary depending on your database. Also, because we are attempting to connect to the ‘test’ database, we add ‘test’ at the end of that string.</p><h4>Configuring the Data Source Object</h4><p>The data source object is the object that contains all required information of the database. This object is used to establish a connection to the database.</p><p>I have create two new folders: ‘daos’ under the ‘medium’ folder, and ‘datasourceconfig’ under the ‘daos’ folder. In the ‘datasourceconfig’ folder, I have created a file called ‘DataSourceConfig.java’, which will contain the data source object initialization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AdR9FP5PiYL48f4hXc5gpg.png" /><figcaption>DataSourceConfig.java File</figcaption></figure><p>Here is all the code that goes into that file:</p><pre>package com.tutorial.medium.daos.datasourceconfig;<br><br>import javax.sql.DataSource;<br><br>import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;<br>import org.springframework.boot.context.properties.ConfigurationProperties;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.jdbc.core.JdbcTemplate;<br>import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;<br><br>@Configuration<br>public class DataSourceConfig {<br>    <br>    @ConfigurationProperties(prefix = &quot;spring.datasource&quot;)<br>    @Bean<br>    public DataSourceProperties getDataSourceProperties(){<br>        return new DataSourceProperties();<br>    }<br><br>    @Bean<br>    public DataSource getDataSource(){<br>        return getDataSourceProperties().initializeDataSourceBuilder().build();<br>    }<br><br>    @Bean<br>    public JdbcTemplate getJdbcTemplate(DataSource dataSource) {<br>        return new JdbcTemplate(dataSource);<br>    }<br><br>    @Bean<br>    public NamedParameterJdbcTemplate getNamedJdbcTemplate(DataSource dataSource){<br>        return new NamedParameterJdbcTemplate(dataSource);<br>    }<br>}</pre><p>The annotations ‘Bean’ are important here. This annotation will register the returned objects of those functions into the list of recognized Spring Beans. These will allow us to automatically determine which object is being referred when using the annotation ‘Autowired’. We will see that shortly.</p><p>The annotation ‘ConfigurationProperties’ has a parameter called ‘prefix’. The value of this parameter depends on your properties in the application.properties file. In our case, all properties starting with ‘spring.datasource’ will automatically get attached to the object returned by the ‘getDataSourceProperties()’ function.</p><p><strong>Multiple Databases</strong></p><p>If you have multiple databases, you will need to use the ‘Qualifier’ annotation with the ‘Bean’ annotation. This way, Spring will know which Bean to return when there are multiple of the same type. The ‘Qualifier’ annotation will be useful when using the ‘Autowired’ annotation.</p><p>An example of this would be:</p><pre>package com.tutorial.medium.daos.datasourceconfig;<br><br>import javax.sql.DataSource;<br><br>import org.springframework.beans.factory.annotation.Qualifier;<br>import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;<br>import org.springframework.boot.context.properties.ConfigurationProperties;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.jdbc.core.JdbcTemplate;<br>import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;<br><br>@Configuration<br>public class DataSourceConfig {<br>    <br>    @ConfigurationProperties(prefix = &quot;spring.datasource&quot;)<br>    @Bean<br>    @Qualifier(&quot;defaultConfig&quot;)<br>    public DataSourceProperties getDataSourceProperties(){<br>        return new DataSourceProperties();<br>    }<br><br>    @ConfigurationProperties(prefix = &quot;spring.datasource2&quot;)<br>    @Bean<br>    @Qualifier(&quot;secondConfig&quot;)<br>    public DataSourceProperties getDataSourceProperties2(){<br>        return new DataSourceProperties();<br>    }<br><br>    @Bean<br>    @Qualifier(&quot;defaultSource&quot;)<br>    public DataSource getDataSource(){<br>        return getDataSourceProperties().initializeDataSourceBuilder().build();<br>    }<br><br>    @Bean<br>    @Qualifier(&quot;secondSource&quot;)<br>    public DataSource getDataSource2(){<br>        return getDataSourceProperties2().initializeDataSourceBuilder().build();<br>    }<br><br>    @Bean<br>    @Qualifier(&quot;defaultJdbc&quot;)<br>    public JdbcTemplate getJdbcTemplate(@Qualifier(&quot;defaultSource&quot;) DataSource dataSource) {<br>        return new JdbcTemplate(dataSource);<br>    }<br><br>    @Bean<br>    @Qualifier(&quot;secondJdbc&quot;)<br>    public JdbcTemplate getJdbcTemplate2(@Qualifier(&quot;secondSource&quot;) DataSource dataSource) {<br>        return new JdbcTemplate(dataSource);<br>    }<br><br>    @Bean<br>    @Qualifier(&quot;defaultNJdbc&quot;)<br>    public NamedParameterJdbcTemplate getNamedJdbcTemplate(@Qualifier(&quot;defaultSource&quot;) DataSource dataSource){<br>        return new NamedParameterJdbcTemplate(dataSource);<br>    }<br><br>    @Bean<br>    @Qualifier(&quot;secondNJdbc&quot;)<br>    public NamedParameterJdbcTemplate getNamedJdbcTemplate2(@Qualifier(&quot;secondSource&quot;) DataSource dataSource){<br>        return new NamedParameterJdbcTemplate(dataSource);<br>    }<br>}</pre><p>If you need more data sources, you will probably need to divide your configurations into multiple DataSourceConfig files, where each file has its own beans with its own qualifiers.</p><p>It goes without saying that if you have multiple databases, you will also need to add other properties in your properties file. The prefix of those new properties will replace the prefix I have put for the function ‘getDataSourceProperties2()’.</p><h4>Adding the DAO (Data Access Object)</h4><p>The DAO will be useful to grab data from the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cw0RVE5hRGiqyymv7qFQyw.jpeg" /><figcaption>DemoDao.java File</figcaption></figure><p>I have put my DAO file under the folder called ‘daos’, which is found under the folder ‘medium’.</p><p>Here is the full code I have put in that file:</p><pre>package com.tutorial.medium.daos;<br><br>import org.springframework.context.annotation.Scope;<br>import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;<br>import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;<br>import org.springframework.stereotype.Repository;<br><br>import java.util.List;<br><br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.beans.factory.config.BeanDefinition;<br><br>@Repository(value=&quot;com.tutorial.medium.daos.DemoDao&quot;)<br>@Scope(BeanDefinition.SCOPE_SINGLETON)<br>public class DemoDao {<br>    <br>    private static final String GET_FIRST_NAME = &quot;SELECT name FROM testtable WHERE idTestTable = 1&quot;;<br><br>    @Autowired<br>    private NamedParameterJdbcTemplate jdbcTemplate;<br><br>    public String getFirstName(){<br>        List&lt;String&gt; namesFound = <br>            jdbcTemplate.queryForList(GET_FIRST_NAME, <br>                                      new MapSqlParameterSource(), <br>                                      String.class); <br>        return namesFound.get(0);<br>    }<br>}</pre><p>The ‘Repository’ annotation is useful to recognize the file as a ‘DAO’. I have added a name to it (the value parameter), which is going to be the name Spring will use to define this bean. The annotation ‘Scope’ has been defined to limit the creation of only one DAO (Singleton).</p><p>I have used the annotation ‘Autowired’ here to define the variable ‘jdbcTemplate’. Spring will find the ‘Bean’ object we have created in DataSourceConfig.java, and assign its result to this variable. It will find the Bean object that is of type ‘NamedParameterJdbcTemplate’, and since there is only one, it will assign it without further questions.</p><p><strong>Important!</strong> If you have multiple data sources, you need to specify the annotation ‘Qualifier’ below the annotation ‘Autowired’, so Spring can determine which object to return. Based on my example above (in the section ‘Multiple Databases’), you would either add ‘@Qualifier(“defaultNJdbc”)’ or ‘@Qualifier(“secondNJdbc”)’.</p><h4>Time to Test!</h4><p>To test that our connection to the database is really working, we will send data to our UI.</p><p>In the file ‘DemoController.java’, we will modify our mapping ‘home.html’, and add our DAO to the controller. This will result in a file that looks like this:</p><pre>package com.tutorial.medium.controllers;<br><br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.stereotype.Controller;<br>import org.springframework.ui.ModelMap;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import org.springframework.web.bind.annotation.RequestMethod;<br>import org.springframework.web.bind.annotation.ResponseBody;<br><br>import com.tutorial.medium.daos.DemoDao;<br><br>@Controller<br>public class DemoController {<br>    <br>    @Autowired<br>    private DemoDao demoDao;<br><br>    @RequestMapping(value=&quot;/index.html&quot;, method = RequestMethod.GET)<br>    @ResponseBody<br>    public String index(){<br>        return &quot;Your first return&quot;;<br>    }<br><br>    @RequestMapping(value=&quot;/home.html&quot;, method = RequestMethod.GET)<br>    public String home(ModelMap modelMap){<br>        modelMap.addAttribute(&quot;name&quot;, demoDao.getFirstName());<br>        return &quot;home.html&quot;;<br>    }<br>}</pre><p>In summary, I have added an autowired field for ‘DemoDao’, the DAO created in the previous step. Also, the function ‘home’ has been added a parameter ‘ModelMap’, which will allow us to send data to the UI. An attribute ‘name’ was defined in the object, with value ‘demoDao.getFirstName()’, which is the method we have developed in our DAO.</p><p>Finally, we will add a line of code in our html file ‘home.html’ under line 9 (which is &lt;h1&gt;Home Page&lt;/h1&gt;):</p><pre>&lt;p th:text=&quot;${name}&quot;&gt;&lt;/p&gt;</pre><p>This is the html ‘p’ tag combined with thymeleaf (th), and this will assign the attribute ‘name’ to the content of the p tag. We have added the attribute ‘name’ to the modelMap in our controller before.</p><p>Using the <a href="#ea7a">Spring Dashboard</a>, relaunch your application. You should now see the word ‘Alex’ showing beneath your ‘Home Page’ text.</p><h3>Conclusion</h3><p>In this tutorial, I have shown you how to setup your Spring application to be ready to start coding. First, we looked at initializing the Spring application. Then, we added front-end content to our application. Finally, we linked a database to the application.</p><p>I hope this tutorial has been fruitful to you.</p><p>If you wish to go further, here are other things that could be done:</p><ul><li>Database connection: change the password in the properties file with an encrypted password</li><li>Create a property to allow you to change the default port of the application</li></ul><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13413e661db5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Personalized Serializer and Deserializer using Java Gson Library]]></title>
            <link>https://medium.com/@alexandre.therrien3/personalized-serializer-and-deserializer-using-java-gson-library-c079de3974d4?source=rss-d1484e3301ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/c079de3974d4</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[serialization]]></category>
            <category><![CDATA[deserialization]]></category>
            <category><![CDATA[songs]]></category>
            <dc:creator><![CDATA[Alex Therrien]]></dc:creator>
            <pubDate>Tue, 02 Jun 2020 00:16:27 GMT</pubDate>
            <atom:updated>2020-06-02T00:24:38.430Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Personalized Serializer and Deserializer using Java Gson Library</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pi52IuzSSDI4oa97" /></figure><p>Before I begin, let me say that this tutorial applies to a very few. There are only some rare cases where this needs to be done. I did it because I created my own linked list and wanted to convert it into JSON. By default, Gson can automatically convert objects to their corresponding JSON format. However, the Gson library did not find a way to correctly convert my customized linked list to JSON.</p><p>I used <a href="http://tutorials.jenkov.com/java-json/gson.html">this</a> website to help me find this solution. Towards the end of the web page, there is some information about customizing the serializer and deserializer. If you need basic examples, this is the place to visit.</p><p>If you need any help with JSON syntax, you should refer to <a href="https://www.tutorialspoint.com/json/json_syntax.htm">this</a> website.</p><p>I knew the conversion was not being done well, because I ended up with ‘TreeNode’ elements (or something with a similar name) in my custom linked list. This is when I started to search for a solution online. You can look <a href="https://howtodoinjava.com/gson/custom-serialization-deserialization/">here</a> for examples, although I feel having it explained would be a lot simpler.</p><h3>Custom Serializer</h3><p>The skeleton of any Gson Serializer resumes to this:</p><pre>import com.google.gson.JsonArray;                       <br>import com.google.gson.JsonElement;                       <br>import com.google.gson.JsonObject;                       <br>import com.google.gson.JsonPrimitive;                       <br>import com.google.gson.JsonSerializationContext;                       import com.google.gson.JsonSerializer;                       <br>import java.lang.reflect.Type;                       <br>/**                        <br>*                        <br>* @author user                        <br>*/                       <br>public class SomeSerializer implements JsonSerializer&lt;<strong>SomeObject</strong>&gt; {                                                   <br>    <br>    public JsonElement serialize(<strong>SomeObject</strong> someObject, Type type,                                   <br>        JsonSerializationContext jsonSerializationContext) { <br>                              <br>    }                       <br>}</pre><p>(Code block 1.1)<br>Where <strong>SomeObject</strong> is the object that you desire to read to put into a JSON file.</p><h4>Building the Custom Serializer</h4><p>The first thing you need to do is start by creating an object of type <strong>JsonObject. </strong>Then, you will need to add your values to that <strong>JsonObject</strong> instance. If the values added are primitive values, you only need to convert your values to <strong>JsonPrimitive</strong> objects. If the values added are arrays, you would need to extract all of the indexes of those arrays and add them into a <strong>JsonArray</strong> one by one. If the values added are objects, then you need to create other <strong>JsonObject</strong>s<strong> </strong>to your main <strong>JsonObject</strong>. The following sections will show how it is done.</p><p><strong>Creating the JSON Object</strong><br>To create the JSON object that will store the object being serialized, do the following:</p><pre>JsonObject jsonObject = new JsonObject();</pre><p><strong>Adding a String, Integer, or Double<br></strong>To add any value to the JSON object (being String, Integer, or Double), you need to do the following:</p><pre>jsonObject.add(&quot;title&quot;, new <br>    JsonPrimitive(<strong>someObject</strong>.getTitle()));</pre><p>This code shows that there is the need to create a new JsonPrimitive object. Gson only understands values being passed as JsonPrimitive objects. Also, the string <strong>title</strong> is the key that is going to be associated to our value.</p><p><strong>Adding an Array of Values</strong><br>To add an array of values to our JSON object, you need to do the following:</p><pre>ArrayList&lt;String&gt; someArray = <strong>someObject</strong>.getInstructions();                               <br>JsonArray someJsonArray = new <br>    JsonArray(someArray.size());<br>                               <br>for(int i=0;i&lt;someArray.size();i++){                                   <br>    someJsonArray.add(someArray.get(i));                               <br>}      <br>                         <br>jsonObject.add(&quot;someArray&quot;, someJsonArray);</pre><p>Essentially, the first line of this code block is irrelevant; this is the way I get the array of information from the object. The next lines, however, are important. First, a <strong>JsonArray</strong> having the same size as the array of reference (<strong>someArray</strong> in this case) must be created. Then, iterating over the indexes of the array of reference is done. For each index, a primitive value is being added to the <strong>JsonArray</strong> using the <strong>add()</strong> method. Finally, once the array is completed, the array is added to <strong>jsonObject</strong> using the <strong>add()</strong> method. The first argument of that method is the key that will be associated with the array. The second argument is the actual <strong>JsonArray</strong> that was just created.</p><p><strong>Adding an Array of Objects<br></strong>To create an array of objects, it would pretty much look like the previous section. the only difference would be that you would be adding objects instead of strings with the <strong>add()</strong> method from the <strong>JsonArray</strong> object. To do so, you would need to instantiate a <strong>JsonObject</strong> object and put key/value pairs in it, as shown from the section <strong>Adding a String, Integer, or Double </strong>in this article.</p><p>To conclude this section, do not forget to return your main <strong>JsonObject</strong> at the end of the function as the <strong>serialize </strong>method returns a <strong>JsonElement</strong>! (refer to code block 1.1)</p><h4>Referencing the Custom Serializer</h4><p>To be able to use your custom serializer, you have to reference it somewhere in your code. To do so, you would follow the common procedure as referenced in the Gson documentation, but with an extra line of code. This line of code would identify the custom serializer as the way to translate the object to JSON. Refer to the <strong>Custom Instance Creators in GSON </strong>on <a href="http://tutorials.jenkov.com/java-json/gson.html">this</a> website for more information.</p><pre>GsonBuilder builder = new GsonBuilder();                             <br>builder = builder.registerTypeAdapter(<strong>SomeObject</strong>.class, new <br>              <strong>SomeSerializer</strong>());<br>Gson gson = builder.create();                              FileWriter writer = new FileWriter(<br>              <strong>PATH_TO_JSON</strong>+<strong>titleOfJsonFile</strong>+&quot;.json&quot;);                                <br>writer.write(gson.toJson(<strong>someObjectInstance</strong>));                                <br>writer.close();</pre><p>Essentially, all you have to do is assign the <strong>builder </strong>object to a builder that considers the custom serializer that was built (look at line 2. This is the line that matters the most, only briefly mentioned in Gson documentation). Note that the class for the custom serializer that was designed in this tutorial was <strong>SomeSerializer</strong>, and that the object that was serialized was called <strong>SomeObject</strong>.</p><p>The variables <strong>PATH_TO_JSON </strong>and <strong>titleOfJsonFile </strong>are variables that determine where the file is going to be stored.</p><p>The variable <strong>someObjectInstance</strong> is an object of type <strong>SomeObject </strong>that we want to have serialized.</p><p>Also, I am able to write the object of type <strong>SomeObject</strong> to a file in JSON using the <strong>gson.toJson() </strong>function.</p><h3>Custom Deserializer</h3><p>The skeleton of any Gson Deserializer resumes to this:</p><pre>import com.google.gson.JsonDeserializationContext;                       import com.google.gson.JsonDeserializer;                       import com.google.gson.JsonParseException;                                                                    import java.lang.reflect.Type;                       <br>/**                        <br>*                        <br>* @author user                        <br>*/                                               <br>public class SomeDeserializer implements  <br>    JsonDeserializer&lt;<strong>SomeObject</strong>&gt; {                                                   <br>    <br>    public <strong>SomeObject</strong> deserialize(JsonElement jsonElement, Type <br>        type, JsonDeserializationContext jsonDeserializationContext) <br>        throws JsonParseException { <br>                        <br>    }<br>}</pre><p>(Code block 2.1)<br>Where <strong>SomeObject</strong> is the object that you desire to create after having read a JSON file. The JsonElement object contains all the data that Gson could extract from the JSON file. This is the only parameter that is required to extract the content of a JSON file.</p><h4>Building the Custom Deserializer</h4><p>The first step in the deserializer is to get the content of the JSON file. To do so, refer to the next section. The second step is to extract the values from the JSON file by using the keys associated with the values that you want to extract. The final step is to return the object built as a result of deserializing the JSON file. Following from code block 2.1, that would be the <strong>SomeObject </strong>instance.</p><p><strong>Extracting the JSON Content<br></strong>To extract the JSON content from a file, all you need to do is:</p><pre>JsonObject jsonObject = <strong>jsonElement</strong>.getAsJsonObject();</pre><p>The <strong>jsonElement</strong> object is of type <strong>JsonElement</strong> and is from the parameter list of your function <strong>deserialize</strong> (refer to Code block 2.1). You can get the content of your file from this function as the syntax of a JSON file starts with a <strong>{</strong> and ends with a <strong>}</strong>.</p><p><strong>Extracting Primitive Values from JSON<br></strong>To extract primitive values from a JSON file (either integer, double, or string) can simply be done from the corresponding functions:</p><ol><li>getAsString() to extract strings</li><li>getAsDouble() to extract doubles</li><li>getAsInt() to extract integers</li></ol><p>You can extract those values from the corresponding JSON element you have chosen.</p><pre>//assuming you have a &quot;title&quot; parameter in your JSON                             <br>String title = jsonObject.get(&quot;title&quot;).getAsString();</pre><p>Inside the <strong>jsonObject</strong> of type JsonObject, there was a field called <strong>title</strong>. The function <strong>get()</strong> returns an object of type JsonElement. This object only comes to use to us when using either the <strong>getAsString(), getAsDouble(), or getAsInt()</strong> method.</p><p>In this previous code block, I extract the string value associated with the key <strong>title</strong>.</p><pre>ingredientJsonObject.get(&quot;quantity&quot;).getAsDouble();</pre><p>In this previous code block, I extract the double value associated with the key <strong>quantity.</strong></p><pre>ingredientJsonObject.get(&quot;unit&quot;).getAsInt();</pre><p>In this previous code block, I extract the integer value associated with the key <strong>unit</strong>.</p><p><strong>Extracting the Content of a Common JSON Array</strong></p><p>To extract the content of some JSON array, use the following:</p><pre>//assuming you have a JSON array named &quot;someArray&quot; in your JSON<br>JsonArray JSONArray = jsonObject.getAsJsonArray(&quot;someArray&quot;);                                                              for(int i=0;i&lt;JSONArray.size();i++){<br>    someObject.addIndex(<br>        JSONArray.get(i).getAsString());                        <br>}</pre><p>This example speaks for itself. From your JsonObject <strong>jsonObject</strong>, get the associated value with the key <strong>someArray. </strong>Using the function <strong>size()</strong> from the JsonArray class to know when the array ends, iterate over the JsonArray and extract all the primitive values from it. The <strong>get()</strong> function from the JsonArray class will allow you to get a value at a certain index.</p><p>This code extracts the content of a common JSON array, which is some thing of the sort:</p><pre>[&quot;orange&quot;, &quot;pancake&quot;, &quot;blueberry&quot;]</pre><p><strong>Extracting the Content of a Custom JSON Array<br></strong>The difference between a custom JSON array and a common JSON array is that the custom one contains JSON objects as indexes, and the other contains primitive values as indexes. Below is an example of how to extract data from a custom JSON array.</p><pre>JsonArray ingredientsJSONArray= <br>    jsonObject.getAsJsonArray(&quot;ingredients&quot;);</pre><pre>for(int i=0;i&lt;ingredientsJSONArray.size();i++){                                     <br>    JsonObject ingredientJsonObject = <br>        ingredientsJSONArray.get(i).getAsJsonObject();                                   <br>    someObject.addIngredient(<br>        ingredientJsonObject.get(&quot;nameIngredient&quot;).getAsString(),                                       <br>        ingredientJsonObject.get(&quot;quantity&quot;).getAsDouble(), <br>        ingredientJsonObject.get(&quot;unit&quot;).getAsInt());                               }</pre><p>In this example, I get the array with the key <strong>ingredients</strong>. Then, I define a for loop the same way I did when extracting data from a common JSON array (see previous section).</p><p>Because indexes are now objects, I extract the content of indexes using the function <strong>getAsJsonObject().</strong> Within that object, I get the values I want using the keys that I defined in those (<strong>nameIngredient, quantity, </strong>and <strong>unit</strong>).</p><p>Last but not least, do not forget to return the object you just built from your JSON file!</p><h4>Referencing the Custom Deserializer</h4><p>There is not much difference from the <strong>Referencing the Custom Serializer</strong> section of this article. The only difference is that you now reference a deserializer instead of a serializer. Of course, after the <strong>Gson </strong>object is created, things get really different. Because we are reading a JSON file, we have to use a <strong>BufferedReader </strong>object to be able to convert the content of the file to a JSON object. Using the <strong>gson.fromJson() </strong>method we accomplish this goal. Refer to the <strong>Custom Instance Creators in GSON </strong>on <a href="http://tutorials.jenkov.com/java-json/gson.html">this</a> website for more information.</p><pre>GsonBuilder builder = new GsonBuilder();                              <br>builder = builder.registerTypeAdapter(<strong>SomeObject</strong>.class, new     <br>    SomeDeserializer());                             <br>Gson gson = builder.create();                              <br>BufferedReader bufferedReader = new BufferedReader(                                <br>    new FileReader(<strong>canonicalPathToFile</strong>));                                                             <br><strong>SomeObject</strong> <strong>someObject</strong> = gson.fromJson(bufferedReader,   <br>    <strong>SomeObject</strong>.class);                              </pre><p>Remember that the <strong>SomeObject</strong> class is only used as an example. The value of <strong>canonicalPathToFile </strong>is the path to the file.</p><h3>Conclusion</h3><p>To conclude, I would like to remind the readers to use the same key fields for serializing and deserializing the object. Otherwise, there will be errors because the values you will be looking for will not be found. What I mean by that is you need to match the key value when serializing the object (say, <strong>title</strong>) with the one you will extract when deserializing the object. If you put anything else than <strong>title</strong>, Gson will not find it in the JSON file.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c079de3974d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to JPA with Apache Netbeans: 2 Different Methods to Setup JPA on the IDE]]></title>
            <link>https://medium.com/@alexandre.therrien3/introduction-to-jpa-with-apache-netbeans-2-different-methods-to-setup-jpa-on-the-ide-2bf5b3d3bb0f?source=rss-d1484e3301ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bf5b3d3bb0f</guid>
            <category><![CDATA[configuration]]></category>
            <category><![CDATA[glassfish]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[jpa]]></category>
            <category><![CDATA[apache-netbeans]]></category>
            <dc:creator><![CDATA[Alex Therrien]]></dc:creator>
            <pubDate>Sun, 27 Oct 2019 20:49:58 GMT</pubDate>
            <atom:updated>2019-10-30T02:26:37.109Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction to JPA with Apache Netbeans: 3 Different Methods to Setup JPA on the IDE</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*z2RRKMxSG3fGj6HE33afyA.png" /></figure><p>To understand how JPA works, I followed a tutorial <a href="https://www.vogella.com/tutorials/JavaPersistenceAPI/article.html#simple">here</a>. However, it was for another IDE than Apache Netbeans. My goal here will be to explain how to setup JPA specifically on Apache Netbeans. If you were wondering how to create a web application on Apache Netbeans, check my article <a href="https://medium.com/@alexandre.therrien3/apache-netbeans-ide-under-ubuntu-setting-up-your-first-web-application-using-netbeans-sibling-d793a04b211a">here</a>.</p><h3>Libraries I Had to Include</h3><p>I had to include the Apache Derby database and the EclipseLink library. Here are their Group IDs followed by their Artifact IDs (for Maven):<br>org.apache.derby / derby<br>org.eclipse.persistence / eclipselink</p><p>To create my tables manually (further down), I had to add the following dependency:<br>org.apache.derby / derbyclient</p><h3>Configuration of Apache Netbeans for JPA</h3><h4>Option 1: Adding Only the persistence.xml File</h4><p>The first particularity I noticed with JPA was the fact that it required a file called <em>persistence.xml</em> to be added to your project. Since I have not found out how to add a file to the classpath of my project, I spent a lot of time figuring out where I could put this file in a way that my Apache Netbeans would notice it.</p><p>After looking through the tutorials offered by <em>Apache Netbeans</em> on <a href="http://netbeans.apache.org/kb/docs/java/">http://netbeans.apache.org/kb/docs/java/,</a> I figured out that there was a folder that I did not have automatically into my project called <em>resources</em>. It seemed to include some configuration files, so I guessed it was important. So, I went ahead to create that folder directly from my <em>File Manager</em> (not in <em>Apache Netbeans</em>) into <strong>NetBeansProjects &gt; _Name_Project &gt; src &gt; main</strong>. After some reading on <em>StackOverflow</em>, I found out that the <em>persistence.xml</em> file needed to be added in a META-INF folder, so I went ahead and added a META-INF folder inside of my resources folder. This gave me the following path to my <em>persistence.xml</em> file: <strong>NetBeansProject &gt; _Name_Project &gt; src &gt; main &gt; resources &gt; META-INF &gt; persistence.xml</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*IfrxE0nx5u9pwnqasebtFw.png" /><figcaption>Fig 1.1: Adding the resources folder manually</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*ALNfv5IzWEbVD6I0nH206g.png" /><figcaption>Fig 1.2: Location of the persistence.xml file</figcaption></figure><p>In this <em>persistence.xml</em> file, I had to change some properties. Indeed, the author of the tutorial I mentioned above set up his xml to create tables, and then manually remove that statement after. What I did was to replace these statements to automatically create and drop the tables once my application was done:</p><pre>&lt;property name=&quot;javax.persistence.jdbc.url&quot;</pre><pre>value=&quot;...;create=true&quot;&gt;</pre><p>Became:</p><pre>&lt;property name=&quot;javax.persistence.jdbc.url&quot;</pre><pre>value=&quot;...&quot;&gt;</pre><p>And also:</p><pre>&lt;property name=&quot;eclipselink.ddl-generation&quot; value=&quot;create-tables&quot; /&gt;</pre><p>Became:</p><pre>&lt;property name=&quot;eclipselink.ddl-generation&quot; value=&quot;create-and-drop-tables&quot; /&gt;</pre><p>Also notice a new &lt;class&gt; tag that must be added for every JPA entity that you have in your project.</p><p>This is what my <em>persistence.xml</em> file looked like after the modifications I applied to it:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;<br>&lt;persistence xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;<br>    xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd&quot;<br>    version=&quot;2.0&quot; xmlns=&quot;http://java.sun.com/xml/ns/persistence&quot;&gt;<br>    &lt;persistence-unit name=&quot;todos&quot; transaction-type=&quot;RESOURCE_LOCAL&quot;&gt;<br>        &lt;class&gt;de.vogella.jpa.simple.model.Todo&lt;/class&gt;<br> &lt;properties&gt;<br>  &lt;property name=&quot;javax.persistence.jdbc.driver&quot; value=&quot;org.apache.derby.jdbc.EmbeddedDriver&quot; /&gt;<br>  &lt;property name=&quot;javax.persistence.jdbc.url&quot;<br>    value=&quot;path/to/folder/on/PC&quot; /&gt;<br>  &lt;property name=&quot;javax.persistence.jdbc.user&quot; value=&quot;test&quot; /&gt;<br>  &lt;property name=&quot;javax.persistence.jdbc.password&quot; value=&quot;test&quot; /&gt;<br><br>  &lt;!-- EclipseLink should create the database schema automatically --&gt;<br>  &lt;property name=&quot;eclipselink.ddl-generation&quot; value=&quot;create-and-drop-tables&quot; /&gt;<br>  &lt;property name=&quot;eclipselink.ddl-generation.output-mode&quot; value=&quot;database&quot; /&gt;<br> &lt;/properties&gt;<br><br>    &lt;/persistence-unit&gt;<br>&lt;/persistence&gt;</pre><h4>Option 2: Creating the Tables Manually with SQL and Setting your Tables on Localhost</h4><p>I originally had an <em>Apache Tomcat</em> server for my web applications as mentioned in my other tutorial on <em>Apache Netbeans</em> <a href="https://medium.com/@alexandre.therrien3/apache-netbeans-ide-under-ubuntu-setting-up-your-first-web-application-using-netbeans-sibling-d793a04b211a">here</a>. I am going to add a <em>GlassFish</em> server to be able to create the tables manually, because <em>GlassFish</em> is the only server that supports this method I am going to describe. Follow my other tutorial to know how to add a web server in <em>Apache Netbeans</em>.</p><p>I learned how to do this from this <a href="http://zetcode.com/db/hibernatederby/">link</a>, which was more about <em>Spring Boot</em>, but that does not matter. Note that this method requires a <em>Java</em> version inferior to the most recent one (I used <em>Java</em> 8), because <em>GlassFish</em> does not work on the latest version of <em>Java</em>.</p><p>Once you have downloaded your <em>GlassFish</em> server from <a href="https://javaee.github.io/glassfish/download">here</a>, and set it up in <em>Apache Netbeans</em> in the same way I did for <em>Tomcat</em> in my other tutorial, go to <em>Apache Netbeans</em> and set your project to use the <em>GlassFish</em> server (by <strong>right-clicking on your project &gt; Properties &gt; Run</strong> and change the Server value to GlassFish). Note: You only need the Web Platform download of GlassFish.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*2ICkggxlcPsqQQfGehmJSg.png" /><figcaption>Fig 2.1: Setting the GlassFish server as the server for this project</figcaption></figure><p>Then, go to your <em>Projects</em> window to select the <em>Services</em> view. In the <em>Services</em> view, under <em>Databases</em>, you will see the <em>Java DB</em> element. Right-click on it, and select <em>Create Database…</em> (which only appears enabled if you have a valid <em>GlassFish</em> server linked to <em>Apache Netbeans</em>). There, give a name for your database, and set your username/password for it. You do not need to change the location of the database, it works fine stored in the default location. Press <em>OK</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*713Upu6aI89xqSATm4cX1g.png" /><figcaption>Fig 2.2: Selecting the Services tab from the view that originally displays the Projects tab. This should be the view you get the first time you use this tab (without the black rectangles of course).</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*hiR5K5YXaRPgRwISRean1A.png" /><figcaption>Fig 2.3: After right-clicking on the Java DB element and selecting Create Database… , this pop up should appear.</figcaption></figure><p>A new link will appear under the directory <em>Databases</em>. It will have the name <em>jdbc:derby://localhost:portNb/name_DB</em>. Refer to figure 2.2 to see the one that was generated for the <em>sample</em> database, which is right above the category <em>Web Services</em>. Right click on it, and select the option <em>Execute Command</em>. This will allow you to set up your database using plain SQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*PxnXXLDjMWfsevoUkIc-Jw.png" /><figcaption>Fig 2.4: This is what appears after you right-click on your database link and select Execute Command. All you need to know is that the button I cover with a red outline will execute the commands you type in the location I wrote “Enter SQL commands here…”.</figcaption></figure><p><strong>Note</strong>: You can have annotations in your servlets indicating to which table and schema they belong to. This made it clearer for me when I designed the tables manually. The annotation is @Table and you can import it from javax.persistence.Table. You can use it in this way @Table(name=”name_table”, schema=”name_schema”). You place this statement right above the class definition.</p><p>Once your SQL is done, go back to your <em>persistence.xml</em> file and remove the line:</p><pre>&lt;property name=&quot;eclipselink.ddl-generation&quot; value=&quot;create-and-drop-tables&quot; /&gt;</pre><p>As you will not need it anymore because you have created the tables yourself.</p><p><strong>Warning</strong>: The username and password you have set for your database must be the same as the credentials inside the <em>persistence.xml</em> file! If needed, set the appropriate values to these lines:</p><pre>&lt;property name=&quot;javax.persistence.jdbc.user&quot; value=&quot;username&quot;/&gt;<br>&lt;property name=&quot;javax.persistence.jdbc.password&quot; value=&quot;password&quot;/&gt;</pre><p>Finally, set the proper URL to your database, which is the link you clicked on earlier of the format <em>jdbc:derby://localhost:portNb/name_DB</em>:</p><pre>&lt;property name=&quot;javax.persistence.jdbc.url&quot; value=&quot;jdbc:derby://localhost:portNb/name_DB&quot;/&gt;</pre><p>Now, you can test your database to see if you properly created your tables. Do not forget to add the dependencies I mention about sooner in this article. This option will not work unless you also have the dependency <em>derbyclient</em>.</p><h4>Option 3: Setting Up your SQL Tables Manually on Localhost Using JDBC</h4><p>I recently found out how to add <em>JDBC</em> to the mix by looking for documentation on Netbeans from <a href="https://stackoverflow.com/questions/6081307/how-to-connect-netbeans-to-mysql-database">here</a>. Using this method, there seems to be no demands towards a specific server. The only differences from option 2 is that :</p><ul><li>A different dependency needs to be added (<em>JDBC</em>)</li><li>Under the Services tab, you need to right click on <strong>Databases &gt; New Connection</strong> to define the connection to be <em>MySQL</em> (which seems to mean using <em>JDBC</em>) to create a link to localhost with your database linked with <em>JDBC</em>.</li></ul><p>The rest of the process is very similar to what was mentioned in option 2. However, I do not know if there is a configuration file, as there seems to be no mention of it.</p><h3>Conclusion</h3><p>In this tutorial, I have covered 2 ways to setup your <em>Apache Netbeans IDE</em> to work with a database using <em>JPA</em>. The first one demands less effort, which demands only to add a <em>persistence.xml </em>file to <strong>src/main/resources/META-INF</strong>. The second one demands more effort, because it only works with <em>GlassFish</em>, which you might have to setup. It also demands you to give <em>SQL</em> commands to manually build your tables. As well, the <em>persistence.xml</em> file will need to be modified to refer to that database.</p><p>I hope this article has helped you configure <em>Apache Netbeans</em> for your web application.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bf5b3d3bb0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Netbeans IDE under Ubuntu: Setting Up Your First Web Application Using Netbeans’ Sibling]]></title>
            <link>https://medium.com/@alexandre.therrien3/apache-netbeans-ide-under-ubuntu-setting-up-your-first-web-application-using-netbeans-sibling-d793a04b211a?source=rss-d1484e3301ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/d793a04b211a</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[apache-tomcat]]></category>
            <category><![CDATA[apache-netbeans]]></category>
            <category><![CDATA[ubuntu]]></category>
            <dc:creator><![CDATA[Alex Therrien]]></dc:creator>
            <pubDate>Fri, 27 Sep 2019 01:40:52 GMT</pubDate>
            <atom:updated>2019-09-27T15:57:48.973Z</atom:updated>
            <content:encoded><![CDATA[<h3>Netbeans Under Ubuntu: Setting Up Your First Web Application Using Apache Netbeans</h3><p>I recently had to download Netbeans for one of my classes, because it has integrated Java Servlets and JSP. However, that was not easy for me, because I wanted to use it on Ubuntu. After I had downloaded Netbeans and launched the IDE, it would either crash giving me unspecific errors, or it would freeze, not allowing me to do anything.</p><p>I found some link giving me some instructions on how to download ‘Apache Netbeans’ on Ubuntu. At first, I did not want to download Apache Netbeans, because it is not Netbeans. However, I noticed that there are a lot of similarities between Apache Netbeans and Netbeans, so I decided to give it a try. I can tell you it was worth it, as I have now a working solution using this IDE.</p><h3>Step 1: Download Java 8</h3><p>Go in your terminal and type the following commands.</p><blockquote>sudo apt-get update<br>sudo apt install openjdk-8-jdk</blockquote><p>Then if you type:</p><blockquote>java -version</blockquote><p>There should be a reply indicating which version of Java you have. The version of your Java should be 8.</p><h3>Step 2: Download Apache Netbeans</h3><p>To download Apache Netbeans, simply type (there are two hyphens):</p><blockquote>sudo snap install netbeans — classic</blockquote><h3>Step 3: Download Apache Tomcat</h3><p>I realize that the setup for Apache Netbeans is a little more difficult than the Netbeans I am used to work with. It does not come with a server that you can use on the spot. So, you need to find yourself a server. I downloaded an Apache Tomcat server on <a href="https://tomcat.apache.org/download-80.cgi">https://tomcat.apache.org/download-80.cgi</a> and I downloaded the <strong>tar.gz</strong> version. Once it was downloaded, I extracted the folder inside the zipped <strong>tar.gz </strong>folder, and I kept it in my <strong>Downloads</strong> folder.</p><h3>Step 4: Creating your first Web Application in Apache Netbeans</h3><p>Once I had my web server, I launched Apache Netbeans. I created a new project using <strong>File →New Project</strong>, and I selected <strong>Java with Maven → Web Application</strong>. Press on <strong>Next</strong>. Give a project name that suits you and you can keep the rest of the values to their default values. Press <strong>Next</strong>. On the <strong>Server</strong> settings, you will find the button <strong>Add…</strong> right next to the input field. Press on it.</p><p>A new popup will appear. Select the type of server you are going to add (Tomcat, …, by following this tutorial you would select Tomcat). Click on <strong>Next. </strong>From here, you set up the server. You will need to specify the path to the server (which is, for me, the <strong>Downloads</strong> folder, as it is where the first folder inside the unzipped <strong>tar.gz</strong> package is), and then create some credentials for your server. Choose your username and password, and do not forget your credentials as you will need them later to launch your application. By that I mean that the IDE will demand you to identify yourself whenever you will be launching your web application, so make sure you do not lose those credentials. I guess that you can add the same server as being another server and reset your credentials in that way, if it ever happens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*T1gvhMFlEUfZQjWkgCZ56g.png" /><figcaption>Figure 1.1: First pop-up appearing after you select File -&gt; New Project with the correct selected values to create a Web Application.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*TbLjqjXFtBYFiZKKVm5Chw.png" /><figcaption>Figure 1.2: Third step to fill as we are creating a new Web Application with Maven in Apache Netbeans.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*-TYzhIduSlHLERyUOfIkcA.png" /><figcaption>Figure 1.3: Pop-up appearing after clicking the Add… button</figcaption></figure><p>Once you are done with creating a new server instance, this last popup will be removed and you will end with what appears on Figure 1.2. You can click on <strong>Finish</strong> and you will have a new web application.</p><p>I created this blog because searching for Apache Netbeans on Google did not yield me a lot of results, and I did not find anything relating to adding a server in Apache Netbeans. This led me to hours of confusion on how to do it. I hope this can help some of you set up your environment faster!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d793a04b211a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>