<?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 Chinthaka Jayatilake on Medium]]></title>
        <description><![CDATA[Stories by Chinthaka Jayatilake on Medium]]></description>
        <link>https://medium.com/@chinthakajayatilake98?source=rss-1b3554b6fdf8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ucSHNHx05CUOkfMLLx_tLA.jpeg</url>
            <title>Stories by Chinthaka Jayatilake on Medium</title>
            <link>https://medium.com/@chinthakajayatilake98?source=rss-1b3554b6fdf8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 18:20:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chinthakajayatilake98/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[Upload and View Files in Amazon S3 using Angular + Spring Boot]]></title>
            <link>https://medium.com/linkit-intecs/upload-and-view-files-in-amazon-s3-using-angular-spring-boot-325b118e7188?source=rss-1b3554b6fdf8------2</link>
            <guid isPermaLink="false">https://medium.com/p/325b118e7188</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[s3-bucket]]></category>
            <dc:creator><![CDATA[Chinthaka Jayatilake]]></dc:creator>
            <pubDate>Thu, 10 Oct 2019 09:40:03 GMT</pubDate>
            <atom:updated>2020-05-30T18:21:41.302Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*WdJb0dgs4KAgRA62JD-oPA.jpeg" /><figcaption>Photo by Christian Wiediger on Unsplash</figcaption></figure><p>Amazon Simple Storage Service (Amazon S3) is an object storage service that offers industry-leading scalability, data availability, security, and performance. This can be used to store and protect any amount of data for a range of use cases, such as websites, mobile applications, backup and restore, archive, enterprise applications, IoT devices, and big data analytics.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F_I14_sXHO8U%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D_I14_sXHO8U&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F_I14_sXHO8U%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7983573d37eb35416303bb73a0a5e99e/href">https://medium.com/media/7983573d37eb35416303bb73a0a5e99e/href</a></iframe><p>So let us now see how we could use Amazon S3 in our projects to store and retrieve files.</p><p>To start with, we will create our Angular project.</p><pre>ng new project_name</pre><p>Next is to create a simple HTML page to upload, view, and delete files. For that, we will move to the <em>app.component.html</em> page and start implementing it.</p><pre>&lt;h1&gt;Upload,View &amp; Delete File&lt;/h1&gt;</pre><pre>&lt;input type=&quot;file&quot; id=&quot;customFile&quot; (change)=&quot;selectFile($event)&quot; placeholder=&quot;File To Upload&quot;&gt;</pre><pre>&lt;button class=&quot;btn btn-primary&quot; [disabled]=&quot;!selectedFiles || admincheck || status&quot; (click)=&quot;upload()&quot;&gt;Save File&lt;/button&gt;</pre><pre>&lt;br&gt;&lt;br&gt;&lt;br&gt;</pre><pre>&lt;input type=&quot;text&quot; placeholder=&quot;File to View or Delete&quot;  name=&quot;image&quot; [(ngModel)]=&quot;file&quot;&gt;</pre><pre>&lt;button class=&quot;btn btn-primary&quot; style=&quot;margin-left: 10px&quot; (click)=&quot;viewFile()&quot;&gt;View File&lt;/button&gt;</pre><pre>&lt;button class=&quot;btn btn-primary&quot; style=&quot;margin-left: 10px&quot; (click)=&quot;deleteFile()&quot;&gt;Delete File&lt;/button&gt;</pre><p>Now we need to create a service to communicate with the back-end and to send the selected file as a multipart file to the back-end.</p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { HttpClient, HttpEvent, HttpRequest } from &#39;@angular/common/http&#39;;<br>import { Observable } from &#39;rxjs&#39;;</pre><pre>@Injectable({<br>  providedIn: &#39;root&#39;<br>})</pre><pre>export class UploadFileService {</pre><pre>  constructor(private https: HttpClient) { }</pre><pre>  pushFileToStorage(file: File): Observable&lt;HttpEvent&lt;{}&gt;&gt; {</pre><pre>    const data: FormData = new FormData();<br>    data.append(&#39;file&#39;, file);</pre><pre>    const newRequest = new HttpRequest(&#39;POST&#39;, &#39;http://localhost:8080/uploadFile&#39;, data, {</pre><pre>      reportProgress: true,<br>      responseType: &#39;text&#39;</pre><pre>    });<br>    return this.https.request(newRequest);<br>  }</pre><pre>}</pre><p>As it is done, we need to import the service we created to the <em>app.component.ts</em> file and add few more methods to upload files with the help of the service, view files, and also to delete files.</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { UploadFileService } from &#39;./Services/upload-file.service&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;</pre><pre>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.scss&#39;]<br>})</pre><pre>export class AppComponent {</pre><pre>  selectedFiles: FileList;</pre><pre>  currentFileUpload: File;</pre><pre>  progress: { percentage: number } = { percentage: 0 };</pre><pre>  selectedFile = null;</pre><pre>  changeImage = false;</pre><pre>  file:string;</pre><pre>  constructor(private uploadService: UploadFileService, private https:HttpClient){}</pre><pre>  viewFile(){</pre><pre>window.open(&#39;https://bucketName.s3.cloudLocation.amazonaws.com/&#39;+this.file);</pre><pre>  }</pre><pre>  deleteFile()<br>  {<br>    this.https.post&lt;string&gt;(&#39;http://localhost:8080/deleteFile&#39;,this.file).subscribe(<br>      res =&gt; {<br>        this.file = res;<br>      }<br>    );<br>  }</pre><pre>  change(event) {<br>    this.changeImage = true;<br>  }</pre><pre>  changedImage(event) {<br>    this.selectedFile = event.target.files[0];<br>  }</pre><pre>  upload() {<br>    this.progress.percentage = 0;<br>    this.currentFileUpload = this.selectedFiles.item(0);</pre><pre>this.uploadService.pushFileToStorage(this.currentFileUpload).subscribe(event =&gt; {<br>      this.selectedFiles = undefined;<br>    });<br>  }</pre><pre>  selectFile(event) {<br>    this.selectedFiles = event.target.files;<br>  }</pre><pre>}</pre><p>It is important to make sure that all the imports which are mentioned at the beginning of the component.ts files are present in the project node modules folder. If not they must be installed as below.</p><pre>npm install imported_file_name</pre><p>With that, we have completed our front-end interface and its functionalities.</p><p>Now we need to create an Amazon Web Service(AWS) account and get the S3 service. The below link will get you to the AWS account creation page.</p><p><a href="https://portal.aws.amazon.com/billing/signup#/start">AWS Console - Signup</a></p><p>Even though your card details will be taken you will not be charged as you will be getting a free period to try their services. After creating the account you will be able to see the services that they provide. Under Storage Services you will be able to select ‘S3’. That would lead you to the buckets that you have. As this is a new account there will be none. So let us now create a bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qrxi4eW9BLx0L0dAp0FzMQ.png" /><figcaption>Screenshot by Author</figcaption></figure><p>First, you need to select the option ‘Create Bucket’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZMxb3LwIugYxOqJMcmMSfA.png" /><figcaption>Screenshot by Author</figcaption></figure><p>The bucket creation process will have 4 sections. In the first section, you need to give a name to your bucket and then select the region. When selecting the region it is better to select a region that is close to you. But that is not a must.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*thRIH23nOkYTTo1yrR7dfg.png" /><figcaption>Screenshot by Author</figcaption></figure><p>You can just skip the next section by clicking the button on your right-hand side bottom of the pop-up window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2nGW0jCCOZIXW1WM67-sCg.png" /><figcaption>Screenshot by Author</figcaption></figure><p>The 3rd section is important as it will set permissions to our bucket. So check the boxes as per below and click next. This setting can be changed anytime after creating the bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7meap62buEeMe1u8hNmaMQ.png" /><figcaption>Screenshot by Author</figcaption></figure><p>Then the last section will show you an overall review of the bucket that you are about to create. So now you can click the option ‘Create Bucket’.</p><p>Now go back to the services and select the option ‘IAM’ under ‘Security, Identity &amp; Compliance’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lw2pSWKHOtogd1wzZu_ZcA.png" /><figcaption>Screenshot by Author</figcaption></figure><p>There you will see the option ‘add user’. Select that option. In the popped up window, you need to give a user name and select access type as programmatic access. Now click ‘Next’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*do0C0UTA7s23NucsIWtnCw.png" /><figcaption>Screenshot by Author</figcaption></figure><p>Then select the option ‘Attach existing policies directly’ and type ‘S3’ in the search box. From the search results select ‘AmazonS3FullAccess’ and click next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8TPryuolagk485EssWT9Cg.png" /><figcaption>Screenshot by Author</figcaption></figure><p>You can now skip the ‘Add tags section’. Then it will show a review of the user that you are about to create. You can click Next again and then you will get the ‘Access Key ID’ and the ‘Secret Access Key’. Open a notepad file and keep them copied.</p><p>We are all set to start implementing our back-end. We can create our Spring Boot project easily from the below link.</p><p><a href="https://start.spring.io/">Spring Initializr</a></p><p>Then we need to add the below dependencies to our<em> pom.xml</em> file.</p><pre>&lt;dependencies&gt;<br>   &lt;dependency&gt;<br>      &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>      &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>   &lt;/dependency&gt;<br><br>   &lt;dependency&gt;<br>      &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>      &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>      &lt;scope&gt;test&lt;/scope&gt;<br>   &lt;/dependency&gt;<br><br>   &lt;dependency&gt;<br>      &lt;groupId&gt;com.amazonaws&lt;/groupId&gt;<br>      &lt;artifactId&gt;aws-java-sdk&lt;/artifactId&gt;<br>      &lt;version&gt;1.11.133&lt;/version&gt;<br>   &lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><p>Let us add the credentials of our S3 bucket which we previously copied to a notepad file, to the <em>application.properties</em> file now.</p><pre>endpointUrl = https://s3.cloudLocation.amazonaws.com<br>accessKey = accesskey<br>secretKey = secretkey<br>bucketName = bucketname</pre><p>It is time to create our service class to work with Amazon S3. In the service class, we need to implement methods to establish a connection with the S3 bucket, to convert the multipart file to a file, to upload that file, and to delete a file.</p><pre>import com.amazonaws.auth.AWSCredentials;<br>import com.amazonaws.auth.BasicAWSCredentials;<br>import com.amazonaws.services.s3.AmazonS3;<br>import com.amazonaws.services.s3.AmazonS3Client;<br>import com.amazonaws.services.s3.model.CannedAccessControlList;<br>import com.amazonaws.services.s3.model.DeleteObjectRequest;<br>import com.amazonaws.services.s3.model.PutObjectRequest;<br>import org.springframework.beans.factory.annotation.Value;<br>import org.springframework.stereotype.Service;<br>import org.springframework.web.multipart.MultipartFile;<br><br>import javax.annotation.PostConstruct;<br>import java.io.File;<br>import java.io.FileOutputStream;<br>import java.io.IOException;<br><br>@Service<br>public class AmazonS3BucketService {<br><br>    private AmazonS3 amazonS3;<br><br>    @Value(&quot;${endpointUrl}&quot;)<br>    private String endpointUrl;<br>    @Value(&quot;${bucketName}&quot;)<br>    private String bucketName;<br>    @Value(&quot;${accessKey}&quot;)<br>    private String accessKey;<br>    @Value(&quot;${secretKey}&quot;)<br>    private String secretKey;<br><br>    @PostConstruct<br>    private void initializeAmazon() {<br>        AWSCredentials credentials = new BasicAWSCredentials(this.accessKey, this.secretKey);<br>        this.amazonS3 = new AmazonS3Client(credentials);<br>    }<br><br>    public String uploadFile(MultipartFile multipartFile) {<br>        String fileURL = &quot;&quot;;<br>        try {<br>            File file = convertMultipartFileToFile(multipartFile);<br>            String fileName = multipartFile.getOriginalFilename();<br>            fileURL = endpointUrl + &quot;/&quot; + bucketName + &quot;/&quot; + fileName;<br>            uploadFileToBucket(fileName, file);<br>            file.delete();<br>        } catch (Exception e) {<br>            e.printStackTrace();<br>        }<br>        return fileURL;<br>    }<br><br>    private File convertMultipartFileToFile(MultipartFile file) throws IOException {<br>        File convertedFile = new File(file.getOriginalFilename());<br>        FileOutputStream fos = new FileOutputStream(convertedFile);<br>        fos.write(file.getBytes());<br>        fos.close();<br>        return convertedFile;<br>    }<br><br>    private void uploadFileToBucket(String fileName, File file) {<br>        amazonS3.putObject(new PutObjectRequest(bucketName, fileName, file)<br>                .withCannedAcl(CannedAccessControlList.<em>PublicRead</em>));<br>    }<br><br>    public String deleteFileFromBucket(String fileName) {<br>        amazonS3.deleteObject(new DeleteObjectRequest(bucketName, fileName));<br>        return &quot;Deletion Successful&quot;;<br>    }<br><br>}</pre><p>Now we need to create the controller class that would communicate with the front-end and uses the service class that we created before to carry out the requests which are being directed by the front-end.</p><pre>import com.s3.fileupload.Service.AmazonS3BucketService;<br>import org.springframework.stereotype.Controller;<br>import org.springframework.web.bind.annotation.*;<br>import org.springframework.web.multipart.MultipartFile;<br><br>@CrossOrigin(origins = &quot;http://localhost:4200&quot;)<br>@Controller<br>public class S3BucketController {<br><br>    private AmazonS3BucketService amazonS3BucketService;<br><br>    S3BucketController(AmazonS3BucketService amazonS3BucketService) {<br>        this.amazonS3BucketService = amazonS3BucketService;<br>    }<br><br>    @PostMapping(&quot;/uploadFile&quot;)<br>    public String uploadFile(@RequestPart(value = &quot;file&quot;) MultipartFile file) {<br>        return this.amazonS3BucketService.uploadFile(file);<br>    }<br><br>    @PostMapping(&quot;/deleteFile&quot;)<br>    public String deleteFile(@RequestBody String fileURL) {<br>        return this.amazonS3BucketService.deleteFileFromBucket(fileURL);<br>    }<br>}</pre><p>With that, we have come to the end of our implementation. Now it is time to test. Try uploading files and see whether they are being saved in the bucket. Also, try to view and delete files by giving the file name along with their file extensions and see whether the functionalities work properly.</p><p>I hope it is all clear and your project is working perfectly...</p><p>So you can use this amazing Amazon service whenever you need to store data in your projects. It is really efficient and easy to implement as well.</p><p>The project source code can be viewed and downloaded from <a href="https://github.com/ChinthakaJ98/AWS-S3-FileManagement">GitHub</a>.</p><p>Cheers!! Have a pleasant day!!</p><p>Visit my <a href="http://chinthakajayatilake.tech/">Official Blog Site</a> to send in your queries directly to me and to read more articles by me….</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=325b118e7188" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linkit-intecs/upload-and-view-files-in-amazon-s3-using-angular-spring-boot-325b118e7188">Upload and View Files in Amazon S3 using Angular + Spring Boot</a> was originally published in <a href="https://medium.com/linkit-intecs">LinkIT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Upload and View Files in Firebase Storage using Angular + Firebase Realtime Database]]></title>
            <link>https://medium.com/linkit-intecs/upload-and-view-files-in-firebase-storage-using-angular-firebase-realtime-database-b7da8bdfb20a?source=rss-1b3554b6fdf8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7da8bdfb20a</guid>
            <category><![CDATA[firebase-storage]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[firebaserealtimedatabase]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Chinthaka Jayatilake]]></dc:creator>
            <pubDate>Thu, 10 Oct 2019 09:37:46 GMT</pubDate>
            <atom:updated>2020-05-30T18:23:30.599Z</atom:updated>
            <content:encoded><![CDATA[<h3>Upload and View Files in Firebase Storage using Angular + Firebase Real-time Database</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*-4HcnjATJABqmW9CNd0uhQ.jpeg" /><figcaption>Photo by Mitchell Luo on Unsplash</figcaption></figure><p>Firebase is a comprehensive app development platform. It helps us to build apps with more efficiency and quality. It can work as a back-end to our application where we can run our services. It also has Firebase extensions from which you can deploy functionalities to your app using pre-packaged solutions. With all this, Firebase is a stand out among current technologies.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FiosNuIdQoy8%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DiosNuIdQoy8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FiosNuIdQoy8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9133dd3369bdbd1422a24caa7191a725/href">https://medium.com/media/9133dd3369bdbd1422a24caa7191a725/href</a></iframe><p>If you are interested in knowing more about Firebase, click the following link to be directed to the Firebase official site where you could enhance your knowledge and awareness regarding it.</p><p><a href="https://firebase.google.com/">Firebase | Google&#39;s Mobile and Web App Development Platform</a></p><p>It is now time for us to create our Firebase project. In the above link, you will find the option ‘Get Started’. With your google account credentials, you will be able to maintain your Firebase account. So once you get to the Firebase console select the option ‘Add Project’.</p><p>Creating a project is a 3 step process. In the 1st step, you need to give a project name. In the 2nd step, it will ask whether we need to add Google analytics to our project. For the moment we can say ‘No’ as this is a sample project. But you can use Google analytics in your future projects. If we do not add Google analytics the 3rd step will be automatically skipped as in the 3rd step we need to give the email account where we need the Google analytics updated. Now we have created our Firebase project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*se7lTKjp7sRDzE-ZdMkB6Q.png" /><figcaption>Screenshot by Author</figcaption></figure><p>Now we can select the option ‘Web’ to create a web app. Then we need to give the app a name.. With that, we have created our web app as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NQetKwvKQfsUGfo5-t11uQ.png" /><figcaption>Screenshot by Author</figcaption></figure><p>On your left sidebar, you will find the option ‘Database’. On the initial click, they will ask about the database rules. For the moment we will select the option ‘Test Mode’. This will allow access to public read and write. But after finished developing, we can change the rules. So, for now, it is not something to worry about.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*6yXRejvu2DBlbfB4u6oJ8w.png" /><figcaption>Screenshot by Author</figcaption></figure><p>Now from the top, you need to select the option ‘Realtime Database’. Then you can find the tab ‘Rules’. Once you go to that tab your rules must be as below. If not, change it to be as below and publish the changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kxAEmYm0-dXfkEKD1pqDmA.png" /><figcaption>Screenshot by Author</figcaption></figure><p>Next is to create our storage. For that select ‘Storage’ from the left sidebar. At the initial selection, you will be asked to get started and in the 1st step you can select ‘Next’. In the 2nd step, you need to set the cloud storage location. With that, you will get your storage. Then go to the tab ‘Rules’ in it and do the below changes. Once it is done publish the changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*YpQKImSA505UrpgrWcsKiA.png" /><figcaption>Screenshot by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*oECeVMHbRw5abjl7xEajqw.png" /><figcaption>Screenshot by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*BKXZREA5Fs2dqGEDeD1GpA.png" /><figcaption>Screenshot by Author</figcaption></figure><p>Now you need to move to the project settings and at the bottom of it, you will find the firebaseConfig within script tags. Copy that to a notepad file.</p><p>Now it is time to create the Angular project. Please follow the steps in the below link which shows how to install and setup Firebase in your angular project. When following the steps at one stage you will need the code snippet that we have already copied to a notepad file. So use it at the correct step.</p><p><a href="https://github.com/angular/angularfire2/blob/master/docs/install-and-setup.md">angular/angularfire2</a></p><p>Now we could proceed with further implementations. Let us create a basic HTML page to upload and view files. So it is time to move to the app.component.html file.</p><pre>&lt;h2&gt;File Upload&lt;/h2&gt;</pre><pre>&lt;input type=&quot;text&quot; placeholder=&quot;Save with Key&quot; name=&quot;id&quot; [(ngModel)]=&quot;id&quot;&gt;<br>&lt;br&gt;&lt;br&gt;<br>&lt;input type=&quot;file&quot; (change)=&quot;showPreview($event)&quot;&gt;<br>&lt;button (click)=&quot;save()&quot;&gt;Save&lt;/button&gt;</pre><pre>&lt;h2&gt;File View&lt;/h2&gt;</pre><pre>&lt;input type=&quot;text&quot; name=&quot;file&quot; [(ngModel)]=&quot;file&quot; placeholder=&quot;Enter Unique Search Key&quot;&gt;<br>&lt;button (click)=&quot;view()&quot;&gt;View&lt;/button&gt;</pre><p>We need to create a service to get records from the realtime database and also to add records to it. This could even be done in our <em>app.component.ts</em> file. But that is not the best practice as then we need to write the same code lines over and over again. It is always better to create a service and import it to the component.ts files when required.</p><pre>import { Injectable, Inject } from &#39;@angular/core&#39;;<br>import { AngularFireList, AngularFireDatabase } from &#39;@angular/fire/database&#39;;</pre><pre>@Injectable({<br>  providedIn: &#39;root&#39;<br>})</pre><pre>export class FileService {</pre><pre>  imageDetailList: AngularFireList&lt;any&gt;;</pre><pre>  fileList: any[];</pre><pre>  dataSet: Data = {<br>    id:&#39;&#39;,<br>    url:&#39;&#39;<br>  };</pre><pre>  msg:string = &#39;error&#39;;</pre><pre>  constructor(@Inject(AngularFireDatabase) private firebase: AngularFireDatabase) { }</pre><pre>  getImageDetailList() {<br>    this.imageDetailList = this.firebase.list(&#39;imageDetails&#39;);<br>  }</pre><pre>  insertImageDetails(id,url) {</pre><pre>    this.dataSet = {<br>      id : id,<br>      url: url<br>    };<br>    this.imageDetailList.push(this.dataSet);</pre><pre>  }</pre><pre>  getImage(value){<br>    this.imageDetailList.snapshotChanges().subscribe(<br>      list =&gt; {<br>        this.fileList = list.map(item =&gt; { return item.payload.val();  });<br>        this.fileList.forEach(element =&gt; {<br>          if(element.id===value)<br>          this.msg = element.url;<br>        });</pre><pre>        if(this.msg===&#39;error&#39;)<br>          alert(&#39;No record found&#39;);<br>        else{<br>          window.open(this.msg);<br>          this.msg = &#39;error&#39;;<br>        }<br>      }<br>    );</pre><pre>  }<br>}</pre><pre>export interface Data{<br>  id:string;<br>  url:string;<br>}</pre><p>We have reached the last step, which is to implement the <em>app.component.ts </em>file. Here we will be importing the service that we created above and we will be implementing methods to get data from the HTML page and to provide the requested functionalities with the help of the imported service.</p><pre>import { Component, Inject } from &#39;@angular/core&#39;;<br>import { AngularFireStorage } from &#39;@angular/fire/storage&#39;;<br>import { finalize } from &quot;rxjs/operators&quot;;<br>import { FileService } from &#39;./Services/file.service&#39;;</pre><pre>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.scss&#39;]<br>})</pre><pre>export class AppComponent{</pre><pre>  selectedImage: any = null;</pre><pre>  url:string;</pre><pre>  id:string;</pre><pre>  file:string;</pre><pre>  constructor( @Inject(AngularFireStorage) private storage: AngularFireStorage, @Inject(FileService) private fileService: FileService) { }</pre><pre>  ngOnInit() {<br>    this.fileService.getImageDetailList();<br>  }</pre><pre>  showPreview(event: any) {<br>    this.selectedImage = event.target.files[0];<br>  }</pre><pre>  save() {</pre><pre>    var name = this.selectedImage.name;<br>    const fileRef = this.storage.ref(name);</pre><pre>    this.storage.upload(name, this.selectedImage).snapshotChanges().pipe(<br>      finalize(() =&gt; {<br>        fileRef.getDownloadURL().subscribe((url) =&gt; {<br>          this.url = url;<br>          this.fileService.insertImageDetails(this.id,this.url);<br>          alert(&#39;Upload Successful&#39;);<br>        })<br>      })<br>    ).subscribe();<br>  }<br></pre><pre>  view(){<br>    this.fileService.getImage(this.file);<br>  }</pre><pre>}</pre><p>It is important to make sure that all the imports which are mentioned at the beginning of the component.ts files are present in the project node modules folder. If not they must be installed as below.</p><pre>npm install imported_file_name</pre><p>That is it. The end of the implementation process. Let us try to work with this simple project now. Upload an image and check in the Firebase Realtime database whether a record has been inserted and check the Firebase storage whether the file is added. Next is to enter the ID and try to view the image.</p><p>I hope it works for you. This is just a simple project to show how these things work. But with the help of this, you could add Firebase storage in your future projects and implement it further according to your project requirements.</p><p>You can view and download the project source code from <a href="https://github.com/ChinthakaJ98/Firebase-Storage-Realtime-Database">GitHub</a>.</p><p>Cheers!! Have a pleasant day!!</p><p>Visit my <a href="http://chinthakajayatilake.tech/">Official Blog Site</a> to send in your queries directly to me and to read more articles by me…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7da8bdfb20a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linkit-intecs/upload-and-view-files-in-firebase-storage-using-angular-firebase-realtime-database-b7da8bdfb20a">Upload and View Files in Firebase Storage using Angular + Firebase Realtime Database</a> was originally published in <a href="https://medium.com/linkit-intecs">LinkIT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create PDF using Angular 6 + Spring Boot + Thymeleaf]]></title>
            <link>https://medium.com/linkit-intecs/create-pdf-using-angular-6-spring-boot-thymeleaf-b94cd85c69dd?source=rss-1b3554b6fdf8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b94cd85c69dd</guid>
            <category><![CDATA[thymeleaf]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Chinthaka Jayatilake]]></dc:creator>
            <pubDate>Tue, 08 Oct 2019 18:29:08 GMT</pubDate>
            <atom:updated>2020-05-30T18:20:34.754Z</atom:updated>
            <content:encoded><![CDATA[<h3>Create PDF using Angular + Spring Boot + Thymeleaf</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*qA4Z0MobxJKKuqoZAkxjxA.jpeg" /><figcaption>Photo by J-S Romeo on Unsplash</figcaption></figure><p>Angular and Spring Boot have become popular among developers because of the ease of programming and the efficiency that they have. Today we will be looking at how we could simply create a PDF using these two technologies which would be really helpful as this could be integrated into any project where a software requirement is there to create a PDF.</p><p>Here we will be having an Angular front-end from which we will be collecting data using a simple form and along with it a Spring Boot back-end to create the PDF.</p><p>Lets first start with the Angular project. Use the below command to create a new project.</p><pre>ng new project_name</pre><p>It is time to create the HTML form to collect data. So let us move to the app.component.html file.</p><pre>&lt;h1&gt;Enter the following details&lt;/h1&gt;</pre><pre>&lt;table&gt;</pre><pre> &lt;tr&gt;<br>  &lt;td&gt;&lt;span&gt;Name&lt;/span&gt;&lt;/td&gt;<br>  &lt;td&gt;&lt;input type=&quot;text&quot; [(ngModel)]=&quot;dataset.name&quot; name=&quot;name&quot;&gt; &lt;/td&gt;<br> &lt;/tr&gt;<br> &lt;tr&gt;<br>  &lt;td&gt;&lt;span&gt;Age(Integer)&lt;/span&gt;&lt;/td&gt;<br>  &lt;td&gt;&lt;input type=&quot;number&quot; [(ngModel)]=&quot;dataset.age&quot; name=&quot;age&quot;&gt;&lt;/td&gt;<br> &lt;/tr&gt;<br> &lt;tr&gt;<br>  &lt;td&gt;&lt;span&gt;Country&lt;/span&gt;&lt;/td&gt;<br>  &lt;td&gt;&lt;input type=&quot;text&quot; [(ngModel)]=&quot;dataset.country&quot; name=&quot;country&quot;&gt;&lt;/td&gt;<br> &lt;/tr&gt;<br> &lt;tr&gt;<br>  &lt;td&gt;&lt;/td&gt;<br>  &lt;td&gt;&lt;button (click)=&quot;onSubmit()&quot;&gt;Submit&lt;/button&gt;&lt;/td&gt;<br> &lt;/tr&gt;</pre><pre>&lt;/table&gt;</pre><p>Next we need to edit the <em>app.component.ts</em> file to send the collected data to the back-end. We will be using the HttpClient to communicate with the Spring Boot back-end.</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;</pre><pre>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.css&#39;]<br>})</pre><pre>export class AppComponent {</pre><pre>  title = &#39;CreatePDF&#39;;</pre><pre>  dataset: Details = {<br>    name:&#39;&#39;,<br>    age:null,<br>    country:&#39;&#39;<br>  };</pre><pre>  constructor(private https: HttpClient) { }</pre><pre>  onSubmit()<br>  {<br>    this.https.post&lt;Details&gt;(&#39;http://localhost:8080/testapp/getdetails&#39;, this.dataset).subscribe(<br>      res =&gt; {<br>        this.dataset = res;<br>        alert(&#39;PDF created successfully&#39;);<br>        this.dataset.age = null;<br>        this.dataset.name = &#39;&#39;;<br>        this.dataset.country = &#39;&#39;;<br>      });<br>  }<br>}</pre><pre>interface Details<br>{<br>  name:string;<br>  age:number;<br>  country:string;<br>}</pre><p>It is important to make sure that all the imports which are mentioned at the beginning of the <em>component.ts</em> files are present in the project node modules folder. If not they must be installed as below.</p><pre>npm install imported_file_name</pre><p>Now let us move to the Spring Boot project. You can create a Spring Boot project easily by using the below link.</p><p><a href="https://start.spring.io/">Spring Initializr</a></p><p>First we need to edit our <em>pom.xml</em> file in order to import the dependencies that we will be needing in the project.</p><pre>&lt;dependencies&gt;<br>   &lt;dependency&gt;<br>      &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>      &lt;artifactId&gt;spring-boot-starter&lt;/artifactId&gt;<br>   &lt;/dependency&gt;<br><br>   &lt;dependency&gt;<br>      &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>      &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>      &lt;scope&gt;test&lt;/scope&gt;<br>   &lt;/dependency&gt;<br><br>   &lt;dependency&gt;<br>      &lt;groupId&gt;org.thymeleaf&lt;/groupId&gt;<br>      &lt;artifactId&gt;thymeleaf-spring4&lt;/artifactId&gt;<br>      &lt;version&gt;2.1.5.RELEASE&lt;/version&gt;<br>   &lt;/dependency&gt;<br><br>   &lt;dependency&gt;<br>      &lt;groupId&gt;org.thymeleaf&lt;/groupId&gt;<br>      &lt;artifactId&gt;thymeleaf&lt;/artifactId&gt;<br>      &lt;version&gt;2.1.5.RELEASE&lt;/version&gt;<br>   &lt;/dependency&gt;<br><br>   &lt;dependency&gt;<br>      &lt;groupId&gt;nz.net.ultraq.thymeleaf&lt;/groupId&gt;<br>      &lt;artifactId&gt;thymeleaf-layout-dialect&lt;/artifactId&gt;<br>      &lt;version&gt;2.1.2&lt;/version&gt;<br>   &lt;/dependency&gt;<br><br>   &lt;dependency&gt;<br>      &lt;groupId&gt;org.xhtmlrenderer&lt;/groupId&gt;<br>      &lt;artifactId&gt;flying-saucer-pdf-itext5&lt;/artifactId&gt;<br>      &lt;version&gt;9.1.6&lt;/version&gt;<br>      &lt;scope&gt;compile&lt;/scope&gt;<br>   &lt;/dependency&gt;<br><br>   &lt;dependency&gt;<br>      &lt;groupId&gt;net.sf.jtidy&lt;/groupId&gt;<br>      &lt;artifactId&gt;jtidy&lt;/artifactId&gt;<br>      &lt;version&gt;r938&lt;/version&gt;<br>      &lt;scope&gt;compile&lt;/scope&gt;<br>   &lt;/dependency&gt;<br><br>   &lt;dependency&gt;<br>      &lt;groupId&gt;org.xhtmlrenderer&lt;/groupId&gt;<br>      &lt;artifactId&gt;flying-saucer-core&lt;/artifactId&gt;<br>      &lt;version&gt;9.1.6&lt;/version&gt;<br>      &lt;scope&gt;compile&lt;/scope&gt;<br>   &lt;/dependency&gt;<br>   <br>   &lt;dependency&gt;<br>      &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>      &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>   &lt;/dependency&gt;<br><br>&lt;/dependencies&gt;</pre><p>Second we need to create a class for us to take the data passed by the Angular front-end to the Spring Boot back-end.</p><pre>public class Details {<br><br>    private String name;<br><br>    private int age;<br><br>    private String country;<br><br>    public String getName() {<br>        return name;<br>    }<br><br>    public void setName(String name) {<br>        this.name = name;<br>    }<br><br>    public int getAge() {<br>        return age;<br>    }<br><br>    public void setAge(int age) {<br>        this.age = age;<br>    }<br><br>    public String getCountry() {<br>        return country;<br>    }<br><br>    public void setCountry(String country) {<br>        this.country = country;<br>    }<br>}</pre><p>Now we need to create the controller class to get the data from the front-end, pass that data to the pdf-templates and also to initialize the pdf-templates.</p><pre>import com.blog.example.CreatePDF.dto.Details;<br>import com.itextpdf.text.DocumentException;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.stereotype.Controller;<br>import org.springframework.web.bind.annotation.RequestBody;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import org.springframework.web.bind.annotation.ResponseBody;<br>import org.thymeleaf.context.Context;<br>import org.thymeleaf.spring4.SpringTemplateEngine;<br>import org.w3c.tidy.Tidy;<br>import org.xhtmlrenderer.pdf.ITextRenderer;<br><br>import java.io.*;<br>import java.nio.file.FileSystems;<br><br>@RequestMapping(&quot;/testapp&quot;)<br>@Controller<br>public class PDFCreator {<br><br>    @Autowired<br>    SpringTemplateEngine templateEngine;<br><br>    @RequestMapping(&quot;/getdetails&quot;)<br>    public @ResponseBody Details savePDF(@RequestBody Details details) throws IOException, DocumentException {<br>        Context context = new Context();<br><br>        context.setVariable(&quot;name&quot;,details.getName());<br>        context.setVariable(&quot;age&quot;,details.getAge());<br>        context.setVariable(&quot;country&quot;,details.getCountry());<br><br>        String htmlContentToRender = templateEngine.process(&quot;pdf-template&quot;, context);<br>        String xHtml = xhtmlConvert(htmlContentToRender);<br><br>        ITextRenderer renderer = new ITextRenderer();<br><br>        String baseUrl = FileSystems<br>                .<em>getDefault</em>()<br>                .getPath(&quot;src&quot;, &quot;main&quot;, &quot;resources&quot;,&quot;templates&quot;)<br>                .toUri()<br>                .toURL()<br>                .toString();<br>        renderer.setDocumentFromString(xHtml, baseUrl);<br>        renderer.layout();<br><br>        OutputStream outputStream = new FileOutputStream(&quot;src//test.pdf&quot;);<br>        renderer.createPDF(outputStream);<br>        outputStream.close();<br><br>        return details;<br><br>    }<br><br>    private String xhtmlConvert(String html) throws UnsupportedEncodingException {<br>        Tidy tidy = new Tidy();<br>        tidy.setInputEncoding(&quot;UTF-8&quot;);<br>        tidy.setOutputEncoding(&quot;UTF-8&quot;);<br>        tidy.setXHTML(true);<br>        ByteArrayInputStream inputStream = new ByteArrayInputStream(html.getBytes(&quot;UTF-8&quot;));<br>        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();<br>        tidy.parseDOM(inputStream, outputStream);<br>        return outputStream.toString(&quot;UTF-8&quot;);<br>    }<br>}</pre><p>We will be using Thymeleaf to configure the pdf-templates. Let us now create the configuration class to configure the SpringTemplateEngine and the SpringResourceTemplateResolver.</p><pre>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.thymeleaf.spring4.SpringTemplateEngine;<br>import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver;<br>import org.thymeleaf.templatemode.StandardTemplateModeHandlers;<br><br>import java.nio.charset.StandardCharsets;<br><br>@Configuration<br>public class PDFThymeleafConfiguration {<br><br><br>    @Bean<br>    public SpringTemplateEngine springTemplateEngine() {<br>        SpringTemplateEngine templateEngine = new SpringTemplateEngine();<br>        templateEngine.addTemplateResolver(htmlTemplateResolver());<br>        return templateEngine;<br>    }<br><br>    @Bean<br>    public SpringResourceTemplateResolver htmlTemplateResolver() {<br>        SpringResourceTemplateResolver pdfTemplateResolver = new SpringResourceTemplateResolver();<br>        pdfTemplateResolver.setPrefix(&quot;classpath:/templates/&quot;);<br>        pdfTemplateResolver.setSuffix(&quot;.html&quot;);<br>        pdfTemplateResolver.setTemplateMode(StandardTemplateModeHandlers.<em>HTML5</em>.getTemplateModeName());<br>        pdfTemplateResolver.setCharacterEncoding(StandardCharsets.<em>UTF_8</em>.name());<br>        return pdfTemplateResolver;<br>    }<br>}</pre><p>Next we need to design the PDF view using HTML syntax in the Spring Boot project.</p><pre>&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;<br>&lt;html xmlns:th=&quot;http://www.thymeleaf.org&quot; xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;<br><br>&lt;head&gt;<br>    &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot; /&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;/&gt;<br>    &lt;title&gt;Template&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br><br>&lt;h1&gt;This is just a sample html page&lt;/h1&gt;<br><br>&lt;h2&gt;Below are the details that were passed to the html page&lt;/h2&gt;<br><br>&lt;p th:text=&quot;${&#39;Name    : &#39; + name}&quot;&gt;&lt;/p&gt;<br>&lt;p th:text=&quot;${&#39;Age     :&#39; + age}&quot;&gt;&lt;/p&gt;<br>&lt;p th:text=&quot;${&#39;Country : &#39; + country}&quot;&gt;&lt;/p&gt;<br><br>&lt;p&gt;&lt;b&gt;You can create the page the way you wish to have your PDF file using HTML tags&lt;/b&gt;&lt;/p&gt;<br><br>&lt;p&gt;&lt;b&gt;Bootstrap can be added to design. Images can be added. All according to your preference&lt;/b&gt;&lt;/p&gt;<br><br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>With that we have reached the end of our implementation and now you can try to work with it. Not just that, feel free to use it in your software when required.</p><p>Hope this could help!! The project source code can be downloaded from <a href="https://github.com/ChinthakaJ98/PDF-Create.git">GitHub</a>.</p><p>Cheers!! Have a pleasant day!!</p><p>Visit my <a href="http://chinthakajayatilake.tech/">Official Blog Site</a> to send in your queries directly to me and to read more articles by me….</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b94cd85c69dd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linkit-intecs/create-pdf-using-angular-6-spring-boot-thymeleaf-b94cd85c69dd">Create PDF using Angular 6 + Spring Boot + Thymeleaf</a> was originally published in <a href="https://medium.com/linkit-intecs">LinkIT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[File Upload & Download as Multipart File using Angular 6 + Spring Boot]]></title>
            <link>https://medium.com/linkit-intecs/file-upload-download-as-multipart-file-using-angular-6-spring-boot-7ad06d841c21?source=rss-1b3554b6fdf8------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ad06d841c21</guid>
            <category><![CDATA[multipartfile]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Chinthaka Jayatilake]]></dc:creator>
            <pubDate>Tue, 08 Oct 2019 18:27:18 GMT</pubDate>
            <atom:updated>2020-05-31T06:45:51.502Z</atom:updated>
            <content:encoded><![CDATA[<h3>File Upload &amp; Download as Multipart File using Angular + Spring Boot</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*Zyqo9ROBVaSTomTtGygTfQ.jpeg" /><figcaption>Photo by Clay Banks on Unsplash</figcaption></figure><p>We know that when creating applications in the present day, it has become a requirement in most of them to upload and download files. But we know that with the security features in the browsers it is not as simple as in the past to upload and download files. We also need to look at the efficiency of the process as it is a main non-functional requirement nowadays.</p><p>So let us now create our Angular project.</p><pre>ng new project_name</pre><p>Let us create a simple HTML form first to get the file input and to show the downloaded file. In order to code it, we will move to the <em>app.component.html </em>file.</p><pre>&lt;h1&gt;Upload and Download File&lt;/h1&gt;</pre><pre>&lt;input type=&quot;file&quot; id=&quot;customFile&quot; (change)=&quot;selectFile($event)&quot;&gt;</pre><pre>&lt;button class=&quot;btn btn-primary&quot; [disabled]=&quot;!selectedFiles || admincheck || status&quot; (click)=&quot;upload()&quot;&gt;Save File&lt;/button&gt;</pre><pre>&lt;button class=&quot;btn btn-primary&quot; style=&quot;margin-left: 10px&quot; (click)=&quot;downloadFile()&quot;&gt;View File&lt;/button&gt;</pre><p>Next, we need to create a service to send the file as a multipart file to the back-end. We will be using this service in our <em>app.component.ts</em> file to communicate with the back-end.</p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { HttpClient, HttpEvent, HttpRequest } from &#39;@angular/common/http&#39;;<br>import { Observable } from &#39;rxjs&#39;;</pre><pre>@Injectable({<br>providedIn: &#39;root&#39;})</pre><pre>export class UploadFileService {</pre><pre>  constructor(private https: HttpClient) { }</pre><pre>  pushFileToStorage(file: File): Observable&lt;HttpEvent&lt;{}&gt;&gt; {</pre><pre>    const data: FormData = new FormData();</pre><pre>    data.append(&#39;file&#39;, file);</pre><pre>    const newRequest = new HttpRequest(&#39;POST&#39;, &#39;http://localhost:8080/savefile&#39;, data, {<br>    reportProgress: true,<br>    responseType: &#39;text&#39;<br>    });</pre><pre>    return this.https.request(newRequest);</pre><pre>}}</pre><p>As the service is created now we can move to implement our <em>app.component.ts</em> file. Here we will be importing the service and with the use of it, we will be sending the file to the back-end. There are other few methods as well in the <em>app.component.ts </em>file to download the file, to check whether the selected file is the same and also to confirm whether a file has been selected.</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { HttpResponse, HttpEventType } from &#39;@angular/common/http&#39;;<br>import { UploadFileService } from &#39;./Services/upload-file.service&#39;;</pre><pre>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.css&#39;]<br>})</pre><pre>export class AppComponent {</pre><pre>  title = &#39;File-Upload-Save&#39;;</pre><pre>  selectedFiles: FileList;</pre><pre>  currentFileUpload: File;</pre><pre>  progress: { percentage: number } = { percentage: 0 };</pre><pre>  selectedFile = null;</pre><pre>  changeImage = false;</pre><pre>  constructor(private uploadService: UploadFileService){}</pre><pre>  downloadFile(){</pre><pre>    const link = document.createElement(&#39;a&#39;);<br>    link.setAttribute(&#39;target&#39;, &#39;_blank&#39;);<br>    link.setAttribute(&#39;href&#39;, &#39;_File_Saved_Path&#39;);<br>    link.setAttribute(&#39;download&#39;, &#39;file_name.pdf&#39;);<br>    document.body.appendChild(link);<br>    link.click();<br>    link.remove();</pre><pre>  }</pre><pre>  change($event) {<br>    this.changeImage = true;<br>  }</pre><pre>  changedImage(event) {<br>    this.selectedFile = event.target.files[0];<br>  }</pre><pre>  upload() {</pre><pre>    this.progress.percentage = 0;<br>    this.currentFileUpload = this.selectedFiles.item(0);<br>this.uploadService.pushFileToStorage(this.currentFileUpload).subscribe(event =&gt; {<br>      if (event.type === HttpEventType.UploadProgress) {<br>        this.progress.percentage = Math.round(100 * event.loaded / event.total);<br>      } else if (event instanceof HttpResponse) {<br>         alert(&#39;File Successfully Uploaded&#39;);<br>      }<br>      this.selectedFiles = undefined;<br>     }<br>    );<br>  }</pre><pre>  selectFile(event) {<br>    this.selectedFiles = event.target.files;<br>  }<br>}</pre><p>It is important to make sure that all the imports which are mentioned at the beginning of the <em>component.ts</em> files are present in the project node modules folder. If not they must be installed as below.</p><pre>npm install imported_file_name</pre><p>Now let us create the Spring Boot project. The below link will help you create your project easily.</p><p><a href="https://start.spring.io/">Spring Initializr</a></p><p>Now let us add the below dependencies to our <em>pom.xml</em> file so that we could use them in our project by importing them.</p><pre>&lt;dependencies&gt;<br><br>   &lt;dependency&gt;<br>      &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>      &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>   &lt;/dependency&gt;<br><br>   &lt;dependency&gt;<br>      &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>      &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>      &lt;scope&gt;test&lt;/scope&gt;<br>   &lt;/dependency&gt;<br><br>&lt;/dependencies&gt;</pre><p>Now let us create a class and write the method to collect the multipart file passed from the front-end and to convert it back to the original file format and save it in a given location.</p><pre>import org.springframework.http.HttpStatus;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.stereotype.Controller;<br>import org.springframework.web.bind.annotation.*;<br>import org.springframework.web.multipart.MultipartFile;<br><br>import java.nio.file.Files;<br>import java.nio.file.Path;<br>import java.nio.file.Paths;<br>import java.util.ArrayList;<br>import java.util.List;<br><br>@CrossOrigin(origins = &quot;http://localhost:4200&quot;)<br>@Controller<br>public class FileUploader {<br><br>   List&lt;String&gt; files = new ArrayList&lt;String&gt;();<br>   private final Path rootLocation = Paths.<em>get</em>(&quot;_Path_To_Save_The_File&quot;);<br><br>   @PostMapping(&quot;/savefile&quot;)<br>   public ResponseEntity&lt;String&gt; handleFileUpload(@RequestParam(&quot;file&quot;) MultipartFile file) {<br>      String message;<br>      try {<br>         try {<br>            Files.<em>copy</em>(file.getInputStream(), this.rootLocation.resolve(&quot;file_name.pdf&quot;));<br>         } catch (Exception e) {<br>            throw new RuntimeException(&quot;FAIL!&quot;);<br>         }<br>         files.add(file.getOriginalFilename());<br><br>         message = &quot;Successfully uploaded!&quot;;<br>         return ResponseEntity.<em>status</em>(HttpStatus.<em>OK</em>).body(message);<br>      } catch (Exception e) {<br>         message = &quot;Failed to upload!&quot;;<br>         return ResponseEntity.<em>status</em>(HttpStatus.<em>EXPECTATION_FAILED</em>).body(message);<br>      }<br>   }<br>}</pre><p>So that is it. A very simple application to store and retrieve files. It can be created in a few minutes. Why wait now. Let us check whether this works.</p><p>Feel free to add this module to your project when required and even implement it further according to your requirements. I hope you got something out of this.</p><p>The project source code can be viewed and downloaded from <a href="https://github.com/ChinthakaJ98/File-Upload-Download">GitHub</a>.</p><p>Cheers!! Have a pleasant day!!</p><p>Visit my <a href="http://chinthakajayatilake.tech/">Official Blog Site</a> to send in your queries directly to me and to read more articles by me…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ad06d841c21" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linkit-intecs/file-upload-download-as-multipart-file-using-angular-6-spring-boot-7ad06d841c21">File Upload &amp; Download as Multipart File using Angular 6 + Spring Boot</a> was originally published in <a href="https://medium.com/linkit-intecs">LinkIT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Send Emails using Angular 6 + Spring Boot + Thymeleaf]]></title>
            <link>https://medium.com/linkit-intecs/send-emails-using-angular-6-spring-boot-thymeleaf-d44de0c6c27f?source=rss-1b3554b6fdf8------2</link>
            <guid isPermaLink="false">https://medium.com/p/d44de0c6c27f</guid>
            <category><![CDATA[thymeleaf]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Chinthaka Jayatilake]]></dc:creator>
            <pubDate>Tue, 08 Oct 2019 18:23:40 GMT</pubDate>
            <atom:updated>2020-05-30T18:19:26.335Z</atom:updated>
            <content:encoded><![CDATA[<h3>Send Emails using Angular + Spring Boot + Thymeleaf</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*zHfCGC1uOAD1j5_DGlpGWQ.jpeg" /><figcaption>Photo by Krsto Jevtic on Unsplash</figcaption></figure><p>Thymeleaf is a modern server-side Java template engine for both web and standalone environments. The main goal of it is to bring elegant natural templates to the development workflow. HTML templates are written in Thymeleaf look and work like HTML.</p><p>Here we will be having an Angular front-end from which we will be collecting data using a simple form and along with it a Spring Boot back-end to send the Email.</p><p>Lets first start with the Angular project. Use the below command to create a new project.</p><pre>ng new project_name</pre><p>Now we need to create the HTML form to collect data. So let us move to the <em>app.component.html</em> file.</p><pre>&lt;h1&gt;Enter the following details&lt;/h1&gt;</pre><pre>&lt;table&gt;</pre><pre>  &lt;tr&gt;<br>    &lt;td&gt;&lt;span&gt;Name&lt;/span&gt;&lt;/td&gt;<br>    &lt;td&gt;&lt;input type=&quot;text&quot; [(ngModel)]=&quot;dataset.name&quot; name=&quot;name&quot;&gt;&lt;/td&gt;<br>  &lt;/tr&gt;<br>  &lt;tr&gt;<br>    &lt;td&gt;&lt;span&gt;Age(Integer)&lt;/span&gt;&lt;/td&gt;<br>    &lt;td&gt;&lt;input type=&quot;number&quot; [(ngModel)]=&quot;dataset.age&quot; name=&quot;age&quot;&gt;&lt;/td&gt;&lt;/tr&gt;<br>  &lt;tr&gt;<br>    &lt;td&gt;&lt;span&gt;Country&lt;/span&gt;&lt;/td&gt;<br>    &lt;td&gt;&lt;input type=&quot;text&quot; [(ngModel)]=&quot;dataset.country&quot; name=&quot;country&quot;&gt;&lt;/td&gt;<br>  &lt;/tr&gt;<br>  &lt;tr&gt;<br>    &lt;td&gt;&lt;span&gt;Send Email to&lt;/span&gt;&lt;/td&gt;<br>    &lt;td&gt;&lt;input type=&quot;text&quot; [(ngModel)]=&quot;dataset.email&quot; name=&quot;email&quot;<br>    &lt;/td&gt;<br>  &lt;/tr&gt;</pre><pre>  &lt;tr&gt;<br>    &lt;td&gt;&lt;/td&gt;<br>    &lt;td&gt;&lt;button (click)=&quot;onSubmit()&quot;&gt;Submit&lt;/button&gt;&lt;/td&gt;<br>  &lt;/tr&gt;</pre><pre>&lt;/table&gt;</pre><p>Next, we need to move to the <em>app.component.ts</em> file. Here we will be using the HttpClient to communicate with the Spring Boot back-end.</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;</pre><pre>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.css&#39;]<br>})</pre><pre>export class AppComponent {</pre><pre>  title = &#39;EmailTemplate&#39;;</pre><pre>  dataset: Details = {<br>    name:&#39;&#39;,<br>    age:null,<br>    country:&#39;&#39;,<br>    email:&#39;&#39;<br>  };</pre><pre>  constructor(private https: HttpClient){ }</pre><pre>  onSubmit(){</pre><pre>    this.https.post&lt;Details&gt;(&#39;http://localhost:8080/testapp/getdetails&#39;, this.dataset).subscribe(</pre><pre>        res =&gt; {<br>          this.dataset = res;<br>          console.log(this.dataset);<br>          alert(&#39;Email Sent successfully&#39;);<br>          this.dataset.age = null;<br>          this.dataset.name = &#39;&#39;;<br>          this.dataset.country = &#39;&#39;;<br>          this.dataset.email = &#39;&#39;;<br>        });</pre><pre>  }<br>}</pre><pre>interface Details{</pre><pre>  name:string;<br>  age:number;<br>  country:string;<br>  email:string;</pre><pre>}</pre><p>It is important to make sure that all the imports which are mentioned at the beginning of the <em>component.ts</em> files are present in the project node modules folder. If not they must be installed as below.</p><pre>npm install imported_file_name</pre><p>Now it is time to move to the Spring Boot project. You can create a Spring Boot project easily by using the below link.</p><p><a href="https://start.spring.io/">Spring Initializr</a></p><p>To start with we need to add the below dependencies to our <em>pom.xml</em> file as we need to import them to our project to work with them.</p><pre>&lt;dependencies&gt;<br><br>   &lt;dependency&gt;<br>      &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>      &lt;artifactId&gt;spring-boot-starter-mail&lt;/artifactId&gt;<br>   &lt;/dependency&gt;<br><br>   &lt;dependency&gt;<br>      &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>      &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>   &lt;/dependency&gt;<br><br>   &lt;dependency&gt;<br>      &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>      &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>      &lt;scope&gt;test&lt;/scope&gt;<br>   &lt;/dependency&gt;<br><br>   &lt;dependency&gt;<br>      &lt;groupId&gt;org.thymeleaf&lt;/groupId&gt;<br>      &lt;artifactId&gt;thymeleaf-spring4&lt;/artifactId&gt;<br>      &lt;version&gt;2.1.5.RELEASE&lt;/version&gt;<br>   &lt;/dependency&gt;<br><br>   &lt;dependency&gt;<br>      &lt;groupId&gt;org.thymeleaf&lt;/groupId&gt;<br>      &lt;artifactId&gt;thymeleaf&lt;/artifactId&gt;<br>      &lt;version&gt;2.1.5.RELEASE&lt;/version&gt;<br>   &lt;/dependency&gt;<br><br>   &lt;dependency&gt;<br>      &lt;groupId&gt;nz.net.ultraq.thymeleaf&lt;/groupId&gt;<br>      &lt;artifactId&gt;thymeleaf-layout-dialect&lt;/artifactId&gt;<br>      &lt;version&gt;2.1.2&lt;/version&gt;<br>   &lt;/dependency&gt;<br><br>&lt;/dependencies&gt;</pre><p>As we will be needing to send the emails through an email account, we need to enter the credentials, host, and port details to the application properties file. Here we will be using the SMTP protocol to send emails. So we need to configure that as well.</p><pre>spring.mail.host=smtp.gmail.com<br>spring.mail.port=587<br>#(above can be used for gmail)<br>spring.mail.username=_email_address_<br>spring.mail.password=_password_<br>spring.mail.properties.mail.smtp.starttls.enable=true<br>spring.mail.properties.mail.smtp.starttls.required=true<br>spring.mail.properties.mail.smtp.auth=true<br>spring.mail.properties.mail.smtp.connectiontimeout=5000<br>spring.mail.properties.mail.smtp.timeout=5000<br>spring.mail.properties.mail.smtp.writetimeout=5000</pre><p>Next is creating a class to get the variables in the front-end.</p><pre>public class Details {<br><br>    private String name;<br><br>    private int age;<br><br>    private String country;<br><br>    private String email;<br><br>    public String getEmail() {<br>        return email;<br>    }<br><br>    public void setEmail(String email) {<br>        this.email = email;<br>    }<br><br>    public String getName() {<br>        return name;<br>    }<br><br>    public void setName(String name) {<br>        this.name = name;<br>    }<br><br>    public int getAge() {<br>        return age;<br>    }<br><br>    public void setAge(int age) {<br>        this.age = age;<br>    }<br><br>    public String getCountry() {<br>        return country;<br>    }<br><br>    public void setCountry(String country) {<br>        this.country = country;<br>    }<br>}</pre><p>Now we need to configure the SpringTemplateEngine and the SpringResourceTemplateResolver as we will be needing them once we are working with Thymeleaf templates.</p><pre>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.thymeleaf.spring4.SpringTemplateEngine;<br>import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver;<br>import org.thymeleaf.templatemode.StandardTemplateModeHandlers;<br><br>import java.nio.charset.StandardCharsets;<br><br>@Configuration<br>public class EmailThymeleafConfiguration {<br><br><br>    @Bean<br>    public SpringTemplateEngine springTemplateEngine() {<br>        SpringTemplateEngine templateEngine = new SpringTemplateEngine();<br>        templateEngine.addTemplateResolver(htmlTemplateResolver());<br>        return templateEngine;<br>    }<br><br>    @Bean<br>    public SpringResourceTemplateResolver htmlTemplateResolver() {<br>        SpringResourceTemplateResolver pdfTemplateResolver = new SpringResourceTemplateResolver();<br>        pdfTemplateResolver.setPrefix(&quot;classpath:/templates/&quot;);<br>        pdfTemplateResolver.setSuffix(&quot;.html&quot;);<br>        pdfTemplateResolver.setTemplateMode(StandardTemplateModeHandlers.<em>HTML5</em>.getTemplateModeName());<br>        pdfTemplateResolver.setCharacterEncoding(StandardCharsets.<em>UTF_8</em>.name());<br>        return pdfTemplateResolver;<br>    }<br>}</pre><p>Now we can write our main few methods in the controller class to get the data from the front-end and to initialize the templates while passing the variables as parameters to them.</p><pre>import com.blog.example.EmailTemplate.dto.Details;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.mail.javamail.JavaMailSender;<br>import org.springframework.mail.javamail.MimeMessageHelper;<br>import org.springframework.stereotype.Controller;<br>import org.springframework.web.bind.annotation.RequestBody;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import org.springframework.web.bind.annotation.ResponseBody;<br>import org.thymeleaf.context.Context;<br>import org.thymeleaf.spring4.SpringTemplateEngine;<br>import javax.mail.internet.MimeMessage;<br>import java.nio.charset.StandardCharsets;<br>import java.util.HashMap;<br>import java.util.Map;<br><br>@RequestMapping(&quot;/testapp&quot;)<br>@Controller<br>public class EmailSender {<br><br>    @Autowired<br>    SpringTemplateEngine templateEngine;<br><br>    @Autowired<br>    private JavaMailSender sender;<br><br>    @RequestMapping(&quot;/getdetails&quot;)<br>    public @ResponseBody Details sendMail(@RequestBody Details details) throws Exception {<br><br>        MimeMessage message = sender.createMimeMessage();<br>        MimeMessageHelper helper = new MimeMessageHelper(message,<br>                MimeMessageHelper.<em>MULTIPART_MODE_MIXED_RELATED</em>,<br>                StandardCharsets.<em>UTF_8</em>.name());<br><br>        Map&lt;String, Object&gt; model = new HashMap&lt;String, Object&gt;();<br>        model.put(&quot;name&quot;,details.getName());<br>        model.put(&quot;age&quot;,details.getAge());<br>        model.put(&quot;country&quot;,details.getCountry());<br><br>        Context context = new Context();<br>        context.setVariables(model);<br>        String html = templateEngine.process(&quot;email-template&quot;, context);<br><br>        try {<br>            helper.setTo(details.getEmail());<br>            helper.setText(html,true);<br>            helper.setSubject(&quot;Test Mail&quot;);<br>        } catch (javax.mail.MessagingException e) {<br>            e.printStackTrace();<br>        }<br>        sender.send(message);<br><br>        return details;<br><br>    }<br>}</pre><p>We also need to create an HTML file to define how our email would appear once the receiver receives it. This will be used as the email template.</p><pre>&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;<br>&lt;html xmlns:th=&quot;http://www.thymeleaf.org&quot; xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;<br><br>&lt;head&gt;<br>    &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot; /&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;/&gt;<br>    &lt;title&gt;Template&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br><br>&lt;h1&gt;This is just a sample html page&lt;/h1&gt;<br><br>&lt;h2&gt;Below are the details that were passed to the html page&lt;/h2&gt;<br><br>&lt;p th:text=&quot;${&#39;Name    : &#39; + name}&quot;&gt;&lt;/p&gt;<br>&lt;p th:text=&quot;${&#39;Age     :&#39; + age}&quot;&gt;&lt;/p&gt;<br>&lt;p th:text=&quot;${&#39;Country : &#39; + country}&quot;&gt;&lt;/p&gt;<br><br>&lt;p&gt;&lt;b&gt;You can create the page the way you wish to have your Email body using HTML tags&lt;/b&gt;&lt;/p&gt;<br><br>&lt;p&gt;&lt;b&gt;Bootstrap can be added to design. Images can be added. All according to your preference&lt;/b&gt;&lt;/p&gt;<br><br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>That’s it. We have completed the implementation and it is time to test…</p><p>Simple… Isn’t it? I hope it was clear to you. The project source code can be viewed and downloaded from <a href="https://github.com/ChinthakaJ98/Send-Email">GitHub</a>. You are free to use it in your projects.</p><p>Cheers!! Have a pleasant day!!</p><p>Visit my <a href="http://chinthakajayatilake.tech/">Official Blog Site</a> to send in your queries directly to me and to read more articles by me….</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d44de0c6c27f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linkit-intecs/send-emails-using-angular-6-spring-boot-thymeleaf-d44de0c6c27f">Send Emails using Angular 6 + Spring Boot + Thymeleaf</a> was originally published in <a href="https://medium.com/linkit-intecs">LinkIT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-time Updating Chat Room  using Angular 6 + Spring Boot + Web Sockets]]></title>
            <link>https://medium.com/linkit-intecs/real-time-updating-chat-room-using-angular-6-spring-boot-web-sockets-cc1a6e9d4944?source=rss-1b3554b6fdf8------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc1a6e9d4944</guid>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Chinthaka Jayatilake]]></dc:creator>
            <pubDate>Tue, 08 Oct 2019 18:20:50 GMT</pubDate>
            <atom:updated>2020-05-30T18:17:51.583Z</atom:updated>
            <content:encoded><![CDATA[<h3>Real-time Updating Chat Room using Angular + Spring Boot + Web Sockets</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*ZY1Jp1WEnJKidT4a_5voJQ.jpeg" /><figcaption>Photo by Volodymyr Hryshchenko on Unsplash</figcaption></figure><p>What is really the specialty when it comes to web sockets? Let&#39;s find out. We know that we can simply make a chat app by using a database and a few code lines where we store and retrieve data when required. But with web sockets is how this process happens in real-time. There will be no need to refresh the page to get new messages, yet it will be automatically updated.</p><p>So let us now see how we could implement this.</p><p>Lets us first create the Angular project.</p><pre>ng new project_name</pre><p>Now we will create a basic HTML page to send messages and to display the received messages. So move to the <em>app.component.html</em> file.</p><pre>&lt;div *ngFor=&quot;let string of greetings&quot;&gt;</pre><pre> &lt;div class=&quot;container&quot;&gt;<br>  &lt;p&gt;{{string}}&lt;/p&gt;<br> &lt;/div&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;form #loginForm=ngForm&gt;<br> &lt;div&gt;<br>  &lt;br&gt;<br>  &lt;textarea autocomplete=&quot;off&quot; placeholder=&quot;Type Your Message...&quot; name=&quot;newmessage&quot; [(ngModel)]=&quot;newmessage&quot; required&gt;&lt;/textarea&gt;</pre><pre>  &lt;button class=&quot;btn btn-primary&quot; (click)=&quot;sendMessage()&quot; [disabled]=&quot;!loginForm.valid&quot;&gt;Send&lt;/button&gt;<br> &lt;/div&gt;<br>&lt;/form&gt;</pre><p>Now its time to implement the web socket in the front-end. For that, we need to move to the <em>app.component.ts</em> file. Here we will also be implementing a method to establish the connection with the back-end, to send messages and also to receive messages.</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import * as Stomp from &#39;stompjs&#39;;<br>import * as SockJS from &#39;sockjs-client&#39;;</pre><pre>@Component({<br> selector: &#39;app-root&#39;,<br> templateUrl: &#39;./app.component.html&#39;,<br> styleUrls: [&#39;./app.component.css&#39;]<br>})</pre><pre>export class AppComponent {</pre><pre>  title = &#39;WebSocketChatRoom&#39;;</pre><pre>  greetings: string[] = [];</pre><pre>  disabled = true;</pre><pre>  newmessage: string;</pre><pre>  private stompClient = null;</pre><pre>  constructor(){}</pre><pre>  ngOnInit() {</pre><pre>    this.connect();</pre><pre>  }</pre><pre>  setConnected(connected: boolean) {</pre><pre>    this.disabled = !connected;<br>    if (connected) {<br>      this.greetings = [];<br>    }</pre><pre>  }</pre><pre>  connect() {</pre><pre>    const socket = new SockJS(&#39;http://localhost:8080/testchat&#39;);<br>    this.stompClient = Stomp.over(socket);<br>    const _this = this;<br>    this.stompClient.connect({}, function (frame) {<br>      console.log(&#39;Connected: &#39; + frame);<br>      _this.stompClient.subscribe(&#39;/start/initial&#39;, function(hello){<br>        console.log(JSON.parse(hello.body));<br>        _this.showMessage(JSON.parse(hello.body));<br>      });<br>   });<br>  }</pre><pre>  sendMessage() {</pre><pre>    this.stompClient.send(<br>      &#39;/current/resume&#39;,<br>      {},<br>      JSON.stringify(this.newmessage)<br>    );<br>    this.newmessage = &quot;&quot;;</pre><pre>  }</pre><pre>  showMessage(message) {</pre><pre>    this.greetings.push(message);</pre><pre>  }</pre><pre>} </pre><p>Do not forget to include the below command in your <em>polyfills.ts</em> file.</p><pre>(window as any).global = window;</pre><p>It is important to make sure that all the imports which are mentioned at the beginning of the <em>component.ts</em> files are present in the project node modules folder. If not they must be installed as below.</p><pre>npm install imported_file_name</pre><p>Now we need to create our Spring Boot project. The following link will help you to create and download your Spring Boot project just by few clicks.</p><p><a href="https://start.spring.io/">Spring Initializr</a></p><p>We need to add the below dependencies to our <em>pom.xml</em> file to import them to our project in order to use them.</p><pre>&lt;dependencies&gt;<br>   &lt;dependency&gt;<br>      &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>      &lt;artifactId&gt;spring-boot-starter&lt;/artifactId&gt;<br>   &lt;/dependency&gt;<br><br>   &lt;dependency&gt;<br>      &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>      &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>      &lt;scope&gt;test&lt;/scope&gt;<br>   &lt;/dependency&gt;<br><br>   &lt;dependency&gt;<br>      &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>      &lt;artifactId&gt;spring-boot-starter-websocket&lt;/artifactId&gt;<br>      &lt;version&gt;1.5.2.RELEASE&lt;/version&gt;<br>   &lt;/dependency&gt;<br><br>   &lt;dependency&gt;<br>      &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>      &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>   &lt;/dependency&gt;<br><br>&lt;/dependencies&gt;</pre><p>Now we need to create the configurations of our web socket. For that, we will be creating a separate class for our convenience.</p><pre>import org.springframework.context.annotation.Configuration;<br>import org.springframework.messaging.simp.config.MessageBrokerRegistry;<br>import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;<br>import org.springframework.web.socket.config.annotation.StompEndpointRegistry;<br>import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;<br><br>@Configuration<br>@EnableWebSocketMessageBroker<br>public class WebSocketChatConfiguration implements WebSocketMessageBrokerConfigurer {<br><br>    @Override<br>    public void configureMessageBroker(MessageBrokerRegistry config{<br>        config.enableSimpleBroker(&quot;/start&quot;);<br>        config.setApplicationDestinationPrefixes(&quot;/current&quot;);<br>    }<br><br>    @Override<br>    public void registerStompEndpoints(StompEndpointRegistry registry) {<br>        registry<br>                .addEndpoint(&quot;/testchat&quot;)<br>                .setAllowedOrigins(&quot;http://localhost:4200&quot;)<br>                .withSockJS();<br>    }<br>}</pre><p>As it is done now, we move on to the final section which is the controller. Here is where we get the data from the front-end and send data back to front-end with the use of the configured web socket.</p><pre>import org.springframework.messaging.handler.annotation.MessageMapping;<br>import org.springframework.messaging.handler.annotation.SendTo;<br>import org.springframework.stereotype.Controller;<br><br><br>@Controller<br>public class WebSocketChatController {<br><br>    @MessageMapping(&quot;/resume&quot;)<br>    @SendTo(&quot;/start/initial&quot;)<br>    public String chat(String msg) {<br>        System.<em>out</em>.println(msg);<br>        return msg;<br>    }<br>}</pre><p>With that, we have come to the end of our implementation. Definitely you must be eagerly waiting now to check whether this works. So check it out now.</p><p>The project source code can be viewed and downloaded from <a href="https://github.com/ChinthakaJ98/Chat-Room-App">GitHub</a>. You can simply add it to your project whenever required.</p><p>Hope you got an idea about how to implement web sockets in your project. You can even add a database to this app to save the messages sent and to load them each time you open the message list.</p><p>Try it out. Trust me. Only a few lines more to be added…</p><p>Cheers!! Have a pleasant day!!</p><p>Visit my <a href="http://chinthakajayatilake.tech/">Official Blog Site</a> to send in your queries directly to me and to read more articles by me…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc1a6e9d4944" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linkit-intecs/real-time-updating-chat-room-using-angular-6-spring-boot-web-sockets-cc1a6e9d4944">Real-time Updating Chat Room  using Angular 6 + Spring Boot + Web Sockets</a> was originally published in <a href="https://medium.com/linkit-intecs">LinkIT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comparison of Java 7 with Java 8]]></title>
            <link>https://medium.com/linkit-intecs/comparison-of-java-7-with-java-8-e99e407832af?source=rss-1b3554b6fdf8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e99e407832af</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[java-7]]></category>
            <category><![CDATA[comparison]]></category>
            <dc:creator><![CDATA[Chinthaka Jayatilake]]></dc:creator>
            <pubDate>Tue, 08 Oct 2019 18:17:10 GMT</pubDate>
            <atom:updated>2020-05-30T17:55:21.382Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*yw8wJInh3TO5M2ad1ho62Q.jpeg" /><figcaption>Photo by Fotis Fotopoulos on Unsplash</figcaption></figure><p>Here we mainly discuss the differences, or in other words advancements that have been included in Java 8 when compared to Java 7.</p><p>To begin with, let me give a brief introduction to Java 7. Java 7 was released in 2011. This was the first major update of Java after being acquired by Oracle from Sun Microsystems. Java 7 is the final Java version that would officially support Windows XP.</p><p>There were some major features that were included in Java 7. Such as,</p><ul><li>Compressed 64-bit pointers.</li><li>Upgraded class-loader architecture.</li><li>Multiple exception handling.</li><li>JVM support for dynamically support languages.</li><li>Upgraded Rowset 1.1 and JDBC 4.1.</li><li>String object in a switch statement.</li><li>Automatic resource management in a <em>try</em> statement and much more.</li></ul><p>But in this blog, our main concern will be on discussing a few advancements that happened when updating from Java 7 to Java 8.</p><p>Java 8 was released in March 2014. The most anticipated feature — Lambda Expressions, was introduced and made possible from Java 8. The use of this Lambda Expressions made Java closer to functional programming which it was not used to be. Java 8 also includes a faster and improved JVM which makes it possible to run programs more efficiently.</p><p>Now it is time to point out and discuss some of the major upgrades of Java 8 when compared to Java 7.</p><h4>Lambda Expressions</h4><ul><li>Lambda expressions only have a body and a parameter list.</li><li>Advantages we get by using Lambda Expressions are,</li></ul><ol><li>Enhanced iterative syntax.</li><li>Readability.</li><li>Code Reuse.</li><li>JAR file size reduction.</li><li>Simplified variable scope.</li><li>Encouraging Functional Programming.</li></ol><ul><li>Let us look at a couple of examples using lambda expressions</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*m989nccYUifUSq__fDJ8Ww.png" /><figcaption>Lambda Expression with No Arguments Passed</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*GCAr46ui55zpiQnwdE5RLw.png" /><figcaption>Lambda Expression with One Arguments Passed</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*MyRPIzNxXR94QegkxD7a5Q.png" /><figcaption>Lambda Expression with Two Arguments Passed</figcaption></figure><p><em>In Java, a </em><strong><em>functional interface</em></strong><em> is an interface that has only one abstract method.</em></p><h4>Null Reference Template</h4><p>We can also call it the Java Optional Class.</p><ul><li>Advantages using the Java Optional class are,</li></ul><ol><li>No Null Pointer Exceptions at run-time.</li><li>Clean APIs can be developed.</li><li>Null checks are not required.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*LkwQwi3QD1H1skQhXuGWYA.png" /><figcaption>Java Optional Class Example</figcaption></figure><h4>New Date and Time API</h4><ul><li>In <em>java.util.Date </em>class the years starting from 1900 and the months start from 0. So it is important to know it, as when we want to assign a year and a month it must be as (YYYY-1900) and (MM-1). This was overcome in Java 8 using the classes in <em>java.time</em> package.</li><li>Unlike integer or string, the <em>Date </em>class is mutable. Which means that the date can be changed without the owner class knowing. Java 8 has a solution for this. The LocalDate, LocalTime, LocalDateTime, etc. introduced in Java 8 are immutable (The original object is not changed. Whenever a change is done, a new object will be returned).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*_YHS9pKQQK5D_AJqtnSSIA.png" /><figcaption>Use of the New Date and Time API</figcaption></figure><h4>Unsigned Integer Arithmetic</h4><ul><li>It is not clear what Java 8 has tried to achieve by the advancement in unsigned integer arithmetic. But generally, an unsigned integer is considered to be harmful to Java. It adds complexity to the type conversion tools, type system, and library APIs.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*dHvTtGB5V2Z4DFMntzRMFg.png" /></figure><h4>Stream API</h4><ul><li>The main advantage that we get using the Stream API is that it clearly increases the speed and efficiency of the program. It is considered to be a powerhouse in Java.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*_LFTbDXOqiR3imK7MNdNeA.png" /></figure><h4>Parallel Sorting</h4><ul><li>Parallel sorting uses multiple threads for the operation. It makes the program fast and efficient. This will not be that much visible with a small data set. But if we use large data set the efficiency and the increase in performance will be highly noticeable.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*ShUh_QTCtcUzkafqP1_e3A.png" /></figure><h4>New JavaScript Engine</h4><ul><li>The JavaScript Engine introduced with Java 8 was named Nashorn.</li></ul><p>With that now, we have come to the end of this section and the main aim of it was to give an idea about the updated and added features in Java 8 compared to Java 7. According to the examples provided hope you got an idea on how to use these advancements for your benefit. Most of these provide us with advantages but there are certain drawbacks as well if we look at different perspectives. It is important to remember, only to absorb the features that would help us and make our program more efficient, reliable, and stable.</p><p>Cheers!! Have a pleasant day!!</p><p>Visit my <a href="http://chinthakajayatilake.tech/">Official Blog Site</a> to send in your queries directly to me and to read more articles by me….</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e99e407832af" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linkit-intecs/comparison-of-java-7-with-java-8-e99e407832af">Comparison of Java 7 with Java 8</a> was originally published in <a href="https://medium.com/linkit-intecs">LinkIT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL vs. MongoDB]]></title>
            <link>https://medium.com/linkit-intecs/sql-vs-mongodb-b83dd434bb24?source=rss-1b3554b6fdf8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b83dd434bb24</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[comparison]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Chinthaka Jayatilake]]></dc:creator>
            <pubDate>Tue, 08 Oct 2019 18:06:06 GMT</pubDate>
            <atom:updated>2020-06-03T15:39:23.420Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*Jw2te2c34Up-rf3XSquw0Q.jpeg" /><figcaption>Photo by Caspar Camille Rubin on Unsplash</figcaption></figure><p>At present, selection between SQL and MongoDB for projects is a common topic among the developers. The main reason for MongoDB to be popular in no time is because of the interesting features that it provides to reduce the complexity in programming and to increase the efficiency in executing.</p><p>Today, the main objective will be to brief both SQL and MongoDB along with a discussion regarding their advantages and drawbacks which will make it easier to select one among them to implement in our projects according to our requirements.</p><h3>SQL</h3><p>SQL stands for the structured query language. It is a database computer language that is designed to retrieve and manage data in a relational database. RDBMS stands for Relational Database Management System. It is the basis of SQL. MSSQL, MySQL, and OracleSQL are examples of some modern database systems. SQL is built around relational algebra. Data Definition Language(DDL) is used for inserting data and Data Manipulation Language(DML) is used to manipulate the existing data. The database sticks to the ACID(Atomicity, Consistency, Isolation, Durability) properties when executing a transaction.</p><p>Let us now give concern towards the advantages and the drawbacks in the use of SQL.</p><h4>Advantages of SQL</h4><ul><li>A large number of records can be retrieved efficiently at a high speed.</li><li>No complex or many lines of code are required to manage the database system.</li><li>It can be used in servers, laptops, personal computers, and mobiles.</li><li>Ability to create views using a single table or a couple of tables</li><li>Locking protocols restrict the same data item being manipulated at the same time by many users. This will maintain consistent data in the database.</li><li>SQL uses an established standard that is being used by ANSI (American National Standard Institutes) and ISO (International Organization for Standardization).</li></ul><h4>Drawbacks of SQL</h4><ul><li>Difficult to scale when the database grows larger.</li><li>Partitioning the database into smaller parts.</li><li>Some SQL versions have a high operating cost.</li><li>Programmers using SQL have only partial control over the database.</li><li>It may be difficult for some users to access as SQL has a complex interface.</li></ul><h3>MongoDB</h3><p>MongoDB is a leading NoSQL Database. It is an open-source document database written in C++. Basically NoSQL database was created to overcome the issues that the traditional relational database technology has. In MongoDB data is organized as JSON documents and BSON(Binary Serialized JSON) format is used for document storage. Data manipulation can be done through object-oriented APIs. MongoDB is a database which was mainly designed for big data and query. MongoDB gains its performance because of its key value-based design.</p><p>Now let us focus on the advantages that we get by using a NoSQL database like MongoDB and the disadvantages we experience.</p><h4>Advantages of MongoDB</h4><ul><li>Scalability increases performance.</li><li>It has a flexible schema which makes agile development possible.</li><li>Geographically distributed scale-out architecture.</li><li>Ability to store large volumes of structured, semi-structured, or unstructured data.</li><li>Flexibility.</li><li>Big data processing and real data analysis.</li><li>The optional strict consistent level which ensure the insertion is completely successful in the safe mode.</li></ul><h4>Disadvantages of MongoDB</h4><ul><li>Transactions are not supported.</li><li>No single join operation. But it could be achieved by using multiple queries.</li></ul><p>With all that we had come to the end of this discussion regarding SQL and MongoDB. We have identified each of them with their differences, positives, and negatives. It is totally up to us to decide on what database technology we must develop the software according to the requirements we have and the features each technology offers. We cannot name any technology and say that it is superior. Everything is based on the project requirements we are working with.</p><p>One technology might give a negative impact on the project while another technology may highly connect with the project. With the use of knowledge on technologies, we must be able to select the most suitable technology, to gain the maximum benefit that we could receive by implementing it within the software.</p><p>Cheers!! Have a pleasant day!!</p><p>Visit my <a href="http://chinthakajayatilake.tech/">Official Blog Site</a> to send in your queries directly to me and to read more articles by me…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b83dd434bb24" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linkit-intecs/sql-vs-mongodb-b83dd434bb24">SQL vs. MongoDB</a> was originally published in <a href="https://medium.com/linkit-intecs">LinkIT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>