<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Spring &#8211; CodePills.com</title>
	<atom:link href="https://codepills.com/tag/spring/feed/" rel="self" type="application/rss+xml" />
	<link>https://codepills.com</link>
	<description>Helping you make a better code</description>
	<lastBuildDate>Sat, 23 Mar 2024 08:38:54 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	
	<item>
		<title>How to load files from Spring JUnit test resources folder</title>
		<link>https://codepills.com/how-to-load-files-from-spring-junit-test-resources-folder/</link>
					<comments>https://codepills.com/how-to-load-files-from-spring-junit-test-resources-folder/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Wed, 03 Mar 2021 10:04:00 +0000</pubDate>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[ClassLoader]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java 7]]></category>
		<category><![CDATA[JUnit]]></category>
		<category><![CDATA[legacy project]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[testing]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1141</guid>

					<description><![CDATA[In this short tutorial, you will see how to read the files from the <i>/src/test/resources</i> test directory path in your Spring application. <a href="https://codepills.com/how-to-load-files-from-spring-junit-test-resources-folder/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>In this short tutorial we will show you how to read the files from the <i>/src/test/resources</i> directory path.</p>
<p><span id="more-1141"></span></p>
<p>It is common practice for unit testing in the Spring JUnit test to load files and their content to make more robust test cases. Or we have a test case where we need perhaps read or write data or test specific files in general.</p>
<h2>1. Using ClassLoader</h2>
<p>First option is to use and instance of the <code>ClassLoader</code>.</p>
<pre><code class="language-java">final ClassLoader classLoader = getClass().getClassLoader();
final String resourceName = "daily_report.csv";
final File file = new File(classLoader.getResource(resourceName).getFile());
final String absolutePath = file.getAbsolutePath();

System.out.println(absolutePath);

Assert.assertTrue(absolutePath.endsWith("/daily_report.csv"));</code></pre>
<p>We will get the output of the absolute path as:</p>
<pre><code class="language-bash">/Users/your.user.name/DEV/tutorials/testing-modules/junit-5-basics/target/test-classes/daily_report.csv</code></pre>
<p>Be aware that the path to the resource will look slightly different from the rest of the examples. It is because the ClassLoader looks for the resources on the classpath. Therefore obtaining a path to the resource is from the point of the compiled project.</p>
<p>If you build your project with Maven, compiled classes and resources are in the <code>/target</code> directory in the project root folder. That is why you need to count on the path to resource adjusted for the difference. The other two methods use project root.</p>
<h2>2. Using Path</h2>
<p>Second option is to use an instance of the <code>Path</code> class. We will call a static factory method <code>Paths.get()</code> which will return us its new instance. Then we will convert <code>Path</code> to <code>File</code> instance and from the that we will extract absolute path with <code>getAbsolutePath()</code> method.</p>
<pre><code class="language-java">final Path resourcePath = Paths.get("src","test","resources");
final String absolutePath = resourcePath.toFile().getAbsolutePath();

System.out.println(absolutePath);

Assert.assertTrue(absolutePath.endsWith("src/test/resources"));</code></pre>
<p>We will get the same output as in example using <code>java.io.File</code>:</p>
<pre><code class="language-bash">/Users/your.user.name/DEV/tutorials/testing-modules/junit-5-basics/src/test/resources</code></pre>
<p><i>Path</i> class was introduced in Java 7; consequently, it is available also in older and legacy projects.</p>
<h2>3. Using java.io.File</h2>
<p>Third approach is to use an instance of the <code>java.io.File</code> class to read the <i>/src/test/resources</i> directory. We will create instance and then we will call its method <code>getAbsolutePath()</code> method. Path we will obtain in this way is relative path towards the current working directory of the project.</p>
<pre><code class="language-java">final String resourcePath = "src/test/resources";
final File file = new File(resourcePath);
final String absolutePath = file.getAbsolutePath();

System.out.println(absolutePath);

Assert.assertTrue(absolutePath.endsWith("src/test/resources"));</code></pre>
<p>Let&#8217;s see an example output when running on the Unix based system:</p>
<pre><code class="language-bash">/Users/your.user.name/DEV/tutorials/testing-modules/junit-5-basics/src/test/resources</code></pre>
<h2>Conclusion</h2>
<p>This article was a quick tutorial where we showed how to read resources from the <i>/src/test/resources</i> directory in JUnit 5.</p>
<p>There are three different ways how to get a resource for testing. We can either use File, Paths or ClassLoader class.</p>
<p>As always, you can find all our examples on our <a href="https://github.com/codekopf/tutorials-jvm/tree/master/testing-modules" title="Tutorial JVM - Testing modules" target="_blank" rel="nofollow noopener">GitHub project</a>!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/how-to-load-files-from-spring-junit-test-resources-folder/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>3 ways how to kill Spring Boot application at port 8080 on Windows</title>
		<link>https://codepills.com/3-ways-how-to-kill-spring-boot-application-at-port-8080-on-windows/</link>
					<comments>https://codepills.com/3-ways-how-to-kill-spring-boot-application-at-port-8080-on-windows/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Wed, 03 Feb 2021 17:47:12 +0000</pubDate>
				<category><![CDATA[Bug hunt]]></category>
		<category><![CDATA[cmd]]></category>
		<category><![CDATA[computer]]></category>
		<category><![CDATA[error]]></category>
		<category><![CDATA[IDE]]></category>
		<category><![CDATA[IntelliJ Idea]]></category>
		<category><![CDATA[PID]]></category>
		<category><![CDATA[process]]></category>
		<category><![CDATA[process ID]]></category>
		<category><![CDATA[server container]]></category>
		<category><![CDATA[servlet]]></category>
		<category><![CDATA[shell]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Spring Boot]]></category>
		<category><![CDATA[Spring Boot application]]></category>
		<category><![CDATA[Spring development]]></category>
		<category><![CDATA[terminal]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1132</guid>

					<description><![CDATA[This article is a simple tutorial on how to kill your Spring Boot application which occupies port 8080 on Windows <a href="https://codepills.com/3-ways-how-to-kill-spring-boot-application-at-port-8080-on-windows/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>This article tries to answer one of the most often occurred questions connected with Spring Boot development. When developing a web application with Spring Boot, you might hit an error announcing that port 8080 is occupied. In this article, we will see why and how to solve this error. However, be sure that tutorial can help you solve the occupancy of any other port.</p>
<p><span id="more-1132"></span></p>
<h2>Spring Boot application default port</h2>
<p>When you develop long enough with Spring Boot, you know the error very well. You work on your Spring Boot application, and you use a console for running the application. Or you use your favourite IDE runner for starting your application (my preferred IDE is IntelliJ IDEA). Your Spring Boot application in the running embedded in servlet container when suddenly you need to do something else. Instead of adequately terminating the embedded servlet container with your application, you detach from the servlet by a closing terminal window or switching to a different project in IDE. However, because you did not correctly terminate your IDE runner and did not correctly kill the terminal&#8217;s application process, the servlet with the application is still running. After that, you might, of course, start developing something else. Surprise, surprise, you cannot. Any Spring Boot application port, by default number 8080, is still occupied with the unterminated process of your Spring Boot servlet container. (In the tutorial, we assume you are using the Spring Boot application port on default port number 8080).</p>
<p>I guess you might be a little bit confused by all the wording describing the issue. Let&#8217;s take a look first at some terminology to understand the problem here fully:</p>
<h3>What is process?</h3>
<p>We are aware that readers of this blog are pretty skilled in computers. So, we will provide a brief description of what is computer process without going to further details.</p>
<p>Every time you start a program on your computer, it requires a certain amount of resource. Your Central Processor Unit, known as CPU, add to this program its process.</p>
<p>If you open task manager on your Windows, you will see a list of all process your CPU is trying to manage at once.</p>
<h3>What is process ID?</h3>
<p>The process ID, also known as PID, is the number assigned by the operating system to each new process.</p>
<h3>What is port number?</h3>
<p>A port number is how to identify individual processes for network message when they arrive on a server. In a real sense, a port number is the logical address of each application or process that helps identify the sender and receiver of processed messages. </p>
<p>You can imagine port numbers as doors in the hallway into which message flows through the networks. It leaves one door and enters another.</p>
<h3>What is Spring Boot server container?</h3>
<p>Spring Boot is a Spring project which makes Spring development fast. Without going too much into the Spring Boot project details, your Spring Boot application runs in a server container, better known as a servlet. This servlet runs in one computer process and lister on port 8080 for traffic.</p>
<h2>Restart computer</h2>
<p>One way how to solve this is to restart your computer. During the restart of Windows OS, start all the fresh, and port 8080 will be empty. But this is not the fastest and definitely not the right way for developers to solve this.</p>
<h2>Set different port number</h2>
<p>Another way is to solve this issue by assigning the Spring Boot application a different port number. When we set a different port number for the application, we will not kill the existing process with the application servlet container. However, we will create a new-different process for the servlet container, which will be listening on a different port. In this way, port 8080 will be still occupied, but we will at least be able to continue to develop.</p>
<p>Go to Spring Boot <code>application.properties</code> file and set different port number for <code>server.port</code> .</p>
<p>Despite this quick workaround, there is a much more mature way to solve this problem. I would like you to show a better way to kill a Spring Boot servlet container listening on port 8080.</p>
<h2>Kill the process listening at port 8080</h2>
<p>To kill the process listening at port 8080 in the Windows environment, we need only go through a few steps. First, check the image below to get the idea.</p>
<p><img fetchpriority="high" decoding="async" src="https://codepills.com/wp-content/uploads/2021/02/kill_process_at_port_8080_on_the_windows_10.png" alt="How to kill process listening at port_8080 on the Windows 10" width="623" height="198" class="size-full wp-image-1133" srcset="https://codepills.com/wp-content/uploads/2021/02/kill_process_at_port_8080_on_the_windows_10.png 623w, https://codepills.com/wp-content/uploads/2021/02/kill_process_at_port_8080_on_the_windows_10-300x95.png 300w" sizes="(max-width: 623px) 100vw, 623px" /></p>
<h3>Find the process occupying port 8080</h3>
<p>On the Windows, open your CMD terminal. With simple command <code>netstat  -ano  |  findstr  PORT_NUMBER</code>, where for PORT_NUMBER add port number 8080, and on command prompt output (hit enter), we will get the <b>process id</b> of process <strong>listening on port 8080</strong>.</p>
<h3>Kill the process with command prompt</h3>
<p>Now, all we need to do is just type the following command <code>taskkill  /F  /PID  PROCESS_ID</code> and replace PROCESS_ID by the <b>process id</b> we got from the previous command result.</p>
<p>If you have typed everything correctly, process listening on port 8080 should be terminated.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/3-ways-how-to-kill-spring-boot-application-at-port-8080-on-windows/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to trigger action with Scheduler and Quartz in Camel</title>
		<link>https://codepills.com/how-to-trigger-action-with-scheduler-and-quartz-in-camel/</link>
					<comments>https://codepills.com/how-to-trigger-action-with-scheduler-and-quartz-in-camel/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Wed, 06 Jan 2021 16:47:38 +0000</pubDate>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Camel]]></category>
		<category><![CDATA[Component]]></category>
		<category><![CDATA[CRON]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[messaging]]></category>
		<category><![CDATA[Quartz]]></category>
		<category><![CDATA[Quartz2]]></category>
		<category><![CDATA[Scheduler]]></category>
		<category><![CDATA[Spring]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1118</guid>

					<description><![CDATA[This article is about triggering action with Scheduler and Quartz components in Camel <a href="https://codepills.com/how-to-trigger-action-with-scheduler-and-quartz-in-camel/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>In any project using Camel you might come to the stage you want to trigger action periodically.</p>
<p>We have recently looked on how to <a href="https://codepills.com/how-to-download-a-file-from-azure-claud-storage/" title="How to download a file from Azure Claud Storage">download file from Azure Cloud Storage</a> in legacy application. With the help of Camel and in Java project, all was written in a couple of minutes. But what if you have a special case and your file is changing periodically. For example, every day or every minute?</p>
<p>This article will show you a couple of code examples on how to initiate an action when periodic change is required. This article will also show you how to start the action with Camel&#8217;s Scheduler and Camel&#8217;s Quartz2 components, mostly for your legacy Camel projects.</p>
<p><span id="more-1118"></span></p>
<p>We will extend code from an article about downloading a file from Azure Cloud Storage in our hypothetical scenario. We will create Spring Component in our new application for Camel messaging. It will download a certain file from Azure Cloud Storage periodically.</p>
<h2>Using Camel Scheduler component as trigger</h2>
<p>First of all, we need to extend RouteBuilder. The RouteBuilder is a base class which is derived from to create routing rules using the DSL. Instances of RouteBuilder are then added to the CamelContext.</p>
<p>In the extended class <i>ScheduleFromAzureCloudStorageToDisk</i> we will override <i>configure()</i> method. <i>configure()</i> method is actually used for Camel&#8217;s messaging system. We start with Camel&#8217;s <i>from</i> method for building routes and we will place our trigger there. We will use the <i>Scheduler</i> component with combination of <i>delay</i> method option for the file download in this example. This delay will trigger periodical lookup into the Azure Cloud Storage. Delay needs to be set up in milliseconds.</p>
<p>The second, thing to do is to set route id for Camel context. Any unique name for route name will do it.</p>
<p>Finally, all we need to do is create a method that will look into the Azure Cloud Storage and save the new document to local/external disk/source. To get a better idea how this method might look in the legacy application, check the article <a href="https://codepills.com/how-to-download-a-file-from-azure-claud-storage/" title="How to download a file from Azure Claud Storage">How to download a file from Azure Claud Storage</a>.</p>
<pre><code>package com.codepills.routes;

import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

@Component
public class ScheduleFromAzureCloudStorageToDisk extends RouteBuilder {

    protected Logger logger = Logger.getLogger(getClass());

    @Override
    public void configure() throws Exception
    {
        logger.info("Start setting up FromAzureCloudStorageToDisk");

        from("scheduler://fileInAzureBlobStorage?delay=30000")  // Trigger action every 30 seconds, number is in milliseconds
            .routeId("FromAzureStorageToDiskRoute")
            .process(this::downloadFromAzureCloudStorageToDisk); // .process((exchange) -> downloadFromAzureCloudStorageToDisk(exchange))

        logger.info("Finished setting up FromAzureCloudStorageToDisk");
    }

    private void downloadFromAzureCloudStorageToDisk(Exchange exchange)
    {
        ...
    }

}
</code></pre>
<h2>Using Camel Quartz2 component as trigger</h2>
<p>If you are working with a legacy application, you might use older versions of Camel. In older version of Camel, Camel does not have support for pure CRON component.</p>
<p>Instead, it has Quartz and Quartz2 components that provide a scheduled delivery of messages using the Quartz Scheduler version 2.x.</p>
<p>Difference between Quartz and Quartz2 is in its API on lower levels and availability in Camel version. Noticeable distinguish in the fact that Quartz2 offers a few more options. So selection and usage of correct Quartz component I will let decision on you.</p>
<pre><code>package com.codepills.routes;

import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

@Component
public class ScheduleFromAzureCloudStorageToDisk extends RouteBuilder {

    protected Logger logger = Logger.getLogger(getClass());

    @Override
    public void configure() throws Exception
    {
        logger.info("Start setting up FromAzureCloudStorageToDisk");

        from("quartz2://import/azure-file?cron=0/30+*+*+*+*+?") // CRON format for every 30 seconds
            .routeId("FromAzureStorageToDiskRoute")
            .process(this::downloadFromAzureCloudStorageToDisk); // .process((exchange) -> downloadFromAzureCloudStorageToDisk(exchange))

        logger.info("Finished setting up FromAzureCloudStorageToDisk");
    }

    private void downloadFromAzureCloudStorageToDisk(Exchange exchange)
    {
        ...
    }

}
</code></pre>
<p>Let&#8217;s explain code above. We have created Spring component <i>ScheduleFromAzureCloudStorageToDisk</i> extending <i>RouteBuilder</i> class. We will implement trigger in <i>configure()</i> method. We will place Quartz2 component into the <i>from</i> method, which will build a route for Camel. Route in <i>from</i> method will have form as quartz2 component, then <i>import</i> trigger, then unique id name of import trigger (in our case <i>azure-file</i>) and lastly define time trigger in CRON format after <i>cron</i> parameter for import Quartz2 trigger.</p>
<p>Again, regarding <i>downloadFromAzureCloudStorageToDisk(final Exchange exchange)</i> method, you can find its implementation in article <a href="https://codepills.com/how-to-download-a-file-from-azure-claud-storage/" title="How to download a file from Azure Claud Storage">How to download a file from Azure Claud Storage</a> .</p>
<p>That is all. All magic regarding triggering on specific time happens in CRON setting.</p>
<h3>How to set up CRON </h3>
<p>Since I know how hard and frustrating it is sometimes to set correct CRON format, here are a couple of examples to distinguish for you the order od time elements in CRON used in Quartz</p>
<p>Examples:</p>
<ul>
<li><code>0/30+*+*+*+*+?</code> Every 30 seconds</li>
<li><code>0+0+6+*+*+?</code> Every day at 6:00 AM</li>
<li><code>0+*+0/6+*+*+?</code> Every 6 hours</li>
</ul>
<p>If you would like to know how to write a CRON job, check the article <a href="https://codepills.com/simple-guide-write-cron-jobs/" title="How to write CRON jobs">How to write CRON jobs</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/how-to-trigger-action-with-scheduler-and-quartz-in-camel/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to build with Maven without running tests</title>
		<link>https://codepills.com/how-to-build-with-maven-without-running-tests/</link>
					<comments>https://codepills.com/how-to-build-with-maven-without-running-tests/#comments</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Thu, 03 Dec 2020 14:44:49 +0000</pubDate>
				<category><![CDATA[Tips & tricks]]></category>
		<category><![CDATA[build]]></category>
		<category><![CDATA[JAR]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[optimization]]></category>
		<category><![CDATA[POM]]></category>
		<category><![CDATA[speed]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[SpringBoot]]></category>
		<category><![CDATA[Surefire]]></category>
		<category><![CDATA[tests]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1084</guid>

					<description><![CDATA[This article will show you multiple ways how to skip the test in your Maven build <a href="https://codepills.com/how-to-build-with-maven-without-running-tests/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>Do you try to build your app after the slightest change in code, and it takes ages to pass all the tests? What if there would be a workaround to obey all unnecessary tests and significantly shorten the Maven build time. And all that just but simple maven flag.</p>
<p><span id="more-1084"></span></p>
<p>Whether you want to build your SpringBoot app into the executable JAR file or build classes for a package, remember to use the single Maven flag parameter <code>mvn install -DskipTests</code>, and in the most cases, you will be fine.</p>
<p>However, the rabbit might run deeper, so it will be better to write a bit more info.</p>
<p><code>-DskipTests</code> option only works from Surefire 2.4. Unfortunately, there are no error messages if you do try to use it with Surefire 2.3 or lower. Therefore, your first task is to check your version of Surefire. For this, run <code>mvn -X test</code> and look for a line that mentions surefire. It should look like this: <code>maven-surefire-plugin: resolved to version 2.3 from repository central</code>. If you use pre-Surefire-2.4 start using <code>-Dmaven.test.skip=true</code>.</p>
<p>Fortunately beyond 2020 older version usage shrinks and you should remember to always favor a <code>-DskipTests </code> above <code>-Dmaven.test.skip=true</code>.</p>
<p>Surefire itself is the intermediate plugin between Maven and JUnit/TestNG for which while <code>-DskipTests </code> works and <code>-Dmaven.test.skip=true</code> works for compiler.</p>
<p>You can find (not really much more) additional info about shortening the build time trough skipping the project tests at <a href="https://maven.apache.org/surefire/maven-surefire-plugin/examples/skipping-tests.html" target="_blank" rel="nofollow noopener">maven skipping tests</a> site.</p>
<p>You can add this plugin configuration to your pom if you do not want to set command line arguments:</p>
<pre><code class="language-xml">&lt;plugin&gt;
    &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
    &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;
    &lt;configuration&gt;
        &lt;skipTests&gt;true&lt;/skipTests&gt;
    &lt;/configuration&gt;
&lt;/plugin&gt;</code></pre>
<p>Or you can also set skipping tests in you POM file over property:</p>
<pre><code class="language-xml">&lt;properties&gt;
    &lt;maven.test.skip&gt;true&lt;/maven.test.skip&gt;
&lt;/properties&gt;</code></pre>
<p><b>Bonus</b></p>
<p>You can also skip tests in IntelliJ Idea. Just go to Maven tool tab and hit <b>&#8216;Skip Test&#8217;</b> mode.</p>
<p><img decoding="async" class="size-full wp-image-1085 aligncenter" src="https://codepills.com/wp-content/uploads/2020/12/skip_test_maven_in_intellij_idea.png" alt="Skip test Maven in IntelliJ Idea" width="369" height="109" srcset="https://codepills.com/wp-content/uploads/2020/12/skip_test_maven_in_intellij_idea.png 369w, https://codepills.com/wp-content/uploads/2020/12/skip_test_maven_in_intellij_idea-300x89.png 300w" sizes="(max-width: 369px) 100vw, 369px" /></p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/how-to-build-with-maven-without-running-tests/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Angular calendar datepicker creates incorrect date one day behind the selection</title>
		<link>https://codepills.com/angular-calendar-datepicker-creates-incorrect-date-one-day-behind-the-selection/</link>
					<comments>https://codepills.com/angular-calendar-datepicker-creates-incorrect-date-one-day-behind-the-selection/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Sat, 22 Jun 2019 12:51:03 +0000</pubDate>
				<category><![CDATA[Bug hunt]]></category>
		<category><![CDATA[Angular]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[Spring]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1015</guid>

					<description><![CDATA[In this article, we will be looking at Angular datepicker and transferring the correct date through the REST endpoint. <a href="https://codepills.com/angular-calendar-datepicker-creates-incorrect-date-one-day-behind-the-selection/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>I was working on the bug fix task, which aimed to solve an extraordinary issue at first sight. In the monolithic Angular-Spring application, I choose a specific date at the front end with an Angular calendar datepicker. However, the database suddenly saved one day before the initially selected date.</p>
<p><span id="more-1015"></span></p>
<p>I started investigating the cause of the issue. First, I examined with Spring backend REST endpoint call with the breakpoint. The entity with the date was already coming incorrect from the Angular frontend. The backend endpoint on entry showed incorrect data, so the error was automatically not in the backend code.</p>
<p>At the frontend call for the backend REST endpoint, I also used <code>JSON.stringify(object)</code> to check if the produced entity which was leaving the frontend to the backend was correct. What I found was that it was also already incorrect.</p>
<p>Consequently, the issue happened somewhere between the user browser and Angular call for the backend. In this way, I also eliminated the possibility that the problem was somewhere in the Spring JSON conversion library (I used Jackson).</p>
<p>In the end, I figured it out. The issue was in class, which was migrating datepicker form data into the object. While the Angular calendar datepicker <u>collect the date from the browser also with local time zone</u> as a string, data to JSON ware pushed as a JavaScript <code>Date</code> class without a time zone. So if you, for example, pickup up any date, it was selected as the date for midnight with the timezone offset and transferred from string to <code>Date</code> as the day before due the offset counted as date subtraction.</p>
<p>I was working in Central Europe. In the case of Central Europe (CET), where I was working, the browser records +1 hour from GMT in datepicker based on local PC time settings. So if I pick up the date, hours and minutes are selected for midnight (00:00). However, <code>Date</code> class takes the datepicker string and subtract the negative offset from midnight and set a selected date for a day before.</p>
<p>This is the Angular&#8217;s datepicker component HTML code from the component form:</p>
<pre><code class="language-typescript">&lt;div class="ui-g-6"&gt;
    &lt;div&gt;
        &lt;label for="startDate"&gt;Start Date&lt;/label&gt;
    &lt;/div&gt;
    &lt;vrm-form-field [control]="editForm.controls['startDate']"&gt;
        &lt;p-calendar id="startDate"
            [formControlName]="'startDate'"
            dateFormat="yy-mm-dd"
            yearRange="1900:2100"&gt;
        &lt;/p-calendar&gt;
    &lt;/vrm-form-field&gt;
&lt;/div&gt;</code></pre>
<p>Following static function created an object from form datepicker which was pushed to REST endpoint before the fix:</p>
<pre><code class="language-typescript">static mapFromFormData(form: any) {
    return new ImportantDate(form.startDate);
}</code></pre>
<p>To fix the problem, I created a workaround. I made a Utility class with <code>moment library</code>, which takes a datepicker string and select only required date information.</p>
<pre><code class="language-typescript">export class Utils {
  public static formatDate(date: any): string {
    if (date === undefined || date === null) {
      return undefined;
    } else {
      return moment(date).format('YYYY-MM-DD');
    }
  }
}</code></pre>
<p>You can see the implementation of the static Utils method, which fixed the date.</p>
<pre><code class="language-typescript">static mapFromFormData(form: any) {
    return new ImportantDate(
        Utils.formatDate(form.startDate)
    );
}</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/angular-calendar-datepicker-creates-incorrect-date-one-day-behind-the-selection/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>3 basic mistakes for NullPointerException when Mock</title>
		<link>https://codepills.com/3-basic-mistakes-for-nullpointerexception-when-mock/</link>
					<comments>https://codepills.com/3-basic-mistakes-for-nullpointerexception-when-mock/#comments</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Thu, 10 May 2018 12:00:47 +0000</pubDate>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[mocking]]></category>
		<category><![CDATA[mockito]]></category>
		<category><![CDATA[Spring]]></category>
		<guid isPermaLink="false">http://codepills.com/?p=958</guid>

					<description><![CDATA[This article is a shortlist of the three most common reasons why you get NullPointerException in your tests. <a href="https://codepills.com/3-basic-mistakes-for-nullpointerexception-when-mock/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>You might get <code>NullPointerException</code> exception when you try to mock object in your tests. This article is a shortlist of the three most common reasons why this might be happening.</p>
<p><span id="more-958"></span></p>
<p>Here is a working example of DocumentRepositoryTest class for reference:</p>
<pre><code class="language-java">@RunWith(MockitoJUnitRunner.class)
public final class DocumentRepositoryTest {

    @Mock
    private DocumentRepository documentRepository;

    @Test
    public void testConvertToNewDocument() {
        String paperColor = new String("white");
        Mockito.when(this.documentRepository.getPaperColor()).thenReturn(paperColor);
        String color = this.documentRepository.getDocumentColor();
        Assert.assertThat(color, is(new String("white"));
    }
}</code></pre>
<p>DocumentRepositoryTest class is mocking <code>documentRepository</code> object.</p>
<p>So you are running your test and suddenly you see <code>NullPointerException</code>:</p>
<pre><code class="language-bash">java.lang.NullPointerException at com.your.custom.clazz.Method.insertTest(CustomServiceTest.java:50)</code></pre>
<p>You looked it up, and it seems your test is written correctly. So what might be a problem if you know how the mocking works?</p>
<p>If you are sure by your mocking skills, the issue will be probably somewhere else. And most likely very trivial. Here is a list of 3 things you should check out.</p>
<p><strong>1. Return something for your Mock.</strong></p>
<p>Most likely, you mistyped returning function. You probably wanted to return the value for the mocked object. So instead of <code>when-thenReturn</code> , you might type just <code>when-then</code>. Maybe it was IntelliSense. Maybe you did it accidentally. But for sure, <code>NullPointerException</code> happened because you want something which is not there. Debug and check if you are returning something.</p>
<p><strong>2. Specify Mockito running class</strong></p>
<p>Don&#8217;t forget to annotate your Testing class with <code>@RunWith(MockitoJUnitRunner.class)</code>. Most of the people just forget to specify the test runner, running class for mocking.</p>
<p><strong>3. You need to annotate the mocking object with the <code>@Mock</code> annotation</strong></p>
<p>If you want to mock an object, you need to annotate the object with <code>@Mock</code> annotation.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/3-basic-mistakes-for-nullpointerexception-when-mock/feed/</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
	</channel>
</rss>
