<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: APD</title>
    <description>The latest articles on DEV Community by APD (@apdharshi).</description>
    <link>https://dev.to/apdharshi</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F191983%2Fd9130329-6c19-4897-9cba-fb684c73ae0a.png</url>
      <title>DEV Community: APD</title>
      <link>https://dev.to/apdharshi</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/apdharshi"/>
    <language>en</language>
    <item>
      <title>Deploying your angular application to GitHub-pages</title>
      <dc:creator>APD</dc:creator>
      <pubDate>Fri, 08 Nov 2019 17:27:52 +0000</pubDate>
      <link>https://dev.to/apdharshi/deploying-your-angular-application-to-github-pages-4laf</link>
      <guid>https://dev.to/apdharshi/deploying-your-angular-application-to-github-pages-4laf</guid>
      <description>&lt;p&gt;In this article, you will learn how to deploy your angular application to GitHub pages.&lt;/p&gt;

&lt;p&gt;Let us go through the following steps,&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Create your angular app with Angular CLI&lt;/li&gt;
&lt;li&gt;Create a git repository&lt;/li&gt;
&lt;li&gt;Push your changes from local repository&lt;/li&gt;
&lt;li&gt;Deploy&lt;/li&gt;
&lt;li&gt;Get through the hurdles (optional)&lt;/li&gt;
&lt;li&gt;Safety tips&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Create your angular app with Angular CLI
&lt;/h3&gt;



&lt;p&gt;&lt;code&gt;ng new my-app --routing=true --style=scss&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;Now move to the project folder&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;cd my-app&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;Install all the dependencies&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npm install&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;Check your application locally&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;ng s -o&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;h3&gt;
  
  
  Create a git repository
&lt;/h3&gt;

&lt;p&gt;1 . Log in to your github account&lt;br&gt;
2 . On the top-right corner click the + icon and then select new repository&lt;br&gt;
3 . Check the “Initialize this repository with a README” if you need a README file to document your project, else just ignore it&lt;br&gt;
4 .  Now go ahead and click the “Create repository” button&lt;/p&gt;
&lt;h3&gt;
  
  
  Push your changes from local repository
&lt;/h3&gt;

&lt;p&gt;Again go to the terminal/command window and initialize your local application with git&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;git init&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;Check the status of the upstages files&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;git status&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;To stage all the changes use&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;git add .&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;Commit all the stages changes to your initial commit with a message&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;git commit -m "Initial commit"&lt;/code&gt;&lt;br&gt;
&lt;br&gt;
 &lt;strong&gt;(If you miss this step, you will get an error saying &lt;em&gt;“src refspec master does not match any.”&lt;/em&gt; So don’t forget your commit)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now set your origin to the remote repository&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;git remote add origin https://github.com/&amp;lt;username&amp;gt;/my-app.git&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;While &lt;strong&gt;connecting over HTTPS is recommended by GitHub&lt;/strong&gt;, If you still don’t want to type the GitHub password each and everytime you commit, just use the below command instead of the previously mentioned one.&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;git remote add origin git@github.com:&amp;lt;username&amp;gt;/&amp;lt;remote_repo_name&amp;gt;&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;But be sure to setup SSH in your device before using this method. &lt;/p&gt;

&lt;p&gt;Did you get ‘&lt;strong&gt;Github “fatal: remote origin already exists”&lt;/strong&gt;’ error? &lt;br&gt;
Then use,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;git remote rm 
git remote add origin https://github.com/&amp;lt;username&amp;gt;/my-app.git
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will remove the associated origin from remote and add it again.&lt;br&gt;
Note: &lt;strong&gt;git remote rm does not delete the remote repository&lt;/strong&gt; from the server. It simply removes the remote and its references from your local repository.&lt;/p&gt;

&lt;p&gt;Now push all changes to remote repository&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;git push origin master&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;h3&gt;
  
  
  Deploy
&lt;/h3&gt;

&lt;p&gt;Since you have pushed everything to your remote, you are now ready to deploy your application.&lt;/p&gt;

&lt;p&gt;Build your application with “&lt;strong&gt;--prod&lt;/strong&gt;” for production mode and provide the --base-href to which link your application has to be hosted. In your case this would be&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;ng build --prod --base-href "https://&amp;lt;username&amp;gt;.github.io/my-app/"&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;If everything is fine, then continue. Else go to the 2nd troubleshoot of the “&lt;strong&gt;Get-through the hurdles&lt;/strong&gt;” section below and comeback soon.&lt;/p&gt;

&lt;p&gt;If you don’t have &lt;strong&gt;angular-cli-ghpages&lt;/strong&gt; installed globally in your system,&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npm install -g angular-cli-ghpages&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;Now deploy,&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;angular-cli-ghpages --dir=dist/angular-app&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;Angular 6 &amp;amp; below&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;angular-cli-ghpages&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;Did you get a message “Successfully published!” ? Hooray!!! You have deployed your app successfully!&lt;/p&gt;

&lt;p&gt;Now goto &lt;strong&gt;https://&lt;em&gt;username&lt;/em&gt;.github.io/my-app/&lt;/strong&gt;(the link provided by you as the “base-href”) and check your application up and running.&lt;/p&gt;

&lt;p&gt;For updating your application with any new changes, just commit, push and follow the steps mentioned under the topic “Deploy”.&lt;br&gt;
&lt;strong&gt;Note:&lt;/strong&gt; After your first deployment, you don’t need to use the “&lt;strong&gt;--base-href&lt;/strong&gt;” flag again as it is already set.&lt;/p&gt;

&lt;p&gt;Why do we provide --dir in newer versions?&lt;br&gt;
In older versions(6 or below) the output folder is dist itself. &lt;br&gt;
But &lt;strong&gt;in newer versions the output folder is dist/project-name/ by default&lt;/strong&gt;. To output to a different folder, change the outputPath in angular.json.&lt;/p&gt;

&lt;p&gt;Get-through the hurdles&lt;/p&gt;

&lt;p&gt;1 . After creating your remote repository, if you receive some message saying: “&lt;strong&gt;We found a vulnerable dependency in a repository you have security alert access to.&lt;/strong&gt;”, &lt;br&gt;
open a terminal/command window on your project location and then run&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npm audit fix&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;This will fix your problem&lt;/p&gt;

&lt;p&gt;2 . While running ‘ng build --prod --base-href "https://&lt;em&gt;username&lt;/em&gt;.github.io/my-app/“‘ some of you may have got the below error&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Error: Schema validation failed with the following errors:&lt;br&gt;
  Data path ".builders['app-shell']" should have required property 'class'.&lt;br&gt;
    at MergeMapSubscriber._registry.compile.pipe.operators_1.concatMap.validatorResult [as project] (/Users/&amp;lt;username&amp;gt;/git/my-app/node_modules/@angular-devkit/core/src/workspace/workspace.js:215:42)&lt;br&gt;
    at MergeMapSubscriber._tryNext (/Users/&amp;lt;username&amp;gt;/git/my-app/node_modules/rxjs/internal/operators/mergeMap.js:69:27)&lt;br&gt;
    at MergeMapSubscriber._next (/Users/&amp;lt;username&amp;gt;/git/my-app/node_modules/rxjs/internal/operators/mergeMap.js:59:18)&lt;br&gt;
    at MergeMapSubscriber.Subscriber.next (/Users/&amp;lt;username&amp;gt;/git/my-app/node_modules/rxjs/internal/Subscriber.js:67:18)&lt;br&gt;
    at MergeMapSubscriber.notifyNext (/Users/&amp;lt;username&amp;gt;/git/my-app/node_modules/rxjs/internal/operators/mergeMap.js:92:26)&lt;br&gt;
    at InnerSubscriber._next (/Users/&amp;lt;username&amp;gt;/git/my-app/node_modules/rxjs/internal/InnerSubscriber.js:28:21)&lt;br&gt;
    at InnerSubscriber.Subscriber.next (/Users/&amp;lt;username&amp;gt;/git/my-app/node_modules/rxjs/internal/Subscriber.js:67:18)&lt;br&gt;
    at MapSubscriber._next (/Users/&amp;lt;username&amp;gt;/git/my-app/node_modules/rxjs/internal/operators/map.js:55:26)&lt;br&gt;
    at MapSubscriber.Subscriber.next (/Users/&amp;lt;username&amp;gt;/git/my-app/node_modules/rxjs/internal/Subscriber.js:67:18)&lt;br&gt;
    at SwitchMapSubscriber.notifyNext (/Users/&amp;lt;username&amp;gt;/git/my-app/node_modules/rxjs/internal/operators/switchMap.js:86:26)&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;To fix this,&lt;br&gt;
Goto your working directory&lt;br&gt;
Delete the &lt;em&gt;node_modules&lt;/em&gt; folder&lt;br&gt;
Also delete &lt;em&gt;package_lock.json&lt;/em&gt; file&lt;/p&gt;

&lt;p&gt;Now open package.json file&lt;br&gt;
In the “devDependencies” change the “&lt;em&gt;@angular-devkit/build-angular&lt;/em&gt;” version to "&lt;em&gt;~0.13.4&lt;/em&gt;"&lt;/p&gt;

&lt;p&gt;Run&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npm install&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;h4&gt;
  
  
  Safety tips
&lt;/h4&gt;

&lt;ol&gt;
&lt;li&gt;In your GitHub pages repo settings, be sure that you have checked the Enforce HTTPS option&lt;/li&gt;
&lt;li&gt;While deploying, always provide your --base-href with a https prefix rather than a http.&lt;/li&gt;
&lt;/ol&gt;

&lt;h5&gt;
  
  
  Reason:
&lt;/h5&gt;

&lt;p&gt;Otherwise you may get few errors like,&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Mixed Content: The page at ‘&amp;lt;your_gpages_remote_url&amp;gt;’ was loaded over HTTPS, but requested an insecure stylesheet ‘&amp;lt;url_provided_with_http_prefix_while_deploying&amp;gt;/styles.acb808cb000123f5c6ec.css'. This request has been blocked; the content must be served over HTTPS.&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;a href="https://help.github.com/en/github/working-with-github-pages/securing-your-github-pages-site-with-https"&gt;Read more here&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Thank you for reading this article and I hope you had a useful time. Have a great day!&lt;/p&gt;

</description>
      <category>angular</category>
      <category>github</category>
    </item>
    <item>
      <title>Ways to fix “-bash: ng: command not found”</title>
      <dc:creator>APD</dc:creator>
      <pubDate>Sat, 02 Nov 2019 21:20:27 +0000</pubDate>
      <link>https://dev.to/apdharshi/ways-to-fix-bash-ng-command-not-found-35fo</link>
      <guid>https://dev.to/apdharshi/ways-to-fix-bash-ng-command-not-found-35fo</guid>
      <description>&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F590%2F1%2A1bh2mszm6rtMXA8F-IbPjw.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F590%2F1%2A1bh2mszm6rtMXA8F-IbPjw.jpeg"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  What you have already tried
&lt;/h4&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

ng version


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;or any other &lt;em&gt;ng&lt;/em&gt; commands.&lt;/p&gt;

&lt;h4&gt;
  
  
  Error produced by the previous command
&lt;/h4&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

-bash: ng: command not found


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h4&gt;
  
  
  Before heading into the fix, let me ask a question
&lt;/h4&gt;

&lt;p&gt;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 &lt;a href="https://angular.io/guide/setup-local" rel="noopener noreferrer"&gt;official Angular site&lt;/a&gt; and get the latest version installed :)&lt;/p&gt;

&lt;p&gt;This problem is caused due to the reason that &lt;strong&gt;npm is unable to find ng.&lt;/strong&gt; There are few ways that we can follow to get rid of this error.&lt;/p&gt;
&lt;h4&gt;
  
  
  1 . Linking angular/cli with npm
&lt;/h4&gt;

&lt;p&gt;This can be done using the command,&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

npm link @angular/cli


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h4&gt;
  
  
  2. Setting the location of npm folder
&lt;/h4&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

export PATH="$HOME/.npm-global/bin:$PATH"


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;or&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

export PATH="$HOME/.npm-packages/bin:$PATH"


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h4&gt;
  
  
  3. Clearing cache and Re-installing Angular (least recommended)
&lt;/h4&gt;

&lt;p&gt;In this case, you may need to uninstall angular from your machine with the command&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

npm uninstall -g @angular/cli
npm cache clean
npm install -g @angular/cli


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h4&gt;
  
  
  4. Giving an alias to ng path
&lt;/h4&gt;

&lt;p&gt;To do this you must know the full path of your angular installation. For example: &lt;em&gt;“/Users/&amp;lt;username&amp;gt;/.npm-global/lib/node_modules/@angular/cli/bin/ng”.&lt;/em&gt; So the command would be&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

alias ng="/Users/Dharshini/.npm-global/lib/node\_modules/@angular/cli/bin/ng"


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;So how can we permanently solve this? Here comes the solution. &lt;em&gt;Credits:&lt;/em&gt; &lt;a href="https://github.com/angular/angular-cli/issues/5021#issuecomment-377030706" rel="noopener noreferrer"&gt;&lt;em&gt;Thanks for this fix&lt;/em&gt;&lt;/a&gt;&lt;em&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  5 . By adding the PATH directly to the Mac OS terminal
&lt;/h4&gt;

&lt;p&gt;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&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

cd ~


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;to get to the base of your files. Then in order to list all your base files, enter&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

ls -a


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now you must see “&lt;em&gt;.npm-global&lt;/em&gt;” listed in the files.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F426%2F1%2AkB_uuT6Jn_siQhbTDcScMw.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F426%2F1%2AkB_uuT6Jn_siQhbTDcScMw.jpeg"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If its not there, again I recommend you to install Angular using the official documentation link I have mentioned in the beginning.&lt;/p&gt;

&lt;p&gt;If the folder is listed, you are good to go. Go back to the base of the user using the command&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

cd ~


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Here we are going to edit the paths using vim editor. Use “&lt;em&gt;sudo&lt;/em&gt;” in front of the command to avoid permission issues. Here you will be prompted to enter the device’s password.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

sudo vim /etc/paths


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The editor now opens a file containing some paths as shown below. All you have to do here is to insert the path of &lt;em&gt;.npm-global/bin&lt;/em&gt; to the list. To do so you have to press insert from your mac keyboard (press &lt;em&gt;fn + i&lt;/em&gt; key combination), navigate to the bottom of the list and add ~/.npm-global/bin as I have added below.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

/usr/local/bin
/usr/bin
/bin
/usr/sbin
/sbin
~/.npm-global/bin
~ 
~


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now to save your changes and exit, press &lt;em&gt;ESc&lt;/em&gt; 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&lt;/p&gt;

&lt;p&gt;echo $PATH&lt;/p&gt;

&lt;p&gt;This should give you all the paths with the newly added one concatenated at the end.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:~/.npm-global/bin&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Finally the happy ending. Try any &lt;em&gt;ng&lt;/em&gt; command&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

ng version


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;There you go! Thanks for reading this article. Have a great day!&lt;/p&gt;

</description>
      <category>angular</category>
      <category>angularcli</category>
    </item>
    <item>
      <title>Difference between Arrays and JSON Objects</title>
      <dc:creator>APD</dc:creator>
      <pubDate>Thu, 16 May 2019 22:08:55 +0000</pubDate>
      <link>https://dev.to/apdharshi/difference-between-arrays-and-json-objects-ceg</link>
      <guid>https://dev.to/apdharshi/difference-between-arrays-and-json-objects-ceg</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--FkZGTatU--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://cdn-images-1.medium.com/max/1024/1%2ALM5eeUhJpt4IyBq4bcNQuQ.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--FkZGTatU--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://cdn-images-1.medium.com/max/1024/1%2ALM5eeUhJpt4IyBq4bcNQuQ.jpeg" alt="" width="800" height="800"&gt;&lt;/a&gt;Designed by Freshgraphix / Freepik&lt;/p&gt;

&lt;p&gt;Sometimes most of us get confused while dealing with Arrays and Objects. This leads into further confusions when choosing which manipulation technique to use. &lt;em&gt;For example&lt;/em&gt;, we can find the length only if we know whether it is an array or an object. As both have different approaches.&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;h3&gt;
  
  
  What are Arrays?
&lt;/h3&gt;

&lt;p&gt;Array items are accessed using  &lt;strong&gt;indices&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Format&lt;/em&gt; [ , , , ]&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Example&lt;/em&gt; [1, 2, 3, 4, 5]&lt;/p&gt;

&lt;p&gt;Arrays can contain objects, strings, numbers, arrays &amp;amp; boolean.&lt;/p&gt;

&lt;h4&gt;
  
  
  &lt;strong&gt;Initialization&lt;/strong&gt;
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;1. _datatype_[] = [, , ,];

2. Array\&amp;lt;_datatype_\&amp;gt; = [, , ,]; // _Uses a generic array type_
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  &lt;strong&gt;Array of objects&lt;/strong&gt;
&lt;/h4&gt;

&lt;p&gt;&lt;em&gt;Syntax :&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[{“ “:” “,” “:” “},{“ “:” “,” “:” “}]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Example:&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[
 { “position”: “winner”,”country”: “U.S.A” },

{ “position”: “runner”,”country”: “China” }

];

[
 { “rainy”: true,”sunny”: false },

{ “rainy”: false,”sunny”: true }

]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  &lt;strong&gt;Array of strings&lt;/strong&gt;
&lt;/h4&gt;

&lt;p&gt;&lt;em&gt;Example:&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’,’Friday’, ‘Saturday’];

[‘a’, ‘b’, ‘c’, ‘d’];

[‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ’6’, ‘7’];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  &lt;strong&gt;Array of numbers&lt;/strong&gt;
&lt;/h4&gt;

&lt;p&gt;&lt;em&gt;Example:&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[1, 2, 3, 4, 5];

[788.34, 432.34, 3234.72];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  &lt;strong&gt;Array of arrays&lt;/strong&gt;
&lt;/h4&gt;

&lt;p&gt;These can be otherwise called as &lt;strong&gt;multi-dimensional&lt;/strong&gt; arrays.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[

[1, 2, 3, 4, 5, 6, 7],

[1, 2, 3, 4, 5, 6, 7],

[1, 2, 3, 4, 5, 6, 7],

[1, 2, 3, 4, 5, 6, 7],

[1, 2, 3, 4, 5, 6, 7],

[1, 2, 3, 4, 5, 6, 7]

];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Array of booleans
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[true, false, false, true]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  What are Objects?
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;An &lt;strong&gt;object&lt;/strong&gt; 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.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Object properties are accessed using  &lt;strong&gt;keys.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Keys&lt;/strong&gt; must be strings, and values must be a &lt;strong&gt;valid JSON data type&lt;/strong&gt; (string, number, &lt;strong&gt;object&lt;/strong&gt; , array, boolean or null).&lt;/p&gt;

&lt;p&gt;Format { “ ”: “ ” }&lt;/p&gt;

&lt;p&gt;Example {“position”: “winner”,”country”: “U.S.A”}&lt;/p&gt;

&lt;h4&gt;
  
  
  &lt;strong&gt;Object of arrays and objects&lt;/strong&gt;
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{

“binary”: [{“id”:1,”name”:0},{“id”:2,”name”:1}],

“boolean”: [{“id”:1,”value”: false},{“id”:2,”value”: true}]

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Nested Objects:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;“results”: {

“tennis”: [
 {“position”: “winner”,“country”: “U.S.A},

{“position”: “runner”,“country”: “China”}
 ]

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  &lt;strong&gt;Object of objects&lt;/strong&gt;
&lt;/h4&gt;

&lt;p&gt;&lt;strong&gt;JSON Objects&lt;/strong&gt; are enclosed within {}&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;“universe”: {

“planets”: {

“day”: “Sun”,

“night”: “Moon”

}

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Nested JSON Object:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;json: any = {

"visible": true,

"colors": {

"data": {

"darkest": "Black",

"lightest": "white",

"neutral": "Grey",

"spectrum": {

"1": "Violet",

"2": "Indigo",

"3": "Blue",

"4": "Green",

"5": "Yellow",

"6": "Orange",

"7": "Red"

},

"default": "Grey",

"primary": "Blue",

"danger": "Red",

"warning": "Yellow",

"success": "Green",

"RGB": {

"r": "Red",

"g": "Green",

"b": "Blue"

}

}

}

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So these are the differences between Arrays and Objects. I hope that from now you all can use these types without any worries.&lt;/p&gt;

&lt;p&gt;Happy coding :)&lt;/p&gt;

</description>
      <category>angular</category>
      <category>javascript</category>
      <category>typescript</category>
      <category>objects</category>
    </item>
    <item>
      <title>Understanding the usage of optional and nullable in TypeScript</title>
      <dc:creator>APD</dc:creator>
      <pubDate>Mon, 22 Oct 2018 11:16:20 +0000</pubDate>
      <link>https://dev.to/apdharshi/understanding-the-usage-of-optional-and-nullable-in-typescript-3ii4</link>
      <guid>https://dev.to/apdharshi/understanding-the-usage-of-optional-and-nullable-in-typescript-3ii4</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--UVHiGtoo--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://cdn-images-1.medium.com/max/1024/1%2A3jpAbmyZn6TozMQpw-XSxw.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--UVHiGtoo--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://cdn-images-1.medium.com/max/1024/1%2A3jpAbmyZn6TozMQpw-XSxw.jpeg" alt="" width="800" height="521"&gt;&lt;/a&gt;Designed by fanjianhua / Freepik&lt;/p&gt;

&lt;p&gt;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 &lt;strong&gt;nullable&lt;/strong&gt; and &lt;strong&gt;optional&lt;/strong&gt; parameters.&lt;/p&gt;

&lt;h4&gt;
  
  
  Common misconception
&lt;/h4&gt;

&lt;p&gt;Most developers fall into the category of misunderstanding nullable and optional parameters. The confusion arises on where to use the “ &lt;strong&gt;?&lt;/strong&gt; ”. Look at this code block.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function example(x: number?, y?: string) {
 // …
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  “?” Suffix
&lt;/h4&gt;

&lt;p&gt;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?&lt;br&gt;&lt;br&gt;
&lt;strong&gt;The answer is no&lt;/strong&gt;. The first one indicates a &lt;strong&gt;nullable&lt;/strong&gt; parameter that can also be a number, &lt;em&gt;undefined&lt;/em&gt; or &lt;em&gt;null&lt;/em&gt;. But, the second argument is an &lt;strong&gt;optional&lt;/strong&gt; , it can be a string or &lt;em&gt;undefined&lt;/em&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;x // =\&amp;gt; number | undefined | null
y // =\&amp;gt; number | undefined
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Undefined vs Null
&lt;/h4&gt;

&lt;p&gt;Again here some may not be aware of the difference between “ &lt;strong&gt;undefined&lt;/strong&gt; ” and “ &lt;strong&gt;null&lt;/strong&gt; ”. Undefined represents something that may not exist. Null is used for things that are nullable. So both are entirely different.&lt;/p&gt;

&lt;h4&gt;
  
  
  [@Optional]
&lt;/h4&gt;

&lt;p&gt;So what is this &lt;strong&gt;@Optional&lt;/strong&gt; in angular is all about? What is the difference between “?” and @Optional? As the official document says, Optional is a constructor parameter decorator that marks a dependency as optional. This clearly states that @Optional is used in the context of &lt;strong&gt;DI&lt;/strong&gt; (Dependency Injection). Here is an example from the &lt;a href="https://angular.io/api/core/Optional"&gt;official docs&lt;/a&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Injectable()
class Car {
  constructor(@Optional() public engine: Engine) {}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;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 &lt;strong&gt;@Optional&lt;/strong&gt; annotation with “ &lt;strong&gt;?”&lt;/strong&gt;. The injector will search for the dependency and when it is undefined, it will throw the exception. &lt;/p&gt;

&lt;p&gt;It is always nice to follow the best practices and learn something new :)&lt;/p&gt;

</description>
      <category>typescript</category>
      <category>angular</category>
    </item>
    <item>
      <title>Account activation by sending email confirmation with Java Spring MVC</title>
      <dc:creator>APD</dc:creator>
      <pubDate>Mon, 20 Aug 2018 19:48:13 +0000</pubDate>
      <link>https://dev.to/apdharshi/account-activation-by-sending-email-confirmation-with-java-spring-mvc-1k9k</link>
      <guid>https://dev.to/apdharshi/account-activation-by-sending-email-confirmation-with-java-spring-mvc-1k9k</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--X0xdv5IJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://cdn-images-1.medium.com/max/1024/1%2ATYt5TmOPN1236zCLHbvfcw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--X0xdv5IJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://cdn-images-1.medium.com/max/1024/1%2ATYt5TmOPN1236zCLHbvfcw.png" alt="" width="800" height="159"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;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 &lt;strong&gt;GitHub repository&lt;/strong&gt; mentioned at the end of this article).&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Entity&lt;/strong&gt;  — VerificationToken.java&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Repository layers &lt;/strong&gt; — TokenDAO.java, ITokenDAO.java&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Package&lt;/strong&gt;  — event&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;event&lt;/strong&gt; &amp;gt; &lt;strong&gt;Event&lt;/strong&gt;  — OnRegistrationSuccessEvent.java&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;event&lt;/strong&gt; &amp;gt; &lt;strong&gt;EventListener&lt;/strong&gt;  — RegistrationEmailListener.java&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;First we are going to start with our &lt;strong&gt;AccountController.java&lt;/strong&gt;. The user fills the registration form and clicks submit. Onsubmit, the &lt;strong&gt;User&lt;/strong&gt; object with the data is posted to the &lt;em&gt;registerNewUser&lt;/em&gt; method with the following method signature.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;AccountController.java&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public String registerNewUser(@ModelAttribute(“user”) UserDTO userDto, BindingResult result, WebRequest request, Model model) { … }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt; : Please ensure that you give the parameters in the same order as above. Changing this order may give you some unwanted errors.&lt;/p&gt;

&lt;p&gt;Always make sure that you &lt;em&gt;do not use your entity directly on your controller&lt;/em&gt; as it may put your application into security vulnerabilities. (i.e., &lt;em&gt;you may expose the entire domain model to the client&lt;/em&gt;. We really don’t want this to happen). So make use of a &lt;strong&gt;Data Transfer Object (DTO)&lt;/strong&gt; as a middle layer to acces the entity.&lt;/p&gt;

&lt;p&gt;We recall few steps from the registration process here,&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Initialize a new User object.&lt;/li&gt;
&lt;li&gt;Find that the user already exists.&lt;/li&gt;
&lt;li&gt;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&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;AccountController.java&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;User registeredUser = new User();

String userName = userDto.getUserName();

if (result.hasErrors()) {

return “registration”;

}

registeredUser = service.findByUsername(userName);

if(registeredUser!=null) {

model.addAttribute(“error”,”There is already an account with this username: “ + userName);

return “registration”;

}

registeredUser = service.registerUser(userDto);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now let’s move into the confirmation of user via email.&lt;/p&gt;

&lt;p&gt;Before going to the controller code, we have to first create the &lt;strong&gt;Event&lt;/strong&gt; and &lt;strong&gt;EventListener&lt;/strong&gt; in order to send the email on successful registration of the user.&lt;/p&gt;

&lt;p&gt;This will be our event,&lt;/p&gt;

&lt;p&gt;&lt;em&gt;OnRegistrationSuccessEvent.java&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class OnRegistrationSuccessEvent extends ApplicationEvent {

private static final long serialVersionUID = 1L;

private String appUrl;

private User user;

public OnRegistrationSuccessEvent(User user, String appUrl) {

super(user);

this.user = user;

this.appUrl = appUrl;

}

public String getAppUrl() {

return appUrl;

}

public void setAppUrl(String appUrl) {

this.appUrl = appUrl;

}

public User getUser() {

return user;

}

public void setUser(User user) {

this.user = user;

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Events must always inherit the &lt;strong&gt;ApplicationEvent&lt;/strong&gt; class of Spring that is inherited from the &lt;strong&gt;java.util.EventObject&lt;/strong&gt;. We have three variables &lt;em&gt;serialVersionUID, appurl and user&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;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 &lt;strong&gt;Java docs&lt;/strong&gt; for &lt;a href="https://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html"&gt;&lt;strong&gt;java.io.Serializable&lt;/strong&gt;&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;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 &lt;em&gt;getters/setters&lt;/em&gt; and &lt;em&gt;constructors&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Next is we have to build an &lt;strong&gt;EventListener&lt;/strong&gt; to handle the &lt;em&gt;OnRegistrationSuccessEvent&lt;/em&gt;. 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 &lt;strong&gt;RegistrationEmailListener&lt;/strong&gt; &lt;em&gt;inherits&lt;/em&gt; the &lt;strong&gt;ApplicationListener&lt;/strong&gt; that Listens to our &lt;em&gt;OnRegistrationSuccessEvent&lt;/em&gt; event.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Component

public class RegistrationEmailListener implements ApplicationListener\&amp;lt;OnRegistrationSuccessEvent\&amp;gt; { … }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Inside this class, we will do the &lt;strong&gt;Dependency Injection&lt;/strong&gt; for the &lt;strong&gt;IUserService&lt;/strong&gt; and &lt;strong&gt;MailSender&lt;/strong&gt; with the @Autowired annotaion of  &lt;strong&gt;Spring&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Autowired

private IUserService userService;

@Autowired

private MailSender mailSender;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then we will override &lt;strong&gt;onApplicationEvent&lt;/strong&gt; , the method defined by the org.springframework.context.ApplicationListener. Inside this we are going to call the &lt;em&gt;confirmRegistration&lt;/em&gt; method that we will create in the next few steps.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Override

public void onApplicationEvent(OnRegistrationSuccessEvent event) {

this.confirmRegistration(event);

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;em&gt;confirmRegistration&lt;/em&gt; method takes &lt;strong&gt;OnRegistrationSuccessEvent&lt;/strong&gt; as its parameter.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private void confirmRegistration(OnRegistrationSuccessEvent event) { … }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then we will initialize the user with the passed parameter. Each user &lt;em&gt;must have a unique id&lt;/em&gt; 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 &lt;strong&gt;UUID&lt;/strong&gt;. Using this UUID, we are going to create a &lt;strong&gt;verification token&lt;/strong&gt; along with an &lt;strong&gt;expiration date&lt;/strong&gt; and save it to the &lt;em&gt;VerificationToken&lt;/em&gt; 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 &lt;em&gt;createVerificationToken&lt;/em&gt; method implemented in the UserService.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;RegistrationEmailListener.java&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;User user = event.getUser();

String token = UUID.randomUUID().toString();

userService.createVerificationToken(user,token);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;IUserService.java&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public void createVerificationToken(User user, String token);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;UserService.java&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Override 
public void createVerificationToken(User user, String token) { VerificationToken newUserToken = new VerificationToken(token, user); tokenDAO.save(newUserToken); 
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After saving the verification token, we will now generate the confirmation email that has to be sent to the user. Get the &lt;em&gt;recipient&lt;/em&gt; from the user object. Then set the email subject text to whatever you want. But I recommend you to &lt;em&gt;give a subject related to the email message&lt;/em&gt;. (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., &lt;strong&gt;UUID&lt;/strong&gt; ). We will then generate the message to be sent along with the email.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;String recipient = user.getEmail();

String subject = “Registration Confirmation”;

String url

= event.getAppUrl() + “/confirmRegistration?token=” + token;

String message = “Thank you for registering. Please click on the below link to activate your account.”;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we have all the necessary data and we are going to send the email using the SimpleMailMessage.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SimpleMailMessage email = new SimpleMailMessage();

email.setTo(recipient);

email.setSubject(subject);

email.setText(message + “http://localhost:8080" + url);

mailSender.send(email);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Create the &lt;strong&gt;SimpleMailMessage&lt;/strong&gt; bean and set the &lt;strong&gt;SMTP&lt;/strong&gt; mail settings in the &lt;em&gt;Config.java&lt;/em&gt; file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Bean(name = “mailSender”)

public MailSender javaMailService() {

JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();

javaMailSender.setHost(“smtp.gmail.com”);

javaMailSender.setPort(587);

javaMailSender.setProtocol(“smtp”);

javaMailSender.setUsername(“sender’s email”);

javaMailSender.setPassword(“sender’s password”);

Properties mailProperties = new Properties();

mailProperties.put(“mail.smtp.auth”, “true”);

mailProperties.put(“mail.smtp.starttls.enable”, “true”);

mailProperties.put(“mail.smtp.debug”, “true”);

javaMailSender.setJavaMailProperties(mailProperties);

return javaMailSender;

}

@Bean

public MessageSource messageSource() {

final ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();

messageSource.setBasename(“classpath:messages”);

messageSource.setUseCodeAsDefaultMessage(true);

messageSource.setDefaultEncoding(“UTF-8”);

messageSource.setCacheSeconds(0);

return messageSource;

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we have to create the VerificationToken Entity inside the entity package of your application.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;VerificationToken.java&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Entity

@Table(name = “verification\_token”)

public class VerificationToken {

private static final int EXPIRATION = 60 \* 24;

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private int id;

@Column(name=”token”)

private String token;

@OneToOne(targetEntity = User.class, fetch = FetchType.EAGER)

@JoinColumn(name = “user\_id”, nullable = false)

private User user;

@Column(name=”created\_date”)

private Date createdDate;

@Column(name=”expiry\_date”)

private Date expiryDate;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Generate the basic &lt;em&gt;getters/setters&lt;/em&gt; and the &lt;em&gt;constructors&lt;/em&gt; for the entity. We will create the &lt;strong&gt;calculateExpiryDate&lt;/strong&gt; method to calculate the expiration date of the verification token.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;VerificationToken.java&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private Date calculateExpiryDate(int expiryTimeInMinutes) {

Calendar calendar = Calendar.getInstance();

calendar.setTime(new Timestamp(calendar.getTime().getTime()));

calendar.add(Calendar.MINUTE, expiryTimeInMinutes);

return new Date(calendar.getTime().getTime());

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then we are going to initiate the &lt;strong&gt;publishEvent&lt;/strong&gt; in order to send the email to the user. After the email has successfully sent, the user will receive a success message.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;AccountController.java&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;try {

String appUrl = request.getContextPath();

eventPublisher.publishEvent(new OnRegistrationSuccessEvent(registeredUser, appUrl));

}catch(Exception re) {

re.printStackTrace();

}

return “registrationSuccess”;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The user receives an email with the following format,&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thank you for registering. Please click on the below link to activate your account.&lt;/strong&gt; &lt;a href="http://localhost:8080/spring-email-verification/confirmRegistration?token=3e5a64c7-dbb1-4179-be48-be9361703457"&gt;&lt;strong&gt;http://localhost:8080/spring-email-verification/confirmRegistration?token=3e5a64c7-dbb1-4179-be48-be9361703457&lt;/strong&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  After the user clicks the link:
&lt;/h4&gt;

&lt;p&gt;Now when the user clicks the link, he/she gets directed to the path /confirmRegistration .&lt;/p&gt;

&lt;p&gt;&lt;em&gt;AccountController.java&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@GetMapping("/confirmRegistration")

public String confirmRegistration(WebRequest request, Model model,@RequestParam("token") String token) {

VerificationToken verificationToken = service.getVerificationToken(token); 
 if(verificationToken == null) { 
 String message = messages.getMessage("auth.message.invalidToken", null, locale); 
 model.addAttribute("message", message); 
 return "redirect:access-denied"; 
 }

User user = verificationToken.getUser(); 
 Calendar calendar = Calendar.getInstance(); 
 if((verificationToken.getExpiryDate().getTime()-calendar.getTime().getTime())\&amp;lt;=0) { 
 String message = messages.getMessage("auth.message.expired", null, locale); 
 model.addAttribute("message", message); 
 return "redirect:access-denied"; 
 }

user.setEnabled(true); 
 service.enableRegisteredUser(user); 
 return null; 
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here the &lt;strong&gt;GET method&lt;/strong&gt; 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).&lt;/p&gt;

&lt;p&gt;Finally, in the &lt;strong&gt;UserService&lt;/strong&gt; we will update the database with the new values.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;IUserService.java&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public void enableRegisteredUser(User user);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;UserService.java&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Override 
@Transactional 
public void enableRegisteredUser(User user) { 
 userDAO.save(user); 
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So, we have successfully implemented the user account confirmation process with Spring. You can find the complete code &lt;a href="https://github.com/angelapriyadharshini/spring-email-verification"&gt;&lt;strong&gt;in this Github repository&lt;/strong&gt;&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Thank you for visiting my blog :)&lt;/p&gt;

</description>
      <category>java</category>
      <category>spring</category>
    </item>
  </channel>
</rss>
