<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by APD on Medium]]></title>
        <description><![CDATA[Stories by APD on Medium]]></description>
        <link>https://medium.com/@apdharshi?source=rss-607db3bab33c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*838e-yKwZEEJrFXXVcYy1g.png</url>
            <title>Stories by APD on Medium</title>
            <link>https://medium.com/@apdharshi?source=rss-607db3bab33c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 04:10:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@apdharshi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Ways to fix “-bash: ng: command not found”]]></title>
            <link>https://medium.com/@apdharshi/ways-to-fix-bash-ng-command-not-found-7f329745795?source=rss-607db3bab33c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f329745795</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-cli]]></category>
            <dc:creator><![CDATA[APD]]></dc:creator>
            <pubDate>Sat, 02 Nov 2019 21:20:27 GMT</pubDate>
            <atom:updated>2022-04-06T07:11:57.629Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*1bh2mszm6rtMXA8F-IbPjw.jpeg" /></figure><h4>What you have already tried</h4><pre>ng version</pre><p>or any other <em>ng</em> commands.</p><h4>Error produced by the previous command</h4><pre>-bash: ng: command not found</pre><h4>Before heading into the fix, let me ask a question</h4><p>Are you sure that Angular is globally installed in your machine? If yes, you can continue to read this article. Else I recommend you to visit the <a href="https://angular.io/guide/setup-local">official Angular site</a> and get the latest version installed :)</p><p>This problem is caused due to the reason that <strong>npm is unable to find ng.</strong> There are few ways that we can follow to get rid of this error.</p><h4>1 . Linking angular/cli with npm</h4><p>This can be done using the command,</p><pre>npm link @angular/cli</pre><h4>2. Setting the location of npm folder</h4><pre>export PATH=&quot;$HOME/.npm-global/bin:$PATH&quot;</pre><p>or</p><pre>export PATH=&quot;$HOME/.npm-packages/bin:$PATH&quot;</pre><h4>3. Clearing cache and Re-installing Angular (least recommended)</h4><p>In this case, you may need to uninstall angular from your machine with the command</p><pre>npm uninstall -g @angular/cli<br>npm cache clean<br>npm install -g @angular/cli</pre><h4>4. Giving an alias to ng path</h4><p>To do this you must know the full path of your angular installation. For example: <em>“/Users/&lt;username&gt;/.npm-global/lib/node_modules/@angular/cli/bin/ng”. </em>So the command would be</p><pre>alias ng=&quot;/Users/&lt;<em>username</em>&gt;/.npm-global/lib/node_modules/@angular/cli/bin/ng&quot;</pre><p>Note that the above option works for many users but the problem is that this is just a temporary solution. It means that this command works only on your current terminal (same terminal where you ran the above command). Once you close and open a new terminal, the problem seems to reappear.</p><p>So how can we permanently solve this? Here comes the solution. <em>Credits: </em><a href="https://github.com/angular/angular-cli/issues/5021#issuecomment-377030706"><em>Thanks for this fix</em></a><em>.</em></p><h4>5 . By adding the PATH directly to the Mac OS terminal</h4><p>Before doing this we just have to verify whether angular is installed to the base of the user. To check this, in your terminal enter</p><pre>cd ~  </pre><p>to get to the base of your files. Then in order to list all your base files, enter</p><pre>ls -a</pre><p>Now you must see “<em>.npm-global</em>” listed in the files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*kB_uuT6Jn_siQhbTDcScMw.jpeg" /></figure><p>If its not there, again I recommend you to install Angular using the official documentation link I have mentioned in the beginning.</p><p>If the folder is listed, you are good to go. Go back to the base of the user using the command</p><pre>cd ~</pre><p>Here we are going to edit the paths using vim editor. Use “<em>sudo</em>” in front of the command to avoid permission issues. Here you will be prompted to enter the device’s password.</p><pre>sudo vim /etc/paths</pre><p>The editor now opens a file containing some paths as shown below. All you have to do here is to insert the path of <em>.npm-global/bin </em>to the list. To do so you have to press insert from your mac keyboard (press <em>fn + i</em> key combination), navigate to the bottom of the list and add ~/.npm-global/bin as I have added below.</p><pre>/usr/local/bin<br>/usr/bin<br>/bin<br>/usr/sbin<br>/sbin<br>~/.npm-global/bin<br>~                                                                               <br>~</pre><p>Now to save your changes and exit, press <em>ESc</em> key and then type :wq vim command which means to write/save the changes and quit. This will bring you back to the terminal window. Now restart your terminal and type</p><p>echo $PATH</p><p>This should give you all the paths with the newly added one concatenated at the end.</p><p><strong><em>/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:~/.npm-global/bin</em></strong></p><p>Finally the happy ending. Try any <em>ng</em> command</p><pre>ng version</pre><p>There you go! Thanks for reading this article. Have a great day!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f329745795" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Difference between Arrays and JSON Objects]]></title>
            <link>https://medium.com/@apdharshi/difference-between-arrays-and-json-objects-fa1c8598f9f1?source=rss-607db3bab33c------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa1c8598f9f1</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[objects]]></category>
            <category><![CDATA[arrays]]></category>
            <dc:creator><![CDATA[APD]]></dc:creator>
            <pubDate>Thu, 16 May 2019 22:08:55 GMT</pubDate>
            <atom:updated>2019-05-19T18:40:46.223Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LM5eeUhJpt4IyBq4bcNQuQ.jpeg" /><figcaption>Designed by Freshgraphix / Freepik</figcaption></figure><p>Sometimes most of us get confused while dealing with Arrays and Objects. This leads into further confusions when choosing which manipulation technique to use. <em>For example</em>, we can find the length only if we know whether it is an array or an object. As both have different approaches.</p><p>This is a basic checklist for all the programmers coding out there. So, in this blog you will learn how to differentiate between Arrays and Objects.</p><h3>What are Arrays?</h3><p>Array items are accessed using <strong>indices</strong></p><p><em>Format</em> [ , , , ]</p><p><em>Example</em> [1, 2, 3, 4, 5]</p><p>Arrays can contain objects, strings, numbers, arrays &amp; boolean.</p><h4><strong>Initialization</strong></h4><pre>1. <em>datatype</em>[] = [ , , , ];</pre><pre>2. Array&lt;<em>datatype</em>&gt; = [ , , , ];     // <em>Uses a generic array type</em></pre><h4><strong>Array of objects</strong></h4><p><em>Syntax :</em></p><pre>[{“ “:” “,” “:” “},{“ “:” “,” “:” “}]</pre><p><em>Example:</em></p><pre>[<br>    { “position”: “winner”,”country”: “U.S.A” },</pre><pre>    { “position”: “runner”,”country”: “China” }</pre><pre>];</pre><pre>[<br>    { “rainy”: true,”sunny”: false },</pre><pre>    { “rainy”: false,”sunny”: true }</pre><pre>]</pre><h4><strong>Array of strings</strong></h4><p><em>Example:</em></p><pre>[‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’,’Friday’, ‘Saturday’];</pre><pre>[‘a’, ‘b’, ‘c’, ‘d’];</pre><pre>[‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ’6’, ‘7’];</pre><h4><strong>Array of numbers</strong></h4><p><em>Example:</em></p><pre>[1, 2, 3, 4, 5];</pre><pre>[788.34, 432.34, 3234.72];</pre><h4><strong>Array of arrays</strong></h4><p>These can be otherwise called as <strong>multi-dimensional</strong> arrays.</p><pre>[</pre><pre>    [1, 2, 3, 4, 5, 6, 7],</pre><pre>    [1, 2, 3, 4, 5, 6, 7],</pre><pre>    [1, 2, 3, 4, 5, 6, 7],</pre><pre>    [1, 2, 3, 4, 5, 6, 7],</pre><pre>    [1, 2, 3, 4, 5, 6, 7],</pre><pre>    [1, 2, 3, 4, 5, 6, 7]</pre><pre>];</pre><h4>Array of booleans</h4><pre>[true, false, false, true]</pre><h3>What are Objects?</h3><blockquote>An <strong>object</strong> is a collection of properties, and a property is an association between a name (or key) and a value. A property’s value can be a function, in which case the property is known as a method.</blockquote><p>Object properties are accessed using <strong>keys.</strong></p><p><strong>Keys</strong> must be strings, and values must be a <strong>valid JSON data type</strong> (string, number, <strong>object</strong>, array, boolean or null).</p><p>Format { “ ”: “ ” }</p><p>Example {“position”: “winner”,”country”: “U.S.A”}</p><h4><strong>Object of arrays and objects</strong></h4><pre>{</pre><pre>    “binary”:   [{“id”:1,”name”:0},{“id”:2,”name”:1}],</pre><pre>    “boolean”:  [{“id”:1,”value”: false},{“id”:2,”value”: true}]</pre><pre>}</pre><p>Nested Objects:</p><pre>“results”: {</pre><pre>    “tennis”: [<br>                 {“position”: “winner”,“country”: “U.S.A},</pre><pre>                 {“position”: “runner”,“country”: “China”}<br>     ]</pre><pre>}</pre><h4><strong>Object of objects</strong></h4><p><strong>JSON Objects</strong> are enclosed within {}</p><pre>“universe”: {</pre><pre>    “planets”: {</pre><pre>        “day”: “Sun”,</pre><pre>        “night”: “Moon”</pre><pre>    }</pre><pre>}</pre><p>Nested JSON Object:</p><pre>json: any = {</pre><pre>    &quot;visible&quot;: true,</pre><pre>    &quot;colors&quot;: {</pre><pre>        &quot;data&quot;: {</pre><pre>            &quot;darkest&quot;: &quot;Black&quot;,</pre><pre>            &quot;lightest&quot;: &quot;white&quot;,</pre><pre>            &quot;neutral&quot;: &quot;Grey&quot;,</pre><pre>            &quot;spectrum&quot;: {</pre><pre>                &quot;1&quot;: &quot;Violet&quot;,</pre><pre>                &quot;2&quot;: &quot;Indigo&quot;,</pre><pre>                &quot;3&quot;: &quot;Blue&quot;,</pre><pre>                &quot;4&quot;: &quot;Green&quot;,</pre><pre>                &quot;5&quot;: &quot;Yellow&quot;,</pre><pre>                &quot;6&quot;: &quot;Orange&quot;,</pre><pre>                &quot;7&quot;: &quot;Red&quot;</pre><pre>            },</pre><pre>            &quot;default&quot;: &quot;Grey&quot;,</pre><pre>            &quot;primary&quot;: &quot;Blue&quot;,</pre><pre>            &quot;danger&quot;: &quot;Red&quot;,</pre><pre>            &quot;warning&quot;: &quot;Yellow&quot;,</pre><pre>            &quot;success&quot;: &quot;Green&quot;,</pre><pre>            &quot;RGB&quot;: {</pre><pre>                &quot;r&quot;: &quot;Red&quot;,</pre><pre>                &quot;g&quot;: &quot;Green&quot;,</pre><pre>                &quot;b&quot;: &quot;Blue&quot;</pre><pre>            }</pre><pre>        }</pre><pre>    }</pre><pre>}</pre><p>So these are the differences between Arrays and Objects. I hope that from now you all can use these types without any worries.</p><p>Happy coding :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa1c8598f9f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the usage of optional and nullable in TypeScript]]></title>
            <link>https://medium.com/@apdharshi/understanding-the-usage-of-optional-and-nullable-in-typescript-826c1754df3?source=rss-607db3bab33c------2</link>
            <guid isPermaLink="false">https://medium.com/p/826c1754df3</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[APD]]></dc:creator>
            <pubDate>Mon, 22 Oct 2018 11:16:20 GMT</pubDate>
            <atom:updated>2018-10-22T15:38:44.162Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3jpAbmyZn6TozMQpw-XSxw.jpeg" /><figcaption>Designed by fanjianhua / Freepik</figcaption></figure><p>Angular is being widely used by developers as a front-end web application development platform. As an open-source platform, Angular is built with TypeScript, a superset of JavaScript. It is good for Angular developers to have an understanding of how things happen with TypeScript. So, in this article, let us discuss about some of the differences between <strong>nullable </strong>and <strong>optional </strong>parameters.</p><h4>Common misconception</h4><p>Most developers fall into the category of misunderstanding nullable and optional parameters. The confusion arises on where to use the “<strong>?</strong>”. Look at this code block.</p><pre>function example(x: number?, y?: string) {<br> // …<br>}</pre><h4>“?” Suffix</h4><p>Notice carefully where the “?” is suffixed. In the first argument it is suffixed to the type of the parameter whereas in the second, it is suffixed to the name of the argument. Do you think both are same?<br><strong>The answer is no</strong>. The first one indicates a <strong>nullable </strong>parameter that can also be a number, <em>undefined </em>or <em>null</em>. But, the second argument is an <strong>optional</strong>, it can be a string or <em>undefined</em>.</p><pre>x // =&gt; number | undefined | null<br>y // =&gt; number | undefined</pre><h4>Undefined vs Null</h4><p>Again here some may not be aware of the difference between “<strong>undefined</strong>” and “<strong>null</strong>”. Undefined represents something that may not exist. Null is used for things that are nullable. So both are entirely different.</p><h4><a href="http://twitter.com/Optional">@Optional</a></h4><p>So what is this <a href="http://twitter.com/Optional"><strong>@Optional</strong></a> in angular is all about? What is the difference between “?” and <a href="http://twitter.com/Optional">@Optional</a>? As the official document says, Optional is a constructor parameter decorator that marks a dependency as optional. This clearly states that <a href="http://twitter.com/Optional">@Optional</a> is used in the context of <strong>DI</strong> (Dependency Injection). Here is an example from the <a href="https://angular.io/api/core/Optional">official docs</a>.</p><pre><a href="http://twitter.com/Injectable">@Injectable</a>()<br>class Car {<br>    constructor(<a href="http://twitter.com/Optional">@Optional</a>() public engine: Engine) {}<br>}</pre><p>When @Optional is used, no exceptions occur even when the injected dependency is undefined. It treats the dependency as optional. Same thing happens if we replace <strong>@Optional </strong>annotation with “<strong>?”</strong>. The injector search for the dependency and when it is undefined, it will throw the exception. Eventhough sometimes replacing these doesn’t make any difference in the way your code executes, it is necessary to understand that always good to follow best practices and the recommended ways as a good developer.</p><p>Knowing these differences may not help you often but it is always nice to learn something new. I hope that after reading this, you can use these concepts without any misconceptions as you learned the usage. If you think this article is helpful, please show your appreciation by giving some applause.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=826c1754df3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Account activation by sending email confirmation with Java Spring MVC]]></title>
            <link>https://medium.com/@apdharshi/sending-email-confirmation-for-account-activation-with-spring-java-cc3f5bb1398e?source=rss-607db3bab33c------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc3f5bb1398e</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[APD]]></dc:creator>
            <pubDate>Mon, 20 Aug 2018 19:48:13 GMT</pubDate>
            <atom:updated>2019-05-02T19:32:38.972Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TYt5TmOPN1236zCLHbvfcw.png" /></figure><p>In this article, you will learn how to implement user registration with email confirmation. Basically, after the registration process, a new user is created behind the scenes. But the user cannot log into the application as the account is by default locked. To activate the user account we need a confirmation from the user. That is why we send a link to verify the registration process and activate the user account if the user clicks on the link.</p><p>Assuming that you already know how to register a new user, we are now heading towards the email verification part. (In case you don’t have any idea about how to register a new user, you may have a look at the <strong>GitHub repository</strong> mentioned at the end of this article).</p><p>We are going to modify few files that we have already created while implementing the user registration process. Apart from this, we are going to add the following new files to our project.</p><ul><li><strong>Entity</strong> — VerificationToken.java</li><li><strong>Repository layers </strong>— TokenDAO.java, ITokenDAO.java</li><li><strong>Package</strong> — event</li><li><strong>event</strong> &gt; <strong>Event</strong> — OnRegistrationSuccessEvent.java</li><li><strong>event</strong> &gt; <strong>EventListener</strong> — RegistrationEmailListener.java</li></ul><p>First we are going to start with our <strong>AccountController.java</strong>. The user fills the registration form and clicks submit. Onsubmit, the <strong>User</strong> object with the data is posted to the <em>registerNewUser </em>method with the following method signature.</p><p><em>AccountController.java</em></p><pre>public String registerNewUser(@ModelAttribute(“user”) UserDTO userDto, BindingResult result, WebRequest request, Model model) { … }</pre><p><strong>Note</strong>: Please ensure that you give the parameters in the same order as above. Changing this order may give you some unwanted errors.</p><p>Always make sure that you <em>do not use your entity directly on your controller</em> as it may put your application into security vulnerabilities. (i.e., <em>you may expose the entire domain model to the client</em>. We really don’t want this to happen). So make use of a <strong>Data Transfer Object (DTO)</strong> as a middle layer to acces the entity.</p><p>We recall few steps from the registration process here,</p><ul><li>Initialize a new User object.</li><li>Find that the user already exists.</li><li>If user already exists, we show an error message else we create a new user and assign the user to the newly initialized User object</li></ul><p><em>AccountController.java</em></p><pre>User registeredUser = new User();</pre><pre>String userName = userDto.getUserName();</pre><pre>if (result.hasErrors()) {</pre><pre>    return “registration”;</pre><pre>}</pre><pre>registeredUser = service.findByUsername(userName);</pre><pre>if(registeredUser!=null) {</pre><pre>    model.addAttribute(“error”,”There is already an account with this username: “ + userName);</pre><pre>    return “registration”;</pre><pre>}</pre><pre>registeredUser = service.registerUser(userDto);</pre><p>Now let’s move into the confirmation of user via email.</p><p>Before going to the controller code, we have to first create the <strong>Event</strong> and <strong>EventListener</strong> in order to send the email on successful registration of the user.</p><p>This will be our event,</p><p><em>OnRegistrationSuccessEvent.java</em></p><pre>public class OnRegistrationSuccessEvent extends ApplicationEvent {</pre><pre>private static final long serialVersionUID = 1L;</pre><pre>private String appUrl;</pre><pre>private User user;</pre><pre>public OnRegistrationSuccessEvent(User user, String appUrl) {</pre><pre>super(user);</pre><pre>this.user = user;</pre><pre>this.appUrl = appUrl;</pre><pre>}</pre><pre>public String getAppUrl() {</pre><pre>return appUrl;</pre><pre>}</pre><pre>public void setAppUrl(String appUrl) {</pre><pre>this.appUrl = appUrl;</pre><pre>}</pre><pre>public User getUser() {</pre><pre>return user;</pre><pre>}</pre><pre>public void setUser(User user) {</pre><pre>this.user = user;</pre><pre>}</pre><p>Events must always inherit the <strong>ApplicationEvent</strong> class of Spring that is inherited from the <strong>java.util.EventObject</strong>. We have three variables <em>serialVersionUID, appurl and user</em>.</p><blockquote>It is strongly recommended that all serializable classes explicitly declare serialVersionUID values, otherwise it may result in unexpected InvalidClassExceptions during deserialization. To know more visit the<strong> Java docs</strong> for <a href="https://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html"><strong>java.io.Serializable</strong></a></blockquote><p>appurl is the context path to our application and user is the new user object. These two variables construct the confirmation url. However, we do not use the serialVersionUID in our url. And finish the Event creation with the implementation of the basic <em>getters/setters</em> and <em>constructors</em>.</p><p>Next is we have to build an <strong>EventListener</strong> to handle the <em>OnRegistrationSuccessEvent</em>. We name our EventListener as RegistrationEmailListener.java and give it the @Component annotation. This will be responsible for sending our confirmation email to the newly registered user. The <strong>RegistrationEmailListener</strong> <em>inherits</em> the <strong>ApplicationListener</strong> that Listens to our <em>OnRegistrationSuccessEvent</em> event.</p><pre>@Component</pre><pre>public class RegistrationEmailListener implements ApplicationListener&lt;OnRegistrationSuccessEvent&gt; { … }</pre><p>Inside this class, we will do the <strong>Dependency Injection</strong> for the <strong>IUserService </strong>and <strong>MailSender</strong> with the @Autowired annotaion of <strong>Spring</strong>.</p><pre>@Autowired</pre><pre>private IUserService userService;</pre><pre>@Autowired</pre><pre>private MailSender mailSender;</pre><p>Then we will override <strong>onApplicationEvent</strong>, the method defined by the org.springframework.context.ApplicationListener. Inside this we are going to call the <em>confirmRegistration</em> method that we will create in the next few steps.</p><pre>@Override</pre><pre>public void onApplicationEvent(OnRegistrationSuccessEvent event) {</pre><pre>this.confirmRegistration(event);</pre><pre>}</pre><p>The <em>confirmRegistration</em> method takes <strong>OnRegistrationSuccessEvent</strong> as its parameter.</p><pre>private void confirmRegistration(OnRegistrationSuccessEvent event) { … }</pre><p>Then we will initialize the user with the passed parameter. Each user <em>must have a unique id</em> because at this point we are still unaware that the new user have been already registered. For this, we create a unique token using the <strong>UUID</strong>. Using this UUID, we are going to create a <strong>verification token</strong> along with an <strong>expiration date</strong> and save it to the <em>VerificationToken</em> table in the database. When the user clicks the link, the verification token helps us to identify whether the confirmation link is valid and is not expired. We create this token in the <em>createVerificationToken</em> method implemented in the UserService.</p><p><em>RegistrationEmailListener.java</em></p><pre>User user = event.getUser();</pre><pre>String token = UUID.randomUUID().toString();</pre><pre>userService.createVerificationToken(user,token);</pre><p><em>IUserService.java</em></p><pre>public void createVerificationToken(User user, String token);</pre><p><em>UserService.java</em></p><pre>@Override <br>public void createVerificationToken(User user, String token) {  VerificationToken newUserToken = new VerificationToken(token, user);  tokenDAO.save(newUserToken); <br>}</pre><p>After saving the verification token, we will now generate the confirmation email that has to be sent to the user. Get the <em>recipient</em> from the user object. Then set the email subject text to whatever you want. But I recommend you to <em>give a subject related to the email message</em>. (i.e., Registration Confirmation.) Then we create the url by concatenating the appurl with the route to the method that activates the user and with the user token (i.e., <strong>UUID</strong>). We will then generate the message to be sent along with the email.</p><pre>String recipient = user.getEmail();</pre><pre>String subject = “Registration Confirmation”;</pre><pre>String url</pre><pre>= event.getAppUrl() + “/confirmRegistration?token=” + token;</pre><pre>String message = “Thank you for registering. Please click on the below link to activate your account.”;</pre><p>Now we have all the necessary data and we are going to send the email using the SimpleMailMessage.</p><pre>SimpleMailMessage email = new SimpleMailMessage();</pre><pre>email.setTo(recipient);</pre><pre>email.setSubject(subject);</pre><pre>email.setText(message + “http://localhost:8080&quot; + url);</pre><pre>mailSender.send(email);</pre><p>Create the <strong>SimpleMailMessage</strong> bean and set the <strong>SMTP</strong> mail settings in the <em>Config.java</em> file.</p><pre>@Bean(name = “mailSender”)</pre><pre>public MailSender javaMailService() {</pre><pre>JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();</pre><pre>javaMailSender.setHost(“smtp.gmail.com”);</pre><pre>javaMailSender.setPort(587);</pre><pre>javaMailSender.setProtocol(“smtp”);</pre><pre>javaMailSender.setUsername(“sender’s email”);</pre><pre>javaMailSender.setPassword(“sender’s password”);</pre><pre>Properties mailProperties = new Properties();</pre><pre>mailProperties.put(“mail.smtp.auth”, “true”);</pre><pre>mailProperties.put(“mail.smtp.starttls.enable”, “true”);</pre><pre>mailProperties.put(“mail.smtp.debug”, “true”);</pre><pre>javaMailSender.setJavaMailProperties(mailProperties);</pre><pre>return javaMailSender;</pre><pre>}</pre><pre>@Bean</pre><pre>public MessageSource messageSource() {</pre><pre>final ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();</pre><pre>messageSource.setBasename(“classpath:messages”);</pre><pre>messageSource.setUseCodeAsDefaultMessage(true);</pre><pre>messageSource.setDefaultEncoding(“UTF-8”);</pre><pre>messageSource.setCacheSeconds(0);</pre><pre>return messageSource;</pre><pre>}</pre><p>Now we have to create the VerificationToken Entity inside the entity package of your application.</p><p><em>VerificationToken.java</em></p><pre>@Entity</pre><pre>@Table(name = “verification_token”)</pre><pre>public class VerificationToken {</pre><pre>private static final int EXPIRATION = 60 * 24;</pre><pre>@Id</pre><pre>@GeneratedValue(strategy = GenerationType.IDENTITY)</pre><pre>private int id;</pre><pre>@Column(name=”token”)</pre><pre>private String token;</pre><pre>@OneToOne(targetEntity = User.class, fetch = FetchType.EAGER)</pre><pre>@JoinColumn(name = “user_id”, nullable = false)</pre><pre>private User user;</pre><pre>@Column(name=”created_date”)</pre><pre>private Date createdDate;</pre><pre>@Column(name=”expiry_date”)</pre><pre>private Date expiryDate;</pre><p>Generate the basic <em>getters/setters</em> and the <em>constructors</em> for the entity. We will create the <strong>calculateExpiryDate</strong> method to calculate the expiration date of the verification token.</p><p><em>VerificationToken.java</em></p><pre>private Date calculateExpiryDate(int expiryTimeInMinutes) {</pre><pre>Calendar calendar = Calendar.getInstance();</pre><pre>calendar.setTime(new Timestamp(calendar.getTime().getTime()));</pre><pre>calendar.add(Calendar.MINUTE, expiryTimeInMinutes);</pre><pre>return new Date(calendar.getTime().getTime());</pre><pre>}</pre><p>Then we are going to initiate the <strong>publishEvent </strong>in order to send the email to the user. After the email has successfully sent, the user will receive a success message.</p><p><em>AccountController.java</em></p><pre>try {</pre><pre>String appUrl = request.getContextPath();</pre><pre>eventPublisher.publishEvent(new OnRegistrationSuccessEvent(registeredUser, appUrl));</pre><pre>}catch(Exception re) {</pre><pre>re.printStackTrace();</pre><pre>}</pre><pre>return “registrationSuccess”;</pre><p>The user receives an email with the following format,</p><p><strong>Thank you for registering. Please click on the below link to activate your account. </strong><a href="http://localhost:8080/spring-email-verification/confirmRegistration?token=3e5a64c7-dbb1-4179-be48-be9361703457"><strong>http://localhost:8080/spring-email-verification/confirmRegistration?token=3e5a64c7-dbb1-4179-be48-be9361703457</strong></a></p><h4>After the user clicks the link:</h4><p>Now when the user clicks the link, he/she gets directed to the path /confirmRegistration .</p><p><em>AccountController.java</em></p><pre>@GetMapping(&quot;/confirmRegistration&quot;) </pre><pre>public String confirmRegistration(WebRequest request, Model model,@RequestParam(&quot;token&quot;) String token) {  </pre><pre>    VerificationToken verificationToken =      service.getVerificationToken(token);  <br>    if(verificationToken == null) {   <br>        String message = messages.getMessage(&quot;auth.message.invalidToken&quot;, null, locale);         <br>        model.addAttribute(&quot;message&quot;, message);   <br>        return &quot;redirect:access-denied&quot;;  <br>    }  </pre><pre>    User user = verificationToken.getUser();  <br>    Calendar calendar = Calendar.getInstance();       <br>    if((verificationToken.getExpiryDate().getTime()-calendar.getTime().getTime())&lt;=0) {   <br>        String message = messages.getMessage(&quot;auth.message.expired&quot;, null, locale);   <br>        model.addAttribute(&quot;message&quot;, message);   <br>        return &quot;redirect:access-denied&quot;;  <br>    }    </pre><pre>    user.setEnabled(true);  <br>    service.enableRegisteredUser(user);      <br>    return null; <br>}</pre><p>Here the <strong>GET method </strong>is called and it first checks whether the token is valid. If not valid, we are going to pass an error stating that the link is invalid. Then we will check the expiration of the token. If the link is valid in both the cases, we will activate the user with the setteruser.setEnabled(true).</p><p>Finally, in the <strong>UserService</strong> we will update the database with the new values.</p><p><em>IUserService.java</em></p><pre>public void enableRegisteredUser(User user);</pre><p><em>UserService.java</em></p><pre>@Override <br>@Transactional <br>public void enableRegisteredUser(User user) {  <br>    userDAO.save(user); <br>}</pre><p>So, we have successfully implemented the user account confirmation process with Spring. You can find the complete code <a href="https://github.com/angelapriyadharshini/spring-email-verification"><strong>in this Github repository</strong></a>.</p><p>Thank you for visiting my blog :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc3f5bb1398e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>