<?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 Zia khalid on Medium]]></title>
        <description><![CDATA[Stories by Zia khalid on Medium]]></description>
        <link>https://medium.com/@ziatheonlyone?source=rss-fa077a28c7ec------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UXsi8A1NZey1L6ZwPSTDmQ.jpeg</url>
            <title>Stories by Zia khalid on Medium</title>
            <link>https://medium.com/@ziatheonlyone?source=rss-fa077a28c7ec------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 05:14:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ziatheonlyone/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[Android in Kotlin -Part 1.0: Configuring project (Android Studio + Kotlin)]]></title>
            <link>https://medium.com/@ziatheonlyone/android-in-kotlin-part-1-0-configuring-project-android-studio-kotlin-984fde547df9?source=rss-fa077a28c7ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/984fde547df9</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-studio]]></category>
            <dc:creator><![CDATA[Zia khalid]]></dc:creator>
            <pubDate>Wed, 03 May 2017 12:40:22 GMT</pubDate>
            <atom:updated>2017-05-05T06:50:57.926Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FGpLdGDxgqCETjjc3fr0Iw.png" /></figure><h3>Part 1.0: Configuring project (Android Studio + Kotlin)</h3><p>In this Part we will configure an Android Studio project to use Kotlin and left everything prepared for the next story to start developing the Android App from the beginning and learning some core concepts.</p><p><strong>Creating Android Project</strong></p><p>We are going to start from scratch, launch<strong> Android Studio </strong>and <br>Hit Start a new Android Studio project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0h6ceWtdr64tQVMSs7d0pA.png" /></figure><p>Choose Application name and Company domain of your choice &gt; Next</p><p><strong>Application name</strong> is the name of you App</p><p><strong>Company domain</strong> is your package name, Your package name is just a unique identifier for your application in the Google Play Store. It can be anything you want as long as it is unique.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S5phdp80Pyoqjm-tFCGwjg.png" /></figure><p>Choose Minimum SDK of your choice &gt; Next</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eUQjU0-hyOky0ETzmX0mYQ.png" /></figure><p>Choose Empty Activity &gt; Next</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uCBfMRt8TUdwbSxd0tPG_A.png" /></figure><p>Keeping Activity Name and Layout Name as default &gt;<strong>Finish</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2kPydXAT-f2XmvC_lef-Mg.png" /></figure><p>This should create your basic project. let’s install the required Plugin for Kotlin.</p><p>Android Studio Pref &gt; Plugins &gt; Browse Repositories &gt; search for “Kotlin”<br>install and restart Android Studio</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qamcDim4VilRiYCw3xB-EQ.png" /></figure><p>Our already created MainActivity.java looks something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SmttLrPsQ4R051Om-nrW7g.png" /></figure><p>Now we gonna change MainActivity.java to kotlin file .</p><p>code &gt; convert java file to kotlin file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MFrwFxVd0-xLMgt_1VuvzA.png" /></figure><p>Here is your MainActivity.kt</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iAzGmCDdFe_ymceSKahqbA.png" /></figure><p>Now its time to configure kotlin in your project.<br>open Find Action(command+shift+A) and start searching “Convert Java to…” &gt; choose All module as an option.</p><p>This will update your build.gradle at app level</p><pre>apply plugin: &#39;<strong>kotlin-android</strong>&#39;</pre><pre>compile &quot;<strong>org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_ver</strong>&quot;</pre><p>and will add classpath to build.gradle at project level</p><pre>classpath &quot;<strong>org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_ver</strong>&quot;</pre><h4>Repository</h4><p>Here you have all the code that we developed</p><p><a href="https://github.com/ziakhalid/android-kotlin-sample">ziakhalid/android-kotlin-sample</a></p><p><strong>Commit<br></strong><a href="https://github.com/ziakhalid/android-kotlin-sample/commit/60c6d0812a628c74dcddd37c7047b61d981bda9d">https://github.com/ziakhalid/android-kotlin-sample/commit/60c6d0812a628c74dcddd37c7047b61d981bda9d</a></p><p>uff… thats it …<strong>Hit Run</strong> :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JNH2E43MAT7EU0dnbvQHJw.png" /></figure><p>If you find something to improve please let me know, I will try my best to improve this story.</p><p><em>If this article was helpful to you, please do hit the </em>💚<em> button below. Thanks!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=984fde547df9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android in Kotlin — Introduction]]></title>
            <link>https://medium.com/@ziatheonlyone/android-in-kotlin-introduction-51249c9513b0?source=rss-fa077a28c7ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/51249c9513b0</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Zia khalid]]></dc:creator>
            <pubDate>Wed, 03 May 2017 12:36:42 GMT</pubDate>
            <atom:updated>2017-05-03T12:45:14.701Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j3xa2PCUYw6riKHn6LH_nw.png" /></figure><p><strong>Introduction</strong></p><p>Welcome to this series of stories where we are going to learn <strong>Android</strong>, while developing an <strong>Android App</strong>, we will choose <strong>Kotlin</strong> as our primary language, This story will be divided into different parts.</p><p>Things we gonna cover are</p><ul><li><strong>RecyclerView</strong></li><li><strong>Kotlin Android Extensions</strong></li><li><strong>Retrofit 2.0</strong></li><li><strong>Dagger 2</strong></li><li><strong>MockWebServer</strong></li><li><strong>RxJava 2</strong></li><li><strong>Gradle</strong></li><li><strong>Timber</strong></li><li><strong>Espresso</strong></li><li><strong>Robolectric</strong></li></ul><p>I will keep on updating list of topics as we progress …</p><p><strong>Repository</strong><br>Here you have all the code that we are going to be creating/reviewing in this series of Stories.</p><p><a href="https://github.com/ziakhalid/android-kotlin-sample">ziakhalid/android-kotlin-sample</a></p><p>Feel free to contact me</p><p><strong>LinkedIn</strong>: <a href="https://in.linkedin.com/in/zia-khalid-5b73b0139">https://in.linkedin.com/in/zia-khalid-5b73b0139</a></p><h3>Next Article</h3><p><a href="https://medium.com/@ziatheonlyone/android-in-kotlin-part-1-0-configuring-project-android-studio-kotlin-984fde547df9">Part 1.0: Configuring project (Android Studio + Kotlin)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51249c9513b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring REST API -Part 4.2: Spring Controllers (RestController — POST,PUT,DELETE)]]></title>
            <link>https://medium.com/@ziatheonlyone/spring-rest-api-part-4-2-spring-controllers-restcontroller-post-put-delete-23ab2fb5dc4a?source=rss-fa077a28c7ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/23ab2fb5dc4a</guid>
            <category><![CDATA[post]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Zia khalid]]></dc:creator>
            <pubDate>Sun, 30 Apr 2017 13:19:53 GMT</pubDate>
            <atom:updated>2017-05-05T06:50:31.971Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8zMVc8befN-bLhhxnNfHbw.png" /></figure><h3>Part 4.2: Spring Controllers (RestController — POST,PUT,DELETE)</h3><p><strong>Note</strong> — Codes in the story is in continuation to the previous parts, so if you feel uncomfortable or disconnected please check the previous parts or navigate through git commit to have a better understanding.</p><p>In this part we will learn about HTTP method POST, PUT and DELETE</p><p><strong>HTTP</strong> <strong>POST</strong></p><p>The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line.</p><p>Note — it should not updates existing resources as we have different method for it(PUT).</p><p>POST method is basically used to add new entity, If you want to add new entry to your collection you should go for POST.</p><p><strong>Handling POST request</strong></p><pre>@RequestMapping(method = RequestMethod.<em>POST</em>)<br>public ResponseEntity&lt;?&gt; addTopic(<strong>@RequestBody</strong> Topic topic) {<br>    if (<strong>topicRepository.save</strong>(new Topic(topic.getTopicName(), topic.getQuestionCount())) != null) {<br>        return Util.<em>createResponseEntity</em>(&quot;Successful creation of a resource&quot;, HttpStatus.<em>CREATED</em>);<br>    }<br>    return Util.<em>createResponseEntity</em>(&quot;Error creating resource&quot;, HttpStatus.<em>BAD_REQUEST</em>);<br>}</pre><p>@RequestBody annotation indicating a method parameter should be bound to the body of the web request.The body of the request is passed through an HttpMessageConverter which process HTTP requests and responses, to resolve the method argument depending on the content type of the request.</p><p>&lt;S extends T&gt; S save(S entity) Saves the given entity.</p><p><strong>Commit<br></strong><a href="https://github.com/ziakhalid/spring-rest-sample/commit/4deb99ff5884c010c6b636557ea7eec324427e9b">https://github.com/ziakhalid/spring-rest-sample/commit/4deb99ff5884c010c6b636557ea7eec324427e9b</a></p><p>Thats it, your api is ready to handle POST request.</p><p><strong>Hit Run</strong></p><p><strong>Using Client : Postman</strong><br>Sending POST request to add new topic.</p><p>Select request type to POST<br>Select Body tab &gt; raw &gt; add json object of Topic type</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TsyiG0s2wZrGuYUu12JdXw.png" /></figure><p>Goto Headers tab &gt; set Key to Content-Type and value to application/json</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iOKPfjlcsXDQo_ftSF9YSg.png" /></figure><p>Hit Send, this should add new topic to your previous list. To check if your request is added to the list, again Hit GET request to get the list of topics, which should have newly added topic “”Java 8 — lambda”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-9EJzDQdUvdv6E14wYnKsQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d11T6_Fruxbg2-d0fTlHcQ.png" /></figure><p><strong>HTTP PUT</strong></p><p>PUT should be used to update existing resource.</p><p>The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server. If the Request-URI does not point to an existing resource, and that URI is capable of being defined as a new resource by the requesting user agent, the origin server can create the resource with that URI.”</p><p><strong>Updating existing resource</strong></p><p>Now you wanna update existing resource, lets say you wanna update resource with id 1</p><p>Adding <em>getTopicById</em> which will return Topic by Id</p><pre>@RequestMapping(method = RequestMethod.<em>GET</em>, value = &quot;topicId/{topicId}&quot;)<br>public Topic getTopicById(@PathVariable Long topicId) {<br>    return topicRepository.findOne(topicId);<br>}</pre><p>Lets see if its working</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7-s8XwvdSTmNjiEV6m35WA.png" /></figure><p>topicId 1 returns a topic named “Multi Threading”, i wanna update it to “Language Fundamentals” and increase “questionCount”</p><p>Adding updateTopic which will handle HTTP PUT request and update the requested data</p><pre>@RequestMapping(method = <strong>RequestMethod.<em>PUT</em></strong>, value = &quot;topicId/{topicId}&quot;)<br>public ResponseEntity&lt;?&gt; updateTopic(@RequestBody Topic topic, @PathVariable long topicId) {<br>    Topic newTopic = topicRepository.findOne(topicId);<br>    if (newTopic != null) {<br>        newTopic.setTopicName(topic.getTopicName());<br>        newTopic.setQuestionCount(topic.getQuestionCount());<br>        if (topicRepository.save(newTopic).getId().equals(topicId)) {<br>            return Util.<em>createResponseEntity</em>(&quot;Data updated successfully&quot;, HttpStatus.<em>OK</em>);<br>        }<br>    }<br>    return Util.<em>createResponseEntity</em>(&quot;Error updating data&quot;, HttpStatus.<em>NOT_FOUND</em>);<br>}</pre><p><strong>Commit<br></strong><a href="https://github.com/ziakhalid/spring-rest-sample/commit/6fce96130e056759b5b76d5b035a6bb685a63888">https://github.com/ziakhalid/spring-rest-sample/commit/6fce96130e056759b5b76d5b035a6bb685a63888</a></p><p><strong>Hit Run</strong></p><p><strong>Using Client : Postman</strong><br>Sending PUT request to update existing resource.</p><p>Select request type to PUT<br>Select Body tab &gt; raw &gt; add json object of updated Topic type</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NI4uEopstoFpMdYFc2x6bw.png" /></figure><p>Goto Headers tab &gt; set Key to Content-Type and value to application/json</p><p>Hit Send, this should update your data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iWQ6mP12LBGIL17cGK8OkA.png" /></figure><p>To recheck your updated data Hit GET request for topicId 1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mXaFErP303bdPAYSAHkSJw.png" /></figure><p>Here you go data updated successfully :)</p><p><strong>HTTP DELETE</strong></p><p>The DELETE method requests that the origin server delete the resource identified by the Request-URI.</p><p>Now i wanna delete existing resource, lets say i wanna delete topic with topicId 1</p><p>Adding <em>deleteTopic </em>which will delete topic based on topicId</p><pre>@RequestMapping(method = <strong>RequestMethod.<em>DELETE</em></strong>, value = &quot;topicId/{topicId}&quot;)<br>ResponseEntity&lt;?&gt; deleteTopic(@PathVariable long topicId) {<br>    try {<br>        topicRepository.delete(topicId);<br>        return Util.<em>createResponseEntity</em>(&quot;Data deleted successfully&quot;, HttpStatus.<em>ACCEPTED</em>);<br>    } catch (Exception e) {<br>        return Util.<em>createResponseEntity</em>(&quot;Resource not found&quot;, HttpStatus.<em>NOT_FOUND</em>);<br>    }<br>}</pre><p><strong>Commit<br></strong><a href="https://github.com/ziakhalid/spring-rest-sample/commit/6722782df03cdb903da27f0d412f33d26b1ae18f">https://github.com/ziakhalid/spring-rest-sample/commit/6722782df03cdb903da27f0d412f33d26b1ae18f</a></p><p><strong>Hit Run</strong></p><p><strong>Using Client : Postman</strong><br>Sending DELETE request to delete existing resource.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xRAsDFsV5aJg8hShwp1n5g.png" /></figure><p>Here you go, “Data deleted successfully”</p><p>If you find something to improve please let me know, I will try my best to improve this story.</p><p><em>If this article was helpful to you, please do hit the </em>💚<em> button below. Thanks!</em></p><p>See you in the next story!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23ab2fb5dc4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring REST API -Part 4.1: Spring Controllers (RestController — GET)]]></title>
            <link>https://medium.com/@ziatheonlyone/spring-rest-api-part-4-1-spring-controllers-restcontroller-get-33dc0a9dbccf?source=rss-fa077a28c7ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/33dc0a9dbccf</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Zia khalid]]></dc:creator>
            <pubDate>Sat, 29 Apr 2017 19:39:19 GMT</pubDate>
            <atom:updated>2017-05-06T19:11:11.696Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vd6IxIGuUW-HVf-6-CM2mA.png" /></figure><h3>Part 4.1:Spring Controllers (RestController — GET)</h3><p><strong>Note</strong> — Codes in the story is in continuation to the previous parts, so if you feel uncomfortable or disconnected please check the previous parts or navigate through git commit to have a better understanding.</p><p>Now you want your own implementation, you want to control the HTTP requests and response for your api</p><p>In Spring’s approach to building RESTful web services, HTTP requests are handled by a controller.</p><p><strong>What is Controller ?</strong></p><p><strong>Controller</strong> is, thread-safe class, capable of handling multiple HTTP requests throughout the lifecycle of an application.</p><p><strong>RestController</strong>, is a specialized version of the controller which is a convenience annotation, that is itself annotated with @Controllerand @ResponseBody. By annotating the controller class with @RestController annotation, you no longer need to add @ResponseBody to all the request mapping methods. The @ResponseBody annotation is active by default</p><p>Creating <strong>TopicController</strong></p><pre><strong>@RestController</strong><br><strong>@RequestMapping</strong> (&quot;/topics&quot;)<br>public class TopicController {<br><br>    @Autowired<br>    TopicRepository topicRepository;<br><br>    @RequestMapping (method = <strong>RequestMethod.<em>GET</em></strong>)<br>    Collection&lt;Topic&gt; getAllTopics(){<br>        return Lists.<em>newArrayList</em>(topicRepository.<strong>findAll()</strong>);<br>    }<br><br>}</pre><p>RequestMethod.GET Handles HTTP GET requests</p><p>CrudRepository provides sophisticated CRUD functionality for the entity class that is being managed. It has implementation for some some of the very commonly user query:</p><p>findAll() Returns all entities.</p><p>T findOne(ID id) Return the entity with the given id.</p><p><strong>Commit<br></strong>Here you can see the commit of all this changes:</p><p><a href="https://github.com/ziakhalid/spring-rest-sample/commit/77f59b37637bfcb1997d1abb3be482540ac4f043">https://github.com/ziakhalid/spring-rest-sample/commit/77f59b37637bfcb1997d1abb3be482540ac4f043</a></p><p><strong>Hit Run</strong></p><p><strong>Using Client : Postman</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*94xAsvwlanH-pgdhOLaVZg.png" /></figure><p>You see the list of topic :) … <strong>Wait…..</strong> but it doesn’t looks like the previous API which Spring produced by default, it don’t have the<br><strong>navigable links</strong> which was pointing to available resource <strong>???</strong></p><p>Hold On till we talk about (Spring <strong>HATEOAS</strong>) in upcoming stories :)</p><p><strong>Implementing custom Query</strong></p><p>Now you wanna have more control over your repository , you want to find topics by topic name</p><p><strong>Adding custom query to your repository</strong></p><pre>//select a from Topic a where a.topicname = :topicname<br>Collection&lt;Topic&gt; <strong>findByTopicName</strong>(String topicName);</pre><p><strong>Adding controller for custom query</strong></p><p>We can pass parameter in URI topicName/{topicName} which can be received by method by using @PathVariable</p><p>@PathVariable annotation, indicates that a method parameter should be bound to a URI template</p><pre>@RequestMapping(method = RequestMethod.<em>GET</em>, value = &quot;topicName/{topicName}&quot;)<br>public Collection&lt;Topic&gt; getTopicByTopicName(<strong>@PathVariable</strong> String topicName){<br>    return topicRepository.<strong>findByTopicName</strong>(topicName);<br>}</pre><p><strong>Commit<br></strong><a href="https://github.com/ziakhalid/spring-rest-sample/commit/5d077f6f4679e9dcf29d20ad09c4bc2727bbfc8f">https://github.com/ziakhalid/spring-rest-sample/commit/5d077f6f4679e9dcf29d20ad09c4bc2727bbfc8f</a></p><p><strong>Hit Run</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PsbboG1GhnEntIkW3BpcLQ.png" /></figure><p>Here you Go , HTTP Response based on your query parameter :)</p><p>If you find something to improve please let me know, I will try my best to improve this story.</p><p><em>If this article was helpful to you, please do hit the </em>💚<em> button below. Thanks!</em></p><p>See you in the next story!</p><h3>Next Article</h3><p><a href="https://medium.com/@ziatheonlyone/spring-rest-api-part-4-2-spring-controllers-restcontroller-post-put-delete-23ab2fb5dc4a">Part 4.2: Spring Controllers (RestController — POST,PUT,DELETE)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33dc0a9dbccf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring REST API -Part 3: Spring Security (Basic Authentication)]]></title>
            <link>https://medium.com/@ziatheonlyone/spring-rest-api-part-3-spring-security-basic-authentication-3fd20342745b?source=rss-fa077a28c7ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fd20342745b</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Zia khalid]]></dc:creator>
            <pubDate>Sat, 15 Apr 2017 17:25:19 GMT</pubDate>
            <atom:updated>2017-05-05T06:49:09.977Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oAK3NL2BsEWysjRb7s5CKQ.png" /></figure><h3>Part 3: Spring Security (Basic Authentication)</h3><p><strong>Note</strong> — Codes in the story is in continuation to the previous parts, so if you feel uncomfortable or disconnected please check the previous parts or navigate through git commit to have a better understanding.</p><p>In this part we will secure REST API using Basic Authentication.</p><p><strong>What is Basic Authentication?</strong></p><p>Basic authentication sends a Base64-encoded string that contains a user name and password for the client. Base64 is not a form of encryption and should be considered the same as sending the user name and password in clear text. If a resource needs to be protected, strongly consider using an authentication scheme other than basic authentication.</p><p>With Basic Authentication, clients send it’s Base64 encoded credentials <strong>with each request</strong>, using HTTP [Authorization] header . That means each request is independent of other request and server does not maintain any state information for the client.</p><p>Base64 encoded string looks somthing like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*akIrOnftqlJj7gRBaEEt2A.png" /></figure><p>This header will be sent with each request.</p><p><strong>Adding spring security dependency<br></strong>To enable spring security add compile time dependency to your build.gradle</p><pre>compile &#39;<strong>org.springframework.boot:spring-boot-starter-security</strong>&#39;</pre><p><strong>Creating User entity</strong></p><pre>@Entity<br>public class User extends BaseEntity {<br><br>    public static final <strong>PasswordEncoder</strong> <em>PASSWORD_ENCODER </em>= new BCryptPasswordEncoder();<br>    private String firstName;<br>    private String lastName;<br>    private String username;<br>    <strong>@JsonIgnore</strong><br>    private String password;<br>    <strong>@JsonIgnore</strong><br>    private String[] roles;<br><br>    public User() {<br>        super();<br>    }<br><br>    public User(String firstName, String lastName, String username, String password, String[] roles) {<br>        this.firstName = firstName;<br>        this.lastName = lastName;<br>        this.username = username;<br>        <strong>setPassword(password);</strong><br>        this.roles = roles;<br>    }<br><br>    public String getFirstName() {<br>        return firstName;<br>    }<br><br>    public void setFirstName(String firstName) {<br>        this.firstName = firstName;<br>    }<br><br>    public String getLastName() {<br>        return lastName;<br>    }<br><br>    public void setLastName(String lastName) {<br>        this.lastName = lastName;<br>    }<br><br>    public String getUsername() {<br>        return username;<br>    }<br><br>    public void setUsername(String username) {<br>        this.username = username;<br>    }<br><br>    public String getPassword() {<br>        return password;<br>    }<br><br>    public void setPassword(String password) {<br>        <strong>this.password = <em>PASSWORD_ENCODER</em>.encode(password);</strong><br>    }<br><br>    public String[] getRoles() {<br>        return roles;<br>    }<br><br>    public void setRoles(String[] roles) {<br>        this.roles = roles;<br>    }<br>}</pre><p>We should use <strong>PasswordEncoder</strong> for encoding password and security<br> we don’t want our password and role to be exposed so @JsonIgnore<strong> </strong>annotation ensure field is to be ignored by introspection-based serialization and deserialization functionality.</p><p><strong>Creating UserRepository</strong></p><pre>public interface UserRepository extends CrudRepository&lt;User, Long&gt;{<br><br>    User findByUsername(String username);<br><br>}</pre><p>Creating Spring’s <strong>UserDetailsService</strong> for loading user-specific data. It is used throughout the framework as a user DAO and is the strategy used by the DaoAuthenticationProvider.</p><pre>@Component<br>public class DetailsService implements UserDetailsService {<br><br>    @Autowired<br>    UserRepository users;<br><br>    @Override<br>    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {<br><br>        User user = users.findByUsername(username);<br>        if (user == null){<br>            throw new UsernameNotFoundException(username + &quot; was not found&quot;);<br>        }<br>        return new org.springframework.security.core.userdetails.User(<br>                user.getUsername(),<br>                user.getPassword(),<br>                AuthorityUtils.<em>createAuthorityList</em>(user.getRoles())<br>        );<br>    }<br>}</pre><p><strong>Creating WebSecurityConfiguration</strong></p><pre>@Component<br><strong>@EnableWebSecurity</strong><br>public class WebSecurityConfiguration extends <strong>WebSecurityConfigurerAdapter</strong>{<br><br>    @Autowired<br>    DetailsService detailsService;<br><br>    @Override<br>    protected void configure(AuthenticationManagerBuilder auth) throws Exception {<br>        auth.userDetailsService(detailsService).passwordEncoder(User.<em>PASSWORD_ENCODER</em>);<br>    }<br><br>    @Override<br>    protected void configure(HttpSecurity http) throws Exception {<br>        http.authorizeRequests()<br>                .anyRequest().authenticated()<br>                .and()<br>                .httpBasic()<br>                .and()<br>                .csrf().disable();<br>    }<br>}</pre><p>@EnableWebSecurity<strong> </strong>— we want custom Spring Security configuration, by overriding base class methods, and ensures that any request to our application requires the user to be authenticated.</p><p><strong>Populating database with dummy user</strong></p><pre>@Component<br>public class DatabaseLoader implements ApplicationRunner{<br><br>    private TopicRepository topics;<br>    private UserRepository users;<br><br>    @Autowired<br>    public DatabaseLoader(TopicRepository topics, UserRepository users) {<br>        this.topics = topics;<br>        this.users = users;<br>    }<br><br>    @Override<br>    public void run(ApplicationArguments args) throws Exception {<br><br>        List&lt;User&gt; students = Arrays.<em>asList</em>(<br>                new User(&quot;Reza&quot;, &quot;Khalid&quot;,  &quot;rezakhalid&quot;, &quot;password&quot;, new String[] {&quot;ROLE_USER&quot;}),<br>                new User(&quot;Satyaveer&quot;, &quot;Singh&quot;,  &quot;satyveer_singh&quot;, &quot;password&quot;, new String[] {&quot;ROLE_USER&quot;}),<br>                new User(&quot;Satish&quot;, &quot;Yadav&quot;,  &quot;satishyadav&quot;, &quot;password&quot;, new String[] {&quot;ROLE_USER&quot;}),<br>                new User(&quot;Farzan&quot;, &quot;Ahmad&quot;,  &quot;farzan_ahmad&quot;, &quot;password&quot;, new String[] {&quot;ROLE_USER&quot;})<br>        );<br>        users.save(students);<br><br>        users.save(new User(&quot;zia&quot;, &quot;khalid&quot;, &quot;zia566&quot;, &quot;123456&quot;, new String[] {&quot;ROLE_USER&quot;, &quot;ROLE_ADMIN&quot;}));<br><br>        ArrayList&lt;Topic&gt; bunchOfTopic = new ArrayList&lt;Topic&gt;();<br><br>        String[] buzzWords = {&quot;Multi Threading&quot;, &quot;Inner Classes&quot;, &quot;Collections&quot;, &quot;Generics&quot;, &quot;Development&quot;, &quot;JVM&quot;};<br><br>        //Using java 8 features (stream, lambda)<br>        IntStream.<em>range</em>(0,10).forEach(it -&gt; {<br>            String buzzWord = buzzWords[it % buzzWords.length];<br>            Topic topic = new Topic(buzzWord, (it % buzzWords.length));<br>            bunchOfTopic.add(topic);<br>        });<br><br>        topics.save(bunchOfTopic);<br>    }<br>}</pre><p><strong>Commit<br></strong>Here you can see the commit of all this changes:</p><p><a href="https://github.com/ziakhalid/spring-rest-sample/commit/9f2e1a1a201c5629dfef4a97d4638ff5a1c34efd">https://github.com/ziakhalid/spring-rest-sample/commit/9f2e1a1a201c5629dfef4a97d4638ff5a1c34efd</a></p><p><strong>Hit Run</strong></p><p><strong>Using Client : Postman</strong><br>Send a request to get the list of topics. you would get 401 as status code, and error message saying “Unauthorized”, this as because of spring security, which is trying to authenticate every request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*77zJ3Z3XmcSeryFXvk7zdA.png" /></figure><p>Now select type as ‘Basic Auth’ from dropdown, fill in username/password , click on ‘update request’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CtQQ-DWh8tBiFFeMNCqOmg.png" /></figure><p>Click on Headers tab. You should see the new header.which should look like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iiFBjY2YFfS3NrIxY1an_g.png" /></figure><p>Now send the request. You should see the list of topics in response this time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xXt-40XWmHDKtDgJbsdHFg.png" /></figure><p>If you find something to improve please let me know, I will try my best to improve this story.</p><p><em>If this article was helpful to you, please do hit the </em>💚<em> button below. Thanks!</em></p><p>See you in the next story!</p><h3>Next Article</h3><p><a href="https://medium.com/@ziatheonlyone/spring-rest-api-part-4-1-spring-controllers-restcontroller-get-33dc0a9dbccf">Part 4.1: Spring Controllers (RestController — GET)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fd20342745b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring REST API -Part 2: Creating first API Response]]></title>
            <link>https://medium.com/@ziatheonlyone/spring-rest-api-part-2-creating-first-api-response-dbc90c4a98f7?source=rss-fa077a28c7ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbc90c4a98f7</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Zia khalid]]></dc:creator>
            <pubDate>Sat, 15 Apr 2017 09:27:47 GMT</pubDate>
            <atom:updated>2017-05-05T06:47:35.168Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5oPmqd5eryOPXOKN-5FjZQ.png" /></figure><h3>Part 2: Creating first API Response</h3><p><strong>Note</strong> — Codes in the story is in continuation to the previous parts, so if you feel uncomfortable or disconnected please check the previous parts or navigate through git commit to have a better understanding.</p><p>In this part we will be creating a API which will give us lists of Java Topics.</p><p>Creating <strong>BaseEntity</strong> abstract class, which is MappedSuperclass for child entity classes, and will hold id’s (primary key) for child entity in database. Here we are choosing primary key generation strategies to be AUTO (persistence provider should pick an appropriate strategy for the particular database)</p><pre><strong>@MappedSuperclass</strong><br>public class BaseEntity {<br><br>    <strong>@Id<br>    @GeneratedValue(strategy = GenerationType.<em>AUTO</em>)</strong><br>    private final Long id;<br><br>    protected BaseEntity() {<br>        this.id = null;<br>    }<br>}</pre><p>Creating <strong>Topic</strong> entity which extends BaseEntity</p><pre><strong>@Entity</strong><br>public class Topic extends <strong>BaseEntity</strong> {<br><br>    private String name;<br>    private int questionCount;<br><br>    protected Topic() {<br>        super();<br>    }<br><br>    public Topic(String name, int questionCount) {<br>        this();<br>        this.name = name;<br>        this.questionCount = questionCount;<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 getQuestionCount() {<br>        return questionCount;<br>    }<br><br>    public void setQuestionCount(int questionCount) {<br>        this.questionCount = questionCount;<br>    }<br>}</pre><p>Creating <strong>TopicRepository</strong> which extends the <strong>CrudRepository</strong> interface. <br><strong>CrudRepository</strong> provides sophisticated CRUD functionality for the entity class that is being managed.</p><pre>import org.springframework.data.repository.CrudRepository;<br><br>public interface TopicRepository extends <strong>CrudRepository</strong>&lt;<strong>Topic</strong>, <strong>Long</strong>&gt;{<br><br>}</pre><p><strong>Loading database with dummy data</strong><br>Creating DatabaseLoader which will load our database with dummy data.</p><pre><strong>@Component</strong><br>public class DatabaseLoader implements <strong>ApplicationRunner</strong>{<br><br>    private TopicRepository topics;</pre><pre>    <strong>@Autowired</strong><br>    public DatabaseLoader(<strong>TopicRepository topics</strong>) {<br>        this.topics = topics;<br>    }<br><br>    @Override<br>    public void run(ApplicationArguments args) throws Exception {<br><br>        ArrayList&lt;Topic&gt; bunchOfTopic = new ArrayList&lt;Topic&gt;();<br><br>        String[] buzzWords = {&quot;Multi Threading&quot;, &quot;Inner Classes&quot;,  &quot;Collections&quot;, &quot;Generics&quot;, &quot;Development&quot;, &quot;JVM&quot;};<br><br>        //Using java 8 features (stream, lambda)<br>        IntStream.<em>range</em>(0,10).forEach(it -&gt; {<br>            String buzzWord = buzzWords[it % buzzWords.length];<br>            Topic topic = new Topic(buzzWord, (it % buzzWords.length));<br>            bunchOfTopic.add(topic);<br>        });<br><br>        topics.save(bunchOfTopic);<br>    }<br>}</pre><p><strong>Commit<br></strong>Here you can see the commit of all this changes:</p><p><a href="https://github.com/ziakhalid/spring-rest-sample/commit/4e6bf81635097e5d35cf1ba8f5317823d68a18dc">https://github.com/ziakhalid/spring-rest-sample/commit/4e6bf81635097e5d35cf1ba8f5317823d68a18dc</a></p><p><strong>HIT Run :)</strong></p><pre>http://localhost:8080/topics</pre><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TDIQXUsvEaPDvvmWKhuF9g.png" /></figure><p>If you find something to improve please let me know, I will try my best to improve this story.</p><p><em>If this article was helpful to you, please do hit the </em>💚<em> button below. Thanks!</em></p><p>See you in the next story!</p><h3>Next Article</h3><p><a href="https://medium.com/@ziatheonlyone/spring-rest-api-part-3-spring-security-basic-authentication-3fd20342745b">Part 3: Spring Security (Basic Authentication)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbc90c4a98f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring REST API -Part 1: Configuring Spring Boot project (IntelliJ IDEA + Gradle)]]></title>
            <link>https://medium.com/@ziatheonlyone/spring-rest-api-part-1-configuring-spring-boot-project-intellij-idea-gradle-385d26e01429?source=rss-fa077a28c7ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/385d26e01429</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Zia khalid]]></dc:creator>
            <pubDate>Sat, 15 Apr 2017 07:30:25 GMT</pubDate>
            <atom:updated>2017-05-05T06:47:59.503Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LDw1kqSZShS_povSJSWgGg.png" /></figure><h3>Part 1: Configuring Spring Boot project (IntelliJ IDEA + Gradle)</h3><p>In this part we are going to configure an Intellij IDEA project to use Spring Boot and left everything prepared for the next story to start developing the REST API from the beginning and learning some core concepts.</p><h4>Create Project</h4><p>We are going to start from scratch, launch<strong> Intellij IDEA </strong>and create a new 1.Gradle project &gt; java &gt; click Next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Izf8omg4LLNl4hrXchNtLg.png" /></figure><p>2. Choose GroupId and ArtifactId of your choice &gt; Next</p><p><strong>GroupId</strong> will identify your project uniquely across all projects.It is basically your project name so you can follow package name rules.</p><p><strong>ArtifactId</strong> is the name of your project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0wP7NLGZvGMdSjKJZOWOlg.png" /></figure><p>You will notice that the <em>build.gradle</em> file in your module. we require to add <strong>spring-boot-gradle-plugin</strong> and <strong>dependencies</strong> for project, i am using h2database you can use database of your choice</p><pre>...<br>buildscript {</pre><pre>  ...<br>  dependencies {<br>        classpath(&quot;<strong>org.springframework.boot:spring-boot-gradle-  plugin</strong>:$spring_plugin_version&quot;)<br>    }<br>}<br>...<br>dependencies {<br>    compile &#39;<strong>org.springframework.boot:spring-boot-starter-data-rest</strong>&#39;<br>    compile &#39;<strong>org.springframework.boot:spring-boot-starter-data-jpa</strong>&#39;<br>    compile &#39;<strong>com.h2database:h2</strong>&#39;<br>    ...<br>}</pre><p>this is how my build.gradle looks like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IOoe71fQV7bx_-ZcrdF0HA.png" /></figure><h4>Repository</h4><p>Here you have the code that we developed</p><p><a href="https://github.com/ziakhalid/spring-rest-sample">ziakhalid/spring-rest-sample</a></p><p><strong>Commit</strong></p><p><a href="https://github.com/ziakhalid/spring-rest-sample/commit/73614b85b4d1a2074f3e7ce60b04cfe068340c7e">https://github.com/ziakhalid/spring-rest-sample/commit/73614b85b4d1a2074f3e7ce60b04cfe068340c7e</a></p><p><strong>Creating Application class</strong></p><p>Creating Application(name it whatever you feel like) class, this class should have @SpringBootApplication annotation and a main method which calls a run method of SpringApplication with two argument , your class name (in this case ‘Application’) and args.</p><pre>@<strong>SpringBootApplication</strong><br>public class Application {<br><br>    public static void main(String[] args) {<br>        <strong>SpringApplication.<em>run</em></strong>(Application.class, args);<br>    }<br>}</pre><p><strong>Commit</strong></p><p><a href="https://github.com/ziakhalid/spring-rest-sample/commit/f88ee8cdb6e5aa49639627efb8b67731b9945bfa">https://github.com/ziakhalid/spring-rest-sample/commit/f88ee8cdb6e5aa49639627efb8b67731b9945bfa</a></p><h4>Run, run, run!</h4><p>Everything is ready to run this App</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*27oVIqyiG0Zo0N5JpKtA3w.png" /></figure><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DTTMSFFBUMqRR1SPDMUGhA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rxty8uDzg8B9NBJgGVan2Q.png" /></figure><pre><strong>Tomcat started on port(s): 8080 (http)</strong></pre><p>Hit port 8080 using Postman or any browser of your choice</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H0-f5_R2_b-LVSxDF2xNnA.png" /></figure><p>Here you GO ! your first API :)</p><p>If you find something to improve please let me know, I will try my best to improve this story.</p><p><em>If this article was helpful to you, please do hit the </em>💚<em> button below. Thanks!</em></p><p>See you in the next story!</p><h3>Next Article</h3><p><a href="https://medium.com/@ziatheonlyone/spring-rest-api-part-2-creating-first-api-response-dbc90c4a98f7">Part 2: Creating first API Response</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=385d26e01429" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>