<?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>Tutorials &#8211; CodePills.com</title>
	<atom:link href="https://codepills.com/category/tutorials/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 14:11:03 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	
	<item>
		<title>How to connect to an EC2 instance over SSH</title>
		<link>https://codepills.com/how-to-connect-to-an-ec2-instance-over-ssh/</link>
					<comments>https://codepills.com/how-to-connect-to-an-ec2-instance-over-ssh/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Fri, 01 Mar 2024 09:10:48 +0000</pubDate>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Amazon Web Services]]></category>
		<category><![CDATA[AWS]]></category>
		<category><![CDATA[EC2]]></category>
		<category><![CDATA[EC2 instance]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[PuTTY]]></category>
		<category><![CDATA[PuTTYgen]]></category>
		<category><![CDATA[remote access]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[SSH]]></category>
		<category><![CDATA[SSH client]]></category>
		<category><![CDATA[windows]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1412</guid>

					<description><![CDATA[The article outlines connecting to an Amazon EC2 instance via SSH, detailing prerequisites and steps for Unix-based systems as well as Windows users, including PuTTY private key conversion. <a href="https://codepills.com/how-to-connect-to-an-ec2-instance-over-ssh/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>This article is a simple guide detailing the prerequisites and step-by-step procedures for connecting to EC2 instances via SSH. It covers Unix-based systems and Windows users, including the conversion of private key files for PuTTY.</p>
<p><span id="more-1412"></span></p>
<h2>Introduction</h2>
<p>SSH (Secure Shell) is a popular, secure protocol for remote access to servers and other network devices. When you launch an EC2 instance, you can connect to it using SSH to manage the server, install and update software, configure settings, and perform other administrative tasks.</p>
<ul>
<li id="prerequisites">Prerequisites</li>
<li id="connecting-over-unix-based-systems">Connecting over Unix-based systems</li>
<li id="connecting-over-windows">Connecting over Windows</li>
</ul>
<h2 id="prerequisites">Prerequisites</h2>
<p>Before you can connect to an EC2 instance over SSH, you need the following:</p>
<ul>
<li>Running EC2 instance and accessible over the network.</li>
<li>The EC2 instance&#8217;s IP address or public DNS.</li>
<li>The appropriate security group configured to allow SSH access (port 22) from your IP address or network.</li>
<li>The private key file (.pem) corresponding to the key pair used when launching the instance.</li>
</ul>
<p>Remember to keep your private key file secure and not share it with anyone. It is the key to accessing your EC2 instance.</p>
<p>If you encounter any issues while connecting, double-check that your instance is running, that the security group allows SSH access from your IP address, or that you are using the correct private key file.</p>
<h2 id="connecting-over-unix-based-systems">Connecting over Unix-based systems</h2>
<p>To connect to your EC2 instance via SSH at Unix-based systems like Linux, macOS, or others, follow these steps:</p>
<h3>Locate the private key file</h3>
<p>Find the private key file (.pem) you downloaded when you created the EC2 instance.</p>
<p>Make sure you have the correct permissions to use the private key file. On Linux or macOS, you can set the permissions using the command:</p>
<pre><code class="language-bash">chmod 400 /path/to/your/private-key.pem</code></pre>
<h3>Connect to the EC2 instance using SSH</h3>
<p>Open a terminal or command prompt and use the `ssh` command to connect to your EC2 instance:</p>
<pre><code class="language-bash">ssh -i /path/to/your/private-key.pem ec2-user@&lt;public-dns-or-ip&gt;</code></pre>
<ul>
<li>Replace <code>/path/to/your/private-key.pem</code> with the real path to your private key file.</li>
<li>Replace <code>&lt;public-dns-or-ip&gt;</code> with the public DNS or IP address of your EC2 instance.</li>
<li>If you&#8217;re using a different username than <b>ec2-user</b> (e.g., for Ubuntu instances, it&#8217;s usually <b>ubuntu</b>), modify the command accordingly.</li>
</ul>
<p>Here&#8217;s an example of the SSH command:</p>
<pre><code class="language-bash"> ssh -i ~/Downloads/my-key-pair.pem ec2-user@ec2-1-25-67-980.us-west-2.compute.amazonaws.com</code></pre>
<h3>Accept the server&#8217;s host key</h3>
<p>If it&#8217;s your first time connecting to the instance, the server may prompt you to accept its host key. Type <i>yes</i> and press Enter to continue.</p>
<h3>Connection to EC2 instance</h3>
<p>Success! You should now have successfully connected to your EC2 instance via SSH.</p>
<h2 id="connecting-over-windows">Connecting over Windows</h2>
<p>If you&#8217;re using Windows and don&#8217;t have the <code>ssh</code> command available, you can use an SSH client like PuTTY:</p>
<ul>
<li>First, convert your private key file (.pem) to a format compatible with PuTTY (.ppk) using PuTTYgen. If you do not know how, just <a href="#generating_a_ppk_file_from_a_pem_file">check the section below</a>.</li>
<li>Open PuTTY and enter the public IPv4 DNS or IP address of your EC2 instance in the <i>&#8220;Host Name (or IP address)&#8221;</i> field. Keep <i>&#8220;Connection type&#8221;</i> as <i>&#8220;SSH&#8221;</i>.</li>
<li>From the <i>&#8220;Connection&#8221;</i> category in left tree navigation, select <i>&#8220;SSH -> Auth&#8221;</i> and click on <i>&#8220;Credentials&#8221;</i>.</li>
<li>For <i>&#8220;Private key file for authentication&#8221;</i> click on <i>&#8220;Browse&#8221;</i> and select the private key file (.ppk).</li>
<li>Click on <i>&#8220;Open&#8221;</i> to initiate the SSH connection. At <i>&#8220;Putty Security Alert&#8221;</i>, click <i>&#8220;Yes&#8221;</i> to accept the server&#8217;s host key.</li>
</ul>
<h3 id="generating_a_ppk_file_from_a_pem_file">Generating a .ppk file from a .pem file</h3>
<p>To convert your private key file (.pem) to a .ppk file for use with PuTTY, follow these steps:</p>
<ul>
<li>Open PuTTY Key Generator (PuTTYgen) and click on <i>&#8220;Load&#8221;</i> to select your private key file (.pem).</li>
<li>Click on <i>&#8220;Save private key&#8221;</i> to convert the key to PuTTY&#8217;s .ppk format and save it to a location of your choice.</li>
<li>You can now connect the converted .ppk file with PuTTY to your EC2 instance.</li>
</ul>
<h2>Conclusion</h2>
<p>This article has shown how to connect to an Amazon EC2 instance over SSH. Following the steps outlined above, you can securely access your EC2 instance and manage it remotely using SSH.</p>
<p>Be sure to store your private key file securely and avoid sharing it with others, as it serves as the gateway to accessing your Amazon EC2 instance.</p>
<p>If you face any connection issues, verify that your instance is operational, that your security group permits SSH access from your IP address, and that you employ the correct private key file.</p>
<p>Did you find connecting to your EC2 instance over SSH easy? Do you have tips or another way to connect to an EC2 instance? Let us know in the comments below. We&#8217;d love to hear your ideas and experiences.</p>
<p>Thanks for reading!</p>
<p>Like this article? Please share it with your friends and help us grow. Happy coding! 😊</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/how-to-connect-to-an-ec2-instance-over-ssh/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Java concurrency interview conversation about passing shared variables to threads</title>
		<link>https://codepills.com/java-concurrency-interview-conversation-about-passing-shared-variables-to-threads/</link>
					<comments>https://codepills.com/java-concurrency-interview-conversation-about-passing-shared-variables-to-threads/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Thu, 01 Jun 2023 08:00:03 +0000</pubDate>
				<category><![CDATA[Java Concurrency]]></category>
		<category><![CDATA[Java concurrency]]></category>
		<category><![CDATA[Java interview]]></category>
		<category><![CDATA[Java threads]]></category>
		<guid isPermaLink="false">http://codekopf.com/?p=1</guid>

					<description><![CDATA[During one interview, I talked with the interviewer about how Java handles Threads and passed references to threads and pitfalls of concurrency in general. <a href="https://codepills.com/java-concurrency-interview-conversation-about-passing-shared-variables-to-threads/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>During one interview, I got a pretty nice Java concurrency interview question. It was more or less a conversation between me and the interviewer about how Java handles Threads and passing references, plus ideas on solving concurrency pitfalls.</p>
<p>Let&#8217;s take a while and simulate such a conversation so you can be prepared for your next Java concurrency interview.</p>
<p><span id="more-854"></span></p>
<p>The whole ping-pong between interviewer and candidate is to test the candidate&#8217;s ability and knowledge of Java concurrency and way of handling access to shared variables.</p>
<h2>Two threads with the same primitive int as argument</h2>
<p>So, the narrative of the conversation goes like this:</p>
<blockquote><p>Create two Java Threads. Each Thread takes the same single <i>primitive int</i> as an argument to its constructor. Let the first thread increment <i>primitive int</i> to 100 million. Let the second Thread increment the same shared variable to 20 million. How will look the output of both threads at the end of the incrementation?</p></blockquote>
<p>So as you might guess already, this example will go in the way of figuring out if incrementing <i>primitive int</i> will be <strong>concurrent safe</strong>. What is meant by that, it incrementing the <i>primitive int</i> in one Thread will not influence the shared variable in the other Thread and vice versa.</p>
<p>Should both threads print 20 million, 100 million or one print count of 20 million and the second 100 million?</p>
<pre><code class="language-java">public class Main {
    public static void main(String[] args) {
        int sharedInt = 0;
        TOne tOne = new TOne(sharedInt);
        TTwo tTwo = new TTwo(sharedInt);
        tOne.start();
        tTwo.start();
    }
}

class TOne extends Thread {
    private int sharedInt;

    public TOne(int sharedInt) {
        this.sharedInt = sharedInt;
    }

    public void run() {
        for (int i = 0; i < 100_000_000; i++) {
            this.sharedInt += 1;
        }
        System.out.println("tOne: The shared primitive int is: " + this.sharedInt);
    }
}

class TTwo extends Thread {
    private int sharedInt;

    public TTwo(int sharedInt) {
        this.sharedInt = sharedInt;
    }

    public void run() {
        for (int i = 0; i < 20_000_000; i++) {
            this.sharedInt += 1;
        }
        System.out.println("tTwo: The shared primitive int is: " + this.sharedInt);
    }
}</code></pre>
<p>Let's put the code to the file name <i>Main.java</i>, compile it and run it. As you can see, the <i>tTwo</i> execute immediately as it increments much lower than <i>tOne</i>. Both threads show the results as expected, although <i>tTwo</i> finished before <i>tOne</i>, which does not look correct.</p>
<pre><code class="language-bash">tTwo: The shared primitive int is: 20000000
tOne: The shared primitive int is: 100000000</code></pre>
<p>Would there be a way for <i>tTwo</i> to wait for <i>tOne</i>? What will be the output? We still do not know if they share the variable <i>sharedInt</i> of primitive <i>int</i>, if to <i>tTwo</i> takes a shorter time to execute as to <i>tOne</i>.</p>
<h2>One Thread waits for another one to finish</h2>
<p>We need to adjust our code slightly. We need to use <i>Thread</i> class <i>join()</i> method.</p>
<p>The whole premise of calling <i>join()</i> method upon calling Thread is for calling Thread to stop and go to a waiting state. <strong>Calling Thread will remain to wait until the referenced Thread upon which the <i>join()</i> method was called terminates.</strong> This way we block <i>tTwo</i> before executing.</p>
<pre><code class="language-java">public class Main {
    public static void main(String[] args) throws InterruptedException {
        int sharedInt = 0;
        TOne tOne = new TOne(sharedInt);
        TTwo tTwo = new TTwo(sharedInt);
        tOne.start();
        tOne.join();
        tTwo.start();
    }
}

class TOne extends Thread {
    private int sharedInt;

    public TOne(int sharedInt) {
        this.sharedInt = sharedInt;
    }

    public void run() {
        for (int i = 0; i < 100_000_000; i++) {
            this.sharedInt += 1;
        }
        System.out.println("tOne: The shared primitive int is: " + this.sharedInt);
    }
}

class TTwo extends Thread {
    private int sharedInt;

    public TTwo(int sharedInt) {
        this.sharedInt = sharedInt;
    }

    public void run() {
        for (int i = 0; i < 20_000_000; i++) {
            this.sharedInt += 1;
        }
        System.out.println("tTwo: The shared primitive int is: " + this.sharedInt);
    }
}</code></pre>
<p>Let's compile and run the code above:</p>
<pre><code class="language-bash">tOne: The shared primitive int is: 100000000
tTwo: The shared primitive int is: 20000000</code></pre>
<p>When we run the code, we conclude that even though the variable is shared, it is isolated in the threads. <strong>The reason is that each Java Thread on its creation allocates and creates resources. And primitive types make their copies; they do not pass as a reference on the new threads.</strong> However, will this rule apply to object-type variables?</p>
<h2>Two threads with the same Integer variable as argument</h2>
<p>But what if we will use <i>Object</i> variable instead <i>primitive int</i> type? Will it be the same? Will the instance of the object also be isolated?</p>
<pre><code class="language-java">public class Main {
    public static void main(String[] args) throws InterruptedException {
        Integer sharedInt = 0;
        TOne tOne = new TOne(sharedInt);
        TTwo tTwo = new TTwo(sharedInt);
        tOne.start();
        tTwo.start();
    }
}

class TOne extends Thread {
    private Integer sharedInt;

    public TOne(Integer sharedInt) {
        this.sharedInt = sharedInt;
    }

    public void run() {
        for (int i = 0; i < 100_000_000; i++) {
            this.sharedInt += 1;
        }
        System.out.println("tOne: The shared object Integer is: " + this.sharedInt);
    }
}

class TTwo extends Thread {
    private Integer sharedInt;

    public TTwo(Integer sharedInt) {
        this.sharedInt = sharedInt;
    }

    public void run() {
        for (int i = 0; i < 20_000_000; i++) {
            this.sharedInt += 1;
        }
        System.out.println("tTwo: The shared object Integer is: " + this.sharedInt);
    }
}</code></pre>
<p>The output of the code above is surprisingly correct:</p>
<pre><code class="language-bash">tTwo: The shared object Integer is: 20000000
tOne: The shared object Integer is: 100000000</code></pre>
<p>Both threads are doing relatively well. However, with a close inspection under the hood, we find out something fishy is happening. If we look better at the assigned references to <i>sharedInt</i>, both threads have assigned the same reference before the thread executions. However, after the run, the <i>sharedInt</i> in <i>tOne</i> had assigned a different reference. Thus, while the output is correct, each Thread's referenced object changes. Therefore, each Thread on every iteration assigns a new object to <i>sharedInt</i>. Consequently, at the end of execution, the different object is printed.</p>
<p>Rather than using the object variable of <i>Integer</i> class, let's make a wrapping class around the <i>count</i> so the passed object variable will not change. What will change will be its internal state. Here is a code with <i>Wrapper</i> class:</p>
<pre><code class="language-java">public class Main {
    public static void main(String[] args) throws InterruptedException {
        Wrapper wrapper = new Wrapper(0);
        TOne tOne = new TOne(wrapper);
        TTwo tTwo = new TTwo(wrapper);
        tOne.start();
        tTwo.start();
    }
}

class TOne extends Thread {
    private Wrapper wrapper;

    public TOne(Wrapper wrapper) {
        this.wrapper = wrapper;
    }

    public void run() {
        synchronize {
            for (int i = 0; i < 100_000_000; i++) {
                this.wrapper.increment();
            }
            System.out.println("tOne: Count is " + this.wrapper.printCount());
        }
    }
}

class TTwo extends Thread {
    private Wrapper wrapper;

    public TTwo(Wrapper wrapper) {
        this.wrapper = wrapper;
    }

    public void run() {
        synchronize {
            for (int i = 0; i < 20_000_000; i++) {
                this.wrapper.increment();
            }
            System.out.println("tTwo: Count is " + this.wrapper.printCount());
        }
    }
}

class Wrapper {
    private Integer count;

    public Wrapper(Integer count) {
        this.count = count;
    }

    public void increment() {
        this.count++;
    }

    public Integer printCount() {
        return this.count;
    }
}</code></pre>
<p><strong>Result is shocking!</strong> More and more you try, you will get slightly different numbers every time. The result is not 20 million, nor 100, or 120. Why?! As you can see, there is clearly a problem with synchronization and keeping the isolated internal state of the wrapper from one Thread to another.</p>
<pre><code class="language-bash">tTwo: Count is 22095354
tOne: Count is 104408141</code></pre>
<p>The whole concurrency is about keeping the data isolated from one Thread to another. We ended the interview section as the conversation showed several vital elements of your concurrency knowledge. You successfully demonstrated mastery of the difference between passing reference for primitive and object variables, ways for synchronizing threads and how to show and estimate concurrent output.</p>
<p>The interview might continue, and the interviewer might challenge you to fix the issues. So formalize the problem with the current solution and figure out how to fix the current situation and isolate the internal state of the wrapper.</p>
<h2>Passing object and isolating its internal state</h2>
<p>How can we isolate the internal state? How to secure the synchronization of internal variables?</p>
<p>The question is now, thus, how we can fix the current situation. There are several mechanisms in Java to keep the inner state concurrent. It would be worth telling about each of them in a separate article. But you might start discussing each Java concurrency mechanism with the interviewer, how it can fix the code, and what the output will be.</p>
<p>Let's show one way to fix the issue, which will be through the use of <b>Locks</b>.</p>
<pre><code class="language-java">import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Wrapper wrapper = new Wrapper(0);
        TOne tOne = new TOne(wrapper);
        TTwo tTwo = new TTwo(wrapper);
        tOne.start();
        tTwo.start();
        // tOne.join();
        // tTwo.join();
        System.out.println("Final count: " + wrapper.printCount());
    }
}

class TOne extends Thread {
    private Wrapper wrapper;

    public TOne(Wrapper wrapper) {
        this.wrapper = wrapper;
    }

    public void run() {
        this.wrapper.getLock();
        try {
            for (int i = 0; i < 100_000_000; i++) {
                this.wrapper.increment();
            }
        } finally {
            this.wrapper.unlock();
        }
        System.out.println("tOne: Count is " + this.wrapper.printCount());
    }
}

class TTwo extends Thread {
    private Wrapper wrapper;

    public TTwo(Wrapper wrapper) {
        this.wrapper = wrapper;
    }

    public void run() {
        this.wrapper.getLock();
        try {
            for (int i = 0; i < 20_000_000; i++) {
                this.wrapper.increment();
            }
        } finally {
            this.wrapper.unlock();
        }
        System.out.println("tTwo: Count is " + this.wrapper.printCount());
    }
}

class Wrapper {
    private Integer count;
    private Lock lock;

    public Wrapper(Integer count) {
        this.count = count;
        this.lock = new ReentrantLock();
    }

    public void getLock() {
        lock.lock();
    }

    public void unlock() {
        lock.unlock();
    }

    public void increment() {
        this.count++;
    }

    public Integer printCount() {
        return this.count;
    }
}</code></pre>
<p>If you choose not to use <i>join()</i> methods for both threads, the main Java thread will execute first and will leave the two other threads running in parallel. The output will be like this:</p>
<pre><code class="language-bash">Final count: 0
tOne: Count is 100000000
tTwo: Count is 120000000</code></pre>
<p>However, if you decide to use <i>join()</i> method, the output will be as follows:</p>
<pre><code class="language-bash">tOne: Count is 100000000
tTwo: Count is 120000000
Final count: 120000000</code></pre>
<h2>Conclusion</h2>
<p>As said before, the whole concept of concurrency is about keeping the data isolated from one Thread to another. You can use this conversation to prepare for an interview for your understanding of concurrent mechanisms. But the successful demonstration of concepts demonstrated your knowledge of the difference between passing reference for primitive variables and object variables, ways for synchronizing threads and how to show and estimate concurrent output.</p>
<p>Don't come only with answers to the interviewers' questions. Try to come also with solutions to problems and pitfalls of concurrency.</p>
<p>And for interviewers, there are several alternatives of how the interview conversation might go between you and the candidate. Suppose this conversation about concurrency inspires you. In that case, you might challenge the candidate to come up with different solutions, can for example, obey using a wrapper and instead focus on handling the situation with <b>volatile</b> or <b>synchronization</b> keyword.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/java-concurrency-interview-conversation-about-passing-shared-variables-to-threads/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Selenium &#8211; remove html element from the DOM</title>
		<link>https://codepills.com/selenium-remove-html-element-from-the-dom/</link>
					<comments>https://codepills.com/selenium-remove-html-element-from-the-dom/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Mon, 03 Jan 2022 08:58:53 +0000</pubDate>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[drivers]]></category>
		<category><![CDATA[finviz.com]]></category>
		<category><![CDATA[Firefox]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Selenium]]></category>
		<category><![CDATA[stocks]]></category>
		<category><![CDATA[time-series]]></category>
		<category><![CDATA[web-scrapper]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1280</guid>

					<description><![CDATA[This article will show you how to remove elements from <b>HTML DOM</b> (Document Object Model) when using automated web-browser framework <b>Selenium</b>. <a href="https://codepills.com/selenium-remove-html-element-from-the-dom/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>This article will show you how to remove elements from <b>HTML DOM</b> (Document Object Model) when using automated web-browser framework <b>Selenium</b>. If you want to remove anything you do not want on your site during web-scraping, you came to the right Selenium tutorial.</p>
<p><span id="more-1280"></span></p>
<h2>Introduction</h2>
<p>Let&#8217;s start with a practical example of removing elements from DOM. Imagine scrapping a website with <b>Selenium</b> and taking a screenshot of the page. However, the timed modal window will unannounced pop up when Selenium&#8217;s driver spin the browser window. So it is probably a good idea to remove the window before taking a picture in such a case.</p>
<p>When scrapping sites, removing excessive advertisement and disturbing elements is hard enough. But pop-up windows in the wrong moments are an overall user experience nowadays on many sites and blogs.</p>
<p>For example, we want to scrap stock time-series from famous sites like finviz.com. Unfortunately, after the first few seconds on the page, the cookies modal window pop-up and block the stock graph. Therefore, I will need to remove the cookie allowance modal window to take a clear screenshot.</p>
<div id="attachment_1281" style="width: 650px" class="wp-caption alignnone"><img fetchpriority="high" decoding="async" aria-describedby="caption-attachment-1281" src="https://codepills.com/wp-content/uploads/2022/01/finviz_cookie_popup-1024x768.png" alt="Finviz.com cookie popup window" width="640" height="480" class="size-large wp-image-1281" srcset="https://codepills.com/wp-content/uploads/2022/01/finviz_cookie_popup-1024x768.png 1024w, https://codepills.com/wp-content/uploads/2022/01/finviz_cookie_popup-300x225.png 300w, https://codepills.com/wp-content/uploads/2022/01/finviz_cookie_popup-768x576.png 768w, https://codepills.com/wp-content/uploads/2022/01/finviz_cookie_popup.png 1098w" sizes="(max-width: 640px) 100vw, 640px" /><p id="caption-attachment-1281" class="wp-caption-text">Finviz.com cookie popup window</p></div>
<p>Let me show you two different ways to remove elements from Selenium&#8217;s HTML DOM. One way will be about eliminating parts that load with the page load and can be removed immediately. The second way will require calling <i>WebDriverWait</i> instance, and the way will be used for elements that pop up or load to page letter.</p>
<p>However, both options do not remove the element from the DOM. Instead, they hide it and make it invisible in the Selenium web driver.</p>
<h2>Remove elements from Selenium&#8217;s DOM without waiting</h2>
<pre><code class="language-java">FirefoxOptions options = new FirefoxOptions();
options.addArguments("-width=1920");
options.addArguments("-height=1080");
FirefoxDriver driver = new FirefoxDriver(options);

String stock = "T"; // AT&T Inc.
driver.get("https://finviz.com/quote.ashx?t=" + stock + "&ty=c&ta=1&p=d");

driver.executeScript("return document.getElementsByClassName('snapshot-table2')[0].remove();");</code></pre>
<p>If we look at the code, it might look straightforward. But I will go through it briefly. Initially, we set options for our Selenium Driver. Then, we pick Firefox as Selenium driver and put options (browser windows dimensions) into the driver itself.</p>
<p>After setting drivers options and instantiating Firefox drivers, we are clear to the call page in Firefox. We call finviz.com stock page for AT&#038;T Inc. company. The page which is loaded is immediately available for changes. If we want to remove any element we do not like, we can call script execution upon the loaded HTML DOM. We call executed script, which will remove the first  (0-th) element of the specific class name. It will be the first data table under the stock time-series graph.</p>
<p><b>Note</b> : If you have better idea for elements removal from Selenium&#8217;s HTML DOM, let me know in comments below.</p>
<h2>Remove elements from Selenium&#8217;s DOM with waiting</h2>
<pre><code class="language-java">FirefoxOptions options = new FirefoxOptions();
options.addArguments("-width=1920");
options.addArguments("-height=1080");
FirefoxDriver driver = new FirefoxDriver(options);

String stock = "T"; // AT&T Inc.
driver.get("https://finviz.com/quote.ashx?t=" + stock + "&ty=c&ta=1&p=d");

WebDriverWait wait = new WebDriverWait(driver, 10);

WebElement cookieWindow = wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("ConsentManager__Overlay-np32r2-0")));
driver.executeScript("return arguments[0].remove();", cookieWindow);</code></pre>
<p>The code above looks straightforward also. Initially, we set options for our Selenium Driver and picked Firefox as Selenium driver.</p>
<p>After setting drivers options and instantiating Firefox driver, we are clear to the call page in Firefox. We call the finviz.com stock page for AT&#038;T Inc. company and wait for 10 seconds or until HTML DOM does not contain an element with a specific class name. If it does, we will execute the script upon it, which will remove the first (the 0-th) element when it is found. Action means removing the whole pop-up modal window that appeared in the first 10 seconds of finviz.com page duration.</p>
<p>Class name &#8220;ConsentManager__Overlay-np32r2-0&#8221; is class name of pop-up cookie modal window. However, this class name might and surely will change in the future. So I would not rely on it for 100%. But for now, it serves our purpose.</p>
<h2>Conclusion</h2>
<p>This article has shown how remove elements from <b>HTML DOM</b> when using automated web-browser framework <b>Selenium</b>. Articles provide two different ways how to remove element on the page. Elements which load with page load can be removed immediately, without calling <i>WebDriverWait</i> instance. However, elements which pop-up or load to page letter needs to be removed with help of <i>WebDriverWait</i> instance.</p>
<p>However, if you look better, code snippets in the article can help you to build your Selenium web-scrapper 😉</p>
<p>Did you find element removal easy? Do you have your trick or know another way <u>how to remove elements from HTML DOM in Selenium</u>? Let us know in the comments below the article. We would like to hear your ideas and stories, and you might help others as well.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/selenium-remove-html-element-from-the-dom/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to connect Jira with IntelliJ IDEA</title>
		<link>https://codepills.com/how-to-connect-jira-with-intellij-idea/</link>
					<comments>https://codepills.com/how-to-connect-jira-with-intellij-idea/#comments</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Tue, 09 Mar 2021 14:19:05 +0000</pubDate>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[IntelliJ Idea]]></category>
		<category><![CDATA[Jira]]></category>
		<category><![CDATA[secure token]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1152</guid>

					<description><![CDATA[This tutorial will show you how to connect your IntelliJ IDEA with the Jira ticketing system. <a href="https://codepills.com/how-to-connect-jira-with-intellij-idea/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>For ease of development, we can connect the IntelliJ IDE with the Jira ticket service.</p>
<p><span id="more-1152"></span></p>
<p>We will need two different components to interconnect IntelliJ with Jira successfully. First, we will need to create an API token in Jira. Consequently, we need to interconnect IntelliJ IDEA with Jira.</p>
<h2>Jira API token creation</h2>
<p>We need to generate the API token in Jira, which will secure communication between IntelliJ and Jira.</p>
<p>1. In Jira, go to your profile and go to the option to change your password. This link should move you to Jira Security Profile at <a title="Jira profile security" href="https://id.atlassian.com/manage-profile/security" target="_blank" rel="nofollow noopener">https://id.atlassian.com/manage-profile/security</a> link.</p>
<p>2. Click on the <i>Create and manage API tokens</i> link from the API token section.</p>
<p><img decoding="async" class="size-full wp-image-1155 aligncenter" src="https://codepills.com/wp-content/uploads/2021/03/jira_security_profile.png" alt="Jira security profile" width="953" height="1012" srcset="https://codepills.com/wp-content/uploads/2021/03/jira_security_profile.png 953w, https://codepills.com/wp-content/uploads/2021/03/jira_security_profile-283x300.png 283w, https://codepills.com/wp-content/uploads/2021/03/jira_security_profile-768x816.png 768w" sizes="(max-width: 953px) 100vw, 953px" /></p>
<p>3. Here at the page <a title="Jira security API tokens page" href="https://id.atlassian.com/manage-profile/security/api-tokens" target="_blank" rel="nofollow noopener">https://id.atlassian.com/manage-profile/security/api-tokens</a> we can create API tokens.</p>
<p><img decoding="async" class="size-full wp-image-1156" src="https://codepills.com/wp-content/uploads/2021/03/jira_api_tokens.png" alt="Jira API tokens page" width="948" height="385" srcset="https://codepills.com/wp-content/uploads/2021/03/jira_api_tokens.png 948w, https://codepills.com/wp-content/uploads/2021/03/jira_api_tokens-300x122.png 300w, https://codepills.com/wp-content/uploads/2021/03/jira_api_tokens-768x312.png 768w" sizes="(max-width: 948px) 100vw, 948px" /></p>
<p>Go to blue <i>Create new token</i> bottom and click it.</p>
<p>4. New pop-up window will show up. Type a rememberable name for the token into the input field.</p>
<p><img loading="lazy" decoding="async" class="size-full wp-image-1158 aligncenter" src="https://codepills.com/wp-content/uploads/2021/03/token_for_intellij_name.png" alt="Jita API token for IntelliJ name" width="412" height="274" srcset="https://codepills.com/wp-content/uploads/2021/03/token_for_intellij_name.png 412w, https://codepills.com/wp-content/uploads/2021/03/token_for_intellij_name-300x200.png 300w" sizes="(max-width: 412px) 100vw, 412px" /></p>
<p>Hit <i>Create</i> button. A new API token will be generated (You should also get an email notification). You can see token plaintext when clicking on the icon of an eye in the field.</p>
<p><img loading="lazy" decoding="async" class="size-full wp-image-1157 aligncenter" src="https://codepills.com/wp-content/uploads/2021/03/new_api_token.png" alt="Jira new API token" width="412" height="276" srcset="https://codepills.com/wp-content/uploads/2021/03/new_api_token.png 412w, https://codepills.com/wp-content/uploads/2021/03/new_api_token-300x201.png 300w" sizes="(max-width: 412px) 100vw, 412px" /></p>
<p><img loading="lazy" decoding="async" class="size-full wp-image-1159 aligncenter" src="https://codepills.com/wp-content/uploads/2021/03/new_token_plaintext.png" alt="New token plaintext" width="411" height="272" srcset="https://codepills.com/wp-content/uploads/2021/03/new_token_plaintext.png 411w, https://codepills.com/wp-content/uploads/2021/03/new_token_plaintext-300x199.png 300w" sizes="(max-width: 411px) 100vw, 411px" /></p>
<p><b>Copy the token to some save location</b>. You will need it later.</p>
<p><b>Be aware that if you close the window, the token will be lost, and it will be not possible to see it again.</b></p>
<p><b>Note</b>: If you made a mistake and want to display the token again, it is not possible. Instead, you need to create a new token and go through the procedure of the new token generation again.</p>
<p>Remove the invalid token from the token list by clicking on <i>Revoke</i> bottom for individual token.</p>
<p><img loading="lazy" decoding="async" class="size-full wp-image-1153 aligncenter" src="https://codepills.com/wp-content/uploads/2021/03/revoke_api_token.png" alt="Revoke API token" width="412" height="225" srcset="https://codepills.com/wp-content/uploads/2021/03/revoke_api_token.png 412w, https://codepills.com/wp-content/uploads/2021/03/revoke_api_token-300x164.png 300w" sizes="(max-width: 412px) 100vw, 412px" /></p>
<p>Revoke API token pop-up window will close, and after successful removal, a new pop-up Notification will show in Jira to display successful removal.</p>
<h2>Connecting IntelliJ IDEA with Jira</h2>
<p>1. Open your desired project in <strong>IntelliJ IDEA</strong>.</p>
<p>2. Go to IntelliJ IDEA settings (<i>Ctrl</i> + <i>Alt</i> + <i>S</i>) and under <i>Tools</i> &gt; <i>Task</i> &gt; <i>Servers</i> add new Jira configuration. New Jira configuration is possible to add by hitting a <b>+</b> (plus sign) in the bottom left corner of Configurated servers list. Select <strong>JIRA</strong> option.</p>
<p><img loading="lazy" decoding="async" class="size-full wp-image-1160 aligncenter" src="https://codepills.com/wp-content/uploads/2021/03/adding_jira_in_intellij.png" alt="Adding Jira in Intellij" width="220" height="462" srcset="https://codepills.com/wp-content/uploads/2021/03/adding_jira_in_intellij.png 220w, https://codepills.com/wp-content/uploads/2021/03/adding_jira_in_intellij-143x300.png 143w" sizes="(max-width: 220px) 100vw, 220px" /></p>
<p>3. Add the following information to the Jira server settings:</p>
<p><img loading="lazy" decoding="async" class="size-full wp-image-1161" src="https://codepills.com/wp-content/uploads/2021/03/intellij_jira_integration.png" alt="Intellij Jira integration" width="998" height="722" srcset="https://codepills.com/wp-content/uploads/2021/03/intellij_jira_integration.png 998w, https://codepills.com/wp-content/uploads/2021/03/intellij_jira_integration-300x217.png 300w, https://codepills.com/wp-content/uploads/2021/03/intellij_jira_integration-768x556.png 768w" sizes="(max-width: 998px) 100vw, 998px" /></p>
<p><b>Server URL</b> &#8211; URL of your Jira</p>
<p><b>Email</b> &#8211; Add your Jira account email</p>
<p><b>API token</b> &#8211; Provide API token generated in Jira.</p>
<p><b>Search</b> &#8211; <code>assignee = currentUser() and project = XXXX and resolution = Unresolved order by updated.</code></p>
<p>The code in the search input field will give you your most recent task assigned to you at the top of the menu.</p>
<p><b>Test</b> your connection with Jira with the <i>Test</i> button.</p>
<p>If your connection to the Jira server was successful hit <b>Apply</b> and <b>OK</b> and close the <i>Settings</i> window. Now you can go into the right corner of the IntelliJ window, and you should see a drop-down menu showing you all connected tasks with Jira.</p>
<h2>Checking out a new task</h2>
<p>When checking out a new task, we can create immediately a new branch on which the task will be built.</p>
<p>Go to section Tasks and set up the settings according to the image below.</p>
<p><img loading="lazy" decoding="async" class="size-full wp-image-1154" src="https://codepills.com/wp-content/uploads/2021/03/intellij_tasks_option.png" alt="IntelliJ IDEA tasks option" width="1000" height="720" srcset="https://codepills.com/wp-content/uploads/2021/03/intellij_tasks_option.png 1000w, https://codepills.com/wp-content/uploads/2021/03/intellij_tasks_option-300x216.png 300w, https://codepills.com/wp-content/uploads/2021/03/intellij_tasks_option-768x553.png 768w" sizes="(max-width: 1000px) 100vw, 1000px" /></p>
<p>Changelist name format: <code>${id} ${summary}</code></p>
<p>Feature branch name format: <code>feature/${id} ${summary}</code></p>
<p>Settings like the picture above will secure that a new feature branch will be created when we check out a new task in the IntelliJ IDEA window.</p>
<h2>Conclusion</h2>
<p>In this short tutorial, we followed the steps to interconnect IntelliJ IDEA with your Jira account. One of the most critical parts is to keep the Jira API token. If you consider using them in other projects, keep the token in a separate secured file. Otherwise, do not be afraid to revoke tokens, if necessary, and create a new one.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/how-to-connect-jira-with-intellij-idea/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>How to sort a map with Java 8</title>
		<link>https://codepills.com/how-to-sort-a-map-with-java-8/</link>
					<comments>https://codepills.com/how-to-sort-a-map-with-java-8/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Sat, 06 Mar 2021 13:22:56 +0000</pubDate>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[generics]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java 8]]></category>
		<category><![CDATA[Map]]></category>
		<category><![CDATA[sort]]></category>
		<category><![CDATA[sorting]]></category>
		<category><![CDATA[streams]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1146</guid>

					<description><![CDATA[This tutorial shows how to sort Java Map implementations with Java 8 streams by map's key or value properties. <a href="https://codepills.com/how-to-sort-a-map-with-java-8/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>This tutorial will show how to sort <code>Map</code> implementations with the map&#8217;s key or value properties.</p>
<p><span id="more-1146"></span></p>
<h2>Introduction</h2>
<p>Every approach for sorting a map consists of a few consequent steps, no matter by which map&#8217;s property (key/value)n we want to sort <code>Map</code>.</p>
<h3>Basic sorting algorithm</h3>
<p>Sorting <code>Map</code> algorithm goes like this:</p>
<ul>
<li>First, we convert a <code>Map</code> into a <code>Stream</code></li>
<li>Second, we sort streaming elements</li>
<li>Third, we collect sorted elements, and we maintain order by placing elements into the correct data structure (<code>LinkedHashMap</code>)</li>
</ul>
<h3>HashMap entrySet() method in Java</h3>
<p>The <code>java.util.HashMap.entrySet()</code> method in Java is used to create a set out of the same elements contained in the <code>HashMap</code>. It returns a set of entries from the <code>HashMap</code>. Alternatively we can create a new set and store the map elements into it.</p>
<h2>Sort Map by Keys</h2>
<pre><code class="language-java">public void sortMapByKeys() {

    Map&lt;String, Integer&gt; unsortedMap = new HashMap<>();

    unsortedMap.put("z", 0);
    unsortedMap.put("b", 5);
    unsortedMap.put("a", 6);
    unsortedMap.put("e", 7);
    unsortedMap.put("k", 8);
    unsortedMap.put("f", 9);
    unsortedMap.put("n", 100);
    unsortedMap.put("o", -4);
    unsortedMap.put("m", 2);
    unsortedMap.put("d", 1);

    System.out.println("Unsorted map: ");
    System.out.println(unsortedMap);

    // We need a LinkedHashMap to keep an order of newly returned sorted map.
    Map&lt;String, Integer&gt; result = unsortedMap.entrySet()
        .stream()
        .sorted(Map.Entry.comparingByKey())
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));

    // Alternative way
    Map&lt;String, Integer&gt; resultAlternative = new LinkedHashMap<>();
    unsortedMap.entrySet()
        .stream()
        .sorted(Map.Entry.comparingByKey())
        .forEachOrdered(x -> resultAlternative.put(x.getKey(), x.getValue()));

    System.out.println("Sorted map by keys: ");
    System.out.println(result);
    System.out.println(resultAlternative);
}</code></pre>
<p><b>Output</b></p>
<pre><code class="language-bash">Unsorted map:
{a=6, b=5, d=1, e=7, f=9, z=0, k=8, m=2, n=100, o=-4}

Sorted map by keys:
{a=6, b=5, d=1, e=7, f=9, k=8, m=2, n=100, o=-4, z=0}
{a=6, b=5, d=1, e=7, f=9, k=8, m=2, n=100, o=-4, z=0}</code></pre>
<p>Order in <i>unsortedMap</i> is not secured. However, after the map sorting with the key, we can see that the map is ordered. The newly created map is placed in <code>LinkedHashMap</code> implementation,  which maintains the elements&#8217; order.</p>
<h2>Sort Map by Values</h2>
<pre><code class="language-java">public void sortMapByValues() {

    Map&lt;String, Integer&gt; unsortedMap = new HashMap<>();

    unsortedMap.put("z", 0);
    unsortedMap.put("c", 7);
    unsortedMap.put("q", 4);
    unsortedMap.put("a", 6);
    unsortedMap.put("e", 7);
    unsortedMap.put("k", 8);
    unsortedMap.put("n", 100);
    unsortedMap.put("o", -4);
    unsortedMap.put("m", 2);
    unsortedMap.put("d", 1);

    System.out.println("Unsorted map: ");
    System.out.println(unsortedMap);

    // We need a LinkedHashMap to keep an order of newly returned sorted map.
    Map&lt;String, Integer&gt; result = unsortedMap.entrySet()
        .stream()
        .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));

    // Alternative way
    Map&lt;String, Integer&gt; resultAlternative = new LinkedHashMap<>();
    unsortedMap.entrySet()
        .stream()
        .sorted(Map.Entry.&lt;String, Integer&gt;comparingByValue().reversed())
        .forEachOrdered(x -> resultAlternative.put(x.getKey(), x.getValue()));

    System.out.println("Sorted map by values: ");
    System.out.println(result);

    System.out.println("Sorted map by values (alternative approach): ");
    System.out.println(resultAlternative);
}</code></pre>
<p><b>Output</b></p>
<pre><code class="language-bash">Unsorted map:
{q=4, a=6, c=7, d=1, e=7, z=0, k=8, m=2, n=100, o=-4}

Sorted map by values:
{n=100, k=8, c=7, e=7, a=6, q=4, m=2, d=1, z=0, o=-4}

Sorted map by values (alternative approach):
{n=100, k=8, c=7, e=7, a=6, q=4, m=2, d=1, z=0, o=-4}</code></pre>
<p>Order in <i>unsortedMap</i> is not secured. However, after the map is sorted by value, we can see it is in order. The newly created map is kept in <code>LinkedHashMap</code> implementation, which maintains the elements&#8217; order.</p>
<h2>Sort special case of Map&lt;Object,Object&gt;</h2>
<p>There exist special case in <code>Map</code> sorting. It is when we place <code>Object</code> type into the <code>Map</code> parameters. The Stream can’t sort the <code>Map&lt;Object, Object&gt;</code> directly. To solve this case we need to convert <code>Map&lt;Object, Object></code> into <code>Map&lt;String, String&gt;</code>. Let&#8217;s take a look on the code example below:</p>
<p><b>Note</b> : If you have better idea for <code>Map</code> sorting, let me know in comments below.</p>
<pre><code class="language-java">public void sortObjectMap() {

    // Example of the Object map
    Properties properties = System.getProperties();
    Set&lt;Map.Entry&lt;Object, Object&gt;&gt; entries = properties.entrySet();

    System.out.println("Unsorted Object map: ");
    entries.forEach(System.out::println);

    LinkedHashMap&lt;String, String&gt; collect = entries.stream()
        .collect(Collectors.toMap(k -> (String) k.getKey(), e -> (String) e.getValue()))
        .entrySet()
        .stream()
        .sorted(Map.Entry.comparingByKey())
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));

    System.out.println("Sorted Object map by keys: ");
    result.forEach((key, value) -> System.out.println(key + " : " + value));
}</code></pre>
<p><b>Output</b></p>
<pre><code class="language-bash">Unsorted Object map:
sun.desktop=windows
java.specification.version=8
...

Sorted Object map by keys:
awt.toolkit:sun.awt.windows.WToolkit
file.encoding:UTF-8
file.separator:\
java.awt.graphicsenv:sun.awt.Win32GraphicsEnvironment
...</code></pre>
<h2>Conclusion</h2>
<p>In this article we have shown how to sort <code>Map</code> by key and by value. As some implementation of <code>Map</code> do not maintain order we created ordered maps with <code>LinkedHashMap</code>.</p>
<p>Eventually we have shown a special case of <code>Map&lt;Object, Object&gt;</code> which require transformation of <code>Object</code> into the string in order to to be compared by key or value.</p>
<p>As always, you can find all our examples on our <a href="https://github.com/codekopf/tutorials-jvm/tree/master/java-basics/java8/" title="Tutorial JVM - Java Basics - Java 8" target="_blank" rel="nofollow noopener">GitHub project</a>!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/how-to-sort-a-map-with-java-8/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<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>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 download a file from Azure Claud Storage</title>
		<link>https://codepills.com/how-to-download-a-file-from-azure-claud-storage/</link>
					<comments>https://codepills.com/how-to-download-a-file-from-azure-claud-storage/#comments</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Sun, 03 Jan 2021 19:09:08 +0000</pubDate>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Azure]]></category>
		<category><![CDATA[Azure Cloud]]></category>
		<category><![CDATA[Azure Cloud Storage]]></category>
		<category><![CDATA[Azure Storage API]]></category>
		<category><![CDATA[code snippets]]></category>
		<category><![CDATA[container]]></category>
		<category><![CDATA[download file from Azure Storage]]></category>
		<category><![CDATA[downloader]]></category>
		<category><![CDATA[googling]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[legacy app]]></category>
		<category><![CDATA[legacy code]]></category>
		<category><![CDATA[SDK]]></category>
		<category><![CDATA[StackOverflow]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1111</guid>

					<description><![CDATA[In this article, we will look into the way how to download a file from Azure Cloud Storage for legacy API <a href="https://codepills.com/how-to-download-a-file-from-azure-claud-storage/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>In this article, we will look at how to download a file from Azure Cloud Storage for legacy API.</p>
<p><span id="more-1111"></span></p>
<h2>Introduction</h2>
<p>Sometimes you must deal with the development of legacy applications which require a thorough approach. You go through ancient documentation, and at the same time, you Google stuff on the internet and hope your questions will be answered for a concrete version of your dependencies. It was also my case.</p>
<p>Therefore I have decided to share a piece of code for legacy Azure Storage API. To be precise, this article focused on the Azure Storage version 5 Software Development Kit.</p>
<pre><code>&lt;dependency&gt;
    &lt;groupId&gt;com.microsoft.azure&lt;/groupId&gt;
    &lt;artifactId&gt;azure-storage&lt;/artifactId&gt;
    &lt;version&gt;5.0.0&lt;/version&gt;
&lt;/dependency&gt;</code></pre>
<p>This is just simple example of working code. For any new development, please use rather new API for Azure Storage. Azure teams created very comprehensive documentation. You can get inspired for example by Azure Storage Blob API documentation <a href="https://docs.microsoft.com/en-us/azure/storage/common/storage-samples-java" title="documentation" target="_blank" rel="nofollow noopener">[1]</a>, <a href="https://docs.microsoft.com/en-us/java/api/overview/azure/storage-blob-readme?view=azure-java-stable" title="documentation" target="_blank" rel="nofollow noopener">[2]</a>.</p>
<p>Here is a code for a Java method that downloads a file from Azure Cloud Storage. Certain code lines of arbitrary class code were omitted for code brevity.</p>
<pre><code>import com.microsoft.azure.storage.CloudStorageAccount;
import com.microsoft.azure.storage.OperationContext;
import com.microsoft.azure.storage.StorageException;
import com.microsoft.azure.storage.file.CloudFile;
import com.microsoft.azure.storage.file.CloudFileClient;
import com.microsoft.azure.storage.file.CloudFileDirectory;
import com.microsoft.azure.storage.file.CloudFileShare;

...

protected Logger logger = Logger.getLogger(getClass());

...

private void downloadFromAzureCloudStorageToDisk() {
    try {
        logger.info("File download from Azure Storage to Disk started.");

        final String sourceContainer = "reports";
        final String sourceFolder = "daily_reports";
        final String targetDir = "C://reports/daily/csv/";
        final String targetFileName = "DAILY_REPORT_IN_CSV.csv";

        final String targetConnection =
            "AccountName=HERE_GOES_ACCOUNT_NAME;" +
            "AccountKey=VERY_LONG_ACCOUNT_KEY;" +
            "DefaultEndpointsProtocol=https;" +
            "EndpointSuffix=core.windows.net;";

        final CloudStorageAccount storageAccount = CloudStorageAccount.parse(targetConnection);

        final CloudFileClient cloudFileClient = storageAccount.createCloudFileClient();

        final CloudFileShare azureStorageContainer = cloudFileClient.getShareReference(sourceContainer);

        CloudFileDirectory directory = azureStorageContainer.getRootDirectoryReference();

        directory = directory.getDirectoryReference(sourceFolder);

        final CloudFile fileReference = directory.getFileReference(targetFileName);

        final File targetFilePath = new File(targetDir + '/' + targetFileName);

        try (FileOutputStream fileOutputStream = new FileOutputStream(targetFilePath)) {
            fileReference.download(fileOutputStream);
        } catch (IOException ex) {
            logger.error("Error saving file to target directory: ", ex);
            throw e;
        }

        logger.info("File download from Azure Storage to Disk completed.");

    } catch (StorageException | URISyntaxException ex) {
        logger.error("FromAzureCloudStorageToDisk threw exception. Storage or URI syntax is wrong: ", ex);
    } catch (Exception ex) {
        logger.error("FromAzureCloudStorageToDisk threw exception: ", ex);
    }
}</code></pre>
<p>First, we will create an instance of <i>CloudStorageAccount</i> into which we will push all credentials and the login information. From <i>CloudStorageAccount</i> instance we will instantiate Azure Cloud Storage client (<i>cloudFileClient</i>).</p>
<p>And from this point, everything should go very smoothly. We have an Azure Cloud Storage client, and all we need to do is get an instance of the reference of the file we want to download. We are using <i>DAILY_REPORT_IN_CSV.csv</i> as an arbitrary stand for the filename we want to download. You will download the file by loading the correct Azure Cloud Storage container and then getting a reference on its root directory. Then, we will crawl the root directory in the direction of the desired file and get its reference.</p>
<p>Now we have a reference instance on the file in our Azure Cloud Storage. We can download it. To do so, we need to save it on the local disk. And for that, we use the last piece of method code. File reference can be download only into Java&#8217;s object with <code>OutputStream</code> interface behavior. However, this condition fulfills any instance of <code>OutputStream</code> implementation.</p>
<p>Do not forget to close your stream if you are working with older Java. For safety, use Java&#8217;s try-with-resource stream construction instead, which has been available since Java 7.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/how-to-download-a-file-from-azure-claud-storage/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>How to create a custom range calendar filter for Angular PrimeNg data turbo table</title>
		<link>https://codepills.com/how-to-create-a-custom-range-calendar-filter-for-angular-primeng-data-turbo-table/</link>
					<comments>https://codepills.com/how-to-create-a-custom-range-calendar-filter-for-angular-primeng-data-turbo-table/#comments</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Fri, 14 Aug 2020 17:48:34 +0000</pubDate>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Angular]]></category>
		<category><![CDATA[calendar]]></category>
		<category><![CDATA[custom filter]]></category>
		<category><![CDATA[ngPrime]]></category>
		<category><![CDATA[PrimeNg]]></category>
		<category><![CDATA[range]]></category>
		<category><![CDATA[table]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1065</guid>

					<description><![CDATA[In this article, we will look at how to create a custom filter for PrimeNg calendar selection with a date range <a href="https://codepills.com/how-to-create-a-custom-range-calendar-filter-for-angular-primeng-data-turbo-table/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>Let&#8217;s look at how to implement the Angular selection range for the newest Angular PrimeNg version. This tutorial was developed on <b>v10.0.0-rc-1</b> version.</p>
<p><span id="more-1065"></span></p>
<p>I had difficulty finding a proper solution for range selection in the PrimeNg turbo data table for the newest version. Therefore I have decided to create a workaround. For the time selection, each click event on the calendar panel fire only one piece of data &#8211; the currently selected date. So the calendar range is stateless. You need to remember somehow to keep in memory what date was fired before and implement this logic in a custom filter.</p>
<p>I observed that there are several rules according to which <code>p-calendar</code> component behave when the selection mode <code>"range"</code> is selected. Here are my findings according to which I programmed the logic:</p>
<ul>
<li>At first, the calendar component has an empty, undefined selection.</li>
<li>If one date is selected, only one date is fired on click event.</li>
<li>If the same date as date previously selected is selected, new date (which is the same as previously selected date) is fired on click event.</li>
<li>If a date before the already selected date is selected, the selection is cancelled and earlier date is fired on click event.</li>
<li>If a date after the already selected date is selected, the selection range is visible.</li>
<li>If any new date is selected after the selection range is visible, a new date is selected, fired upon click event and selection range is cancelled.</li>
</ul>
<p>When all this wrote down, here is the implementation code for component and custom filter:</p>
<p><b>record-list.component.html</b></p>
<pre><code class="language-html">&#60;p-table #dt [value]="records" sortMode="multiple" [paginator]="true" [rowsPerPageOptions]="rowsPerPageTable" [rows]="rowsPerTable" [showCurrentPageReport]="true" [(first)]="page" styleClass="p-datatable-striped" currentPageReportTemplate="Showing {first} to {last} of {totalRecords} entries"&#62;
    &#60;ng-template pTemplate="header"&#62;
        &#60;tr class="ui-table-thead"&#62;
            &#60;th [ngStyle]="{'width':'50%'}" pSortableColumn="createdDate"&#62;Created &#60;p-sortIcon field="createdDate"&#62;&#60;/p-sortIcon&#62;&#60;/th&#62;
            &#60;th [ngStyle]="{'width':'50%'}" pSortableColumn="info"&#62;Info &#60;p-sortIcon field="info"&#62;&#60;/p-sortIcon&#62;&#60;/th&#62;
        &#60;/tr&#62;
        &#60;tr class="ui-table-thead"&#62;
            &#60;th scope="col"&#62;
                &#60;p-calendar (onSelect)="onDateSelect($event)" [style]="{'width':'100%'}" selectionMode="range" [readonlyInput]="true" (onClearClick)="onDateClear($event)" [showButtonBar]="true" placeholder="Created Date" class="p-column-filter" dateFormat="yy-mm-dd"&#62;&#60;/p-calendar&#62;
            &#60;/th&#62;
            &#60;th scope="col"&#62;
                &#60;input pInputText type="text" [style]="{'width':'100%'}" (input)="dt.filter($event.target.value, 'info', 'contains')" placeholder="Info"&#62;
            &#60;/th&#62;
        &#60;/tr&#62;
    &#60;/ng-template&#62;

    &#60;ng-template pTemplate="body" let-rowData&#62;
        &#60;tr ng-repeat="rowData in let-rowData" ng-click="showClient(rowData)"&#62;
            &#60;td&#62;{{ rowData.createdDate }}&#60;/td&#62;
            &#60;td&#62;{{ rowData.info }}&#60;/td&#62;
        &#60;/tr&#62;
    &#60;/ng-template&#62;

&#60;/p-table&#62;</code></pre>
<p><b>record-list.component.ts</b></p>
<pre><code class="language-typescript">export class RecordListComponent implements OnInit {

    public records: IssueShortInfo[];

    @ViewChild('dt') table: Table;

    cols: any[];
    dateRangeStart: string;
    dateRangeEnd: string;

    rowsPerPageTable: number[] = [25, 50, 100, 200];

    page: number = 0;
    rowsPerTable: number = 25;

    constructor(private recordService: RecordService) {}

    ngOnInit() {

        this.recordService.getAllRecords().subscribe(page => {
            this.getRecords(page);
        }, (error => {
            console.log(error)
        }));

        this.cols = [
            {field: 'id', header: 'Id'},
            {field: 'createdDate', header: 'Created Date'},
            {field: 'info', header: 'Info'}
        ];

        FilterUtils['customCreatedDateFilter'] = (value: string, filter) => {

            if (this.dateRangeStart === value && this.dateRangeEnd === undefined) {
                return true;
            }

            if (this.dateRangeStart === value || this.dateRangeEnd === value) {
                return true;
            }

            if (this.dateRangeStart !== undefined && this.dateRangeEnd !== undefined &&
                moment(this.dateRangeStart).isBefore(value) && moment(this.dateRangeEnd).isAfter(value)) {
                return true;
            }

            return false;
        };
    }

    getRecords(page: Page<IncomingRecordDTO>) {
        this.records = page.content.map(incomingRecordDTO => new Record(incomingRecordDTO));
    }

    onDateSelect($event) {

        const eventDate = this.formatDate($event);

        if (this.dateRangeStart === undefined) {
            this.dateRangeStart = eventDate;
        } else if (moment($event).isBefore(this.dateRangeStart)) {
            this.dateRangeStart = eventDate;
            this.dateRangeEnd = undefined;
        } else if (moment($event).isSame(this.dateRangeStart) && this.dateRangeStart !== undefined && this.dateRangeEnd === undefined) {
            this.dateRangeEnd = eventDate;
        } else if (moment($event).isSame(this.dateRangeStart) && this.dateRangeStart !== undefined && this.dateRangeEnd !== undefined) {
            this.dateRangeStart = eventDate;
            this.dateRangeEnd = undefined;
        } else if (moment($event).isAfter(this.dateRangeStart) && this.dateRangeStart !== undefined && this.dateRangeEnd !== undefined) {
            this.dateRangeStart = eventDate;
            this.dateRangeEnd = undefined;
        } else {
            this.dateRangeEnd = eventDate;
        }

        this.table.filter(eventDate, 'createdDate', 'customCreatedDateFilter');
    }

    onDateClear($event) {
        this.dateRangeStart = undefined;
        this.dateRangeEnd = undefined;
        this.table.filter('', 'createdDate', 'equals');
    }

    formatDate(date) {
        let month = date.getMonth() + 1;
        let day = date.getDate();

        if (month < 10) {
            month = '0' + month;
        }

        if (day < 10) {
            day = '0' + day;
        }
        return date.getFullYear() + '-' + month + '-' + day;
    }

    customCreatedDateArrayFilter(event) {
        this.table.filter(event, 'createdDate', 'customCreatedDateFilter');
    }

}</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/how-to-create-a-custom-range-calendar-filter-for-angular-primeng-data-turbo-table/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>How to connect Azure Cosmos DB Emulator with Spring Boot app at Windows</title>
		<link>https://codepills.com/how-to-connect-azure-cosmos-db-emulator-with-spring-boot-app-at-windows/</link>
					<comments>https://codepills.com/how-to-connect-azure-cosmos-db-emulator-with-spring-boot-app-at-windows/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Fri, 21 Feb 2020 13:58:46 +0000</pubDate>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Azure]]></category>
		<category><![CDATA[certificate]]></category>
		<category><![CDATA[cmd]]></category>
		<category><![CDATA[CosmosDB]]></category>
		<category><![CDATA[emulator]]></category>
		<category><![CDATA[Git]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JDK]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[windows]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1060</guid>

					<description><![CDATA[In this article, we look at installing Azure Cosmos DB Emulator on your Windows machine and using the Azure Cosmos DB Emulator for local development of our Spring Boot application. <a href="https://codepills.com/how-to-connect-azure-cosmos-db-emulator-with-spring-boot-app-at-windows/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>This article will look at how to install Azure Cosmos DB Emulator on your Windows machine and how to use the Azure Cosmos DB Emulator for the local development of our Spring Boot application.</p>
<p><span id="more-1060"></span></p>
<h2>How to install Azure CosmosDB Emulator</h2>
<p>First of all, we need to install Azure CosmosDB Emulator locally. Go to <a href="https://docs.microsoft.com/en-us/azure/cosmos-db/local-emulator#installation" title="How to install Cosmos DB" rel="nofollow noopener" target="_blank">https://docs.microsoft.com/en-us/azure/cosmos-db/local-emulator#installation</a>, download the windows installation package and install <strong>Azure Cosmos DB Emulator</strong>.</p>
<p>When installing Azure Cosmos DB Emulator passed successfully on your Windows machine, start the emulator (if it did not start automatically).</p>
<p>If it is already running you can find it minimized in the system hidden in the running application system and either click <strong>Open Data Explorer &#8230;</strong> or visit <a href="https://localhost:8081/_explorer/index.html" title="local address of Azure Cosmos DB Emulator" rel="nofollow noopener" target="_blank">https://localhost:8081/_explorer/index.html</a> page. You can now get finally into the Azure CosmosDB Emulator.</p>
<h2>Exporting security certificates</h2>
<p>Azure Cosmos DB Emulator uses a secure connection with your application. We need to extract and register your certificate for communication with the emulator.</p>
<p>Let’s type &#8220;Manage user certificates&#8221; into Windows Start console or open Windows Certificate Manager (running certlm.msc in the run prompt). Go to Personal->Certificates folder and export certificate with <strong>DocumentDbEmulatorCertificate</strong> name. The whole tutorial how to do it can be found at <a href="https://docs.microsoft.com/bs-latn-ba/azure/cosmos-db/local-emulator-export-ssl-certificates#how-to-export-the-azure-cosmos-db-ssl-certificate" title="How to export Azure Cosmos DB SSL certificate" rel="nofollow noopener" target="_blank">Microsoft Azure website</a> explaining how to export the Azure Cosmos DB SSL certificate.</p>
<p>You can name your file when exporting arbitrary. However, we will name it for our example <strong>documentdbemulatorcert.cer</strong>.</p>
<p>Now when I have extracted the SSL certificate, I need to upload it into the correct Java SDK location.</p>
<p>Check which version of Java do you use in your project. In IntelliJ idea you can use either keyword shortcut [ctrl] + [shift] + [alt] + [s] or go to File->Project Structure->SDKs and check which version your Spring Boot application uses or where SDK is located.</p>
<p>Copy certificate into the Java SDK directory. It should be copied into the <strong>%JAVA_HOME%/jre/lib/security</strong> location.</p>
<p>If you use OpenJDK, OpenJDK does not contain <strong>jre</strong> folder. Just copy it into <strong>%JAVA_HOME%/lib/security</strong> location.</p>
<h2>Registering certificate</h2>
<p>The nearly last thing we need to do is to register the certificate into the system.</p>
<p>We need to open the Windows Command prompt as an administrator and navigate at JDK&#8217;s folder at jdk\jre\lib\security.</p>
<p><strong>Hint</strong>: A little hint if you are more familiar with Linux based systems than Windows. If you open a folder in Windows, copy the path to the folder and place it into quotation marks in the command prompt. Executing the command changes the directory instantly.</p>
<p>Then, upon the folder, we need just to run the following command to register the certificate into the keystore on your system:</p>
<pre><code class="language-bash">keytool -keystore cacerts -importcert -alias documentdbemulator -file documentdbemulatorcert.cer</code></pre>
<p><strong>Hint</strong>: Keytool is a tool located in your Java installation, so you need to have jdk/bin on your PATH for this to work.</p>
<p>If you need a hint with registration, check this tutorial at <a href="https://docs.microsoft.com/en-us/azure/java/java-sdk-add-certificate-ca-store?view=azure-java-stable#to-add-a-root-certificate-to-the-cacerts-store" title="How to add a root certificate to the cacerts store" rel="nofollow noopener" target="_blank">Microsoft Azure website</a> where you learn how to add a root certificate to the certification authority certificates storage. However instead of <strong>bc2025.cer</strong> name in tutorial use name of your certificate.</p>
<p>Otherwise, when the prompt asks for a password, type your password. More likely you didn&#8217;t change it, so default password is <strong><i>changeit</i></strong>. Following, you get a question, if you trust this certificate. Answer it simply <strong>yes</strong>.</p>
<p>That is it. The certificate is registered, and Azure Cosmos DB Emulator should be now created securely and with ease.</p>
<h2>Using emulator with local Spring Boot app development</h2>
<p>And all we need to do now is just run the Spring Boot application. If you implemented a connection to Cosmos DB and registered connection properties to <code>application.properties</code> or <code>application.yml</code> you can successfully run the application.</p>
<pre><code class="language-yaml">azure:
   cosmosdb:
    uri: https://localhost:8081
    key: VERY_LONG_KEY
    database: YOUR_DB_NAME</code></pre>
<p>To fill up <code>application.yml</code> you will need to implement your own data:</p>
<p>You can find VERY_LONG_KEY in your Azure Cosmos DB Emulator Data Explorer under the <i>Quick start</i> tab.</p>
<p>And all we need to do now is just run the Spring Boot application. If you check now Data Explorer under <i>Explorer</i> tab, you can find now your database with all the defined structures.</p>
<h2>Troubleshooting</h2>
<p>In case you already successfully installed the Azure CosmosDB Emulator and you want to restart the database, you have an option to reset data. Data reset comes handy when you get an authentication issue over HTTPS with your Azure CosmosDB certificate on the application run.</p>
<p>Pick up &#8220;Reset data&#8221; from the Azure CosmosDB Emulator mini-panel dialogue window from your start button. Operation is not reversible; it will clean up all your caches and the internal state of the Azure CosmosDB Emulator database and reset the certificate.</p>
<p>Then it would be best if you continued extracting the certificate from the list of certificates according to the description in Exporting Security Certificates. However, before registering the certificate back to Java keytool, you need to remove the old alias on the certificate with a command like this:</p>
<pre><code class="language-bash">keytool -delete -alias documentdbemulator -keystore cacerts -storepass changeit</code></pre>
<p><strong>Notes</strong>: behind <code>-alias</code> you place the name of the certificate, <code>-keystore</code> is the name of a file containing the certificates and behind <code>-storepass</code> is your password (default is <i>changeit</i>).</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/how-to-connect-azure-cosmos-db-emulator-with-spring-boot-app-at-windows/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
