<?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[Springframework - Medium]]></title>
        <description><![CDATA[Here I post my learnings from spring framework - Medium]]></description>
        <link>https://medium.com/springframework?source=rss----ad4892889193---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Springframework - Medium</title>
            <link>https://medium.com/springframework?source=rss----ad4892889193---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 05:49:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/springframework" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[12. Adding GIT release information]]></title>
            <link>https://medium.com/springframework/12-adding-git-release-information-8c8bbfa9c05b?source=rss----ad4892889193---4</link>
            <guid isPermaLink="false">https://medium.com/p/8c8bbfa9c05b</guid>
            <category><![CDATA[actuator]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[commit-id]]></category>
            <category><![CDATA[releases]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Vinay Avasthi]]></dc:creator>
            <pubDate>Tue, 19 Feb 2019 05:56:49 GMT</pubDate>
            <atom:updated>2019-02-19T05:56:49.901Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous post, we saw how to enable actuator endpoints on our spring server. Once we have done that, it is a good idea to add GIT release information to the server in order to get the information related to the currently deployed server at runtime.<br>We add the <em>git-commit-id-plugin</em> to our <em>pom.xml</em>.</p><pre>&lt;plugin&gt;<br>    &lt;groupid&gt;pl.project13.maven&lt;/groupid&gt;<br>    &lt;artifactid&gt;git-commit-id-plugin&lt;/artifactid&gt;<br>    &lt;version&gt;2.2.1&lt;/version&gt;<br>   &lt;/plugin&gt;</pre><p>The next things to do is to create a git.properties file in the resource directory of the project.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cdd2b1e1f5006e9ac678117072e38c2/href">https://medium.com/media/8cdd2b1e1f5006e9ac678117072e38c2/href</a></iframe><p>The git-commit-id is added by the maven plugin so it is a good idea to build the project using maven.</p><pre>$ mvn clean package -DskipTests</pre><p>Now we can run the server and check the <em>/manage/info</em> endpoint using <em>curl</em> command.</p><pre>$ curl -X GET <a href="http://localhost:9091/manage/info">http://localhost:9091/manage/info</a><br>{&quot;git&quot;:{&quot;branch&quot;:&quot;master&quot;,&quot;commit&quot;:{&quot;id&quot;:&quot;6fb94c0&quot;,&quot;time&quot;:1549868235.000000000}}</pre><p>This post first appeared in my <a href="https://www.springframework.in/2019/02/12-adding-git-release-information.html">Spring Framework Blog</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c8bbfa9c05b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/springframework/12-adding-git-release-information-8c8bbfa9c05b">12. Adding GIT release information</a> was originally published in <a href="https://medium.com/springframework">Springframework</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[11. Spring Actuators]]></title>
            <link>https://medium.com/springframework/11-spring-actuators-2d22b8688bed?source=rss----ad4892889193---4</link>
            <guid isPermaLink="false">https://medium.com/p/2d22b8688bed</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[actuator]]></category>
            <category><![CDATA[spring-framework]]></category>
            <dc:creator><![CDATA[Vinay Avasthi]]></dc:creator>
            <pubDate>Tue, 19 Feb 2019 05:54:30 GMT</pubDate>
            <atom:updated>2019-02-19T05:54:30.608Z</atom:updated>
            <content:encoded><![CDATA[<p>pring provides actuators that are a helpful set of tools to debug the application on runtime. Here is how to enable them. We first add actuator dependency in the pom.xml</p><pre>&lt;dependency&gt;<br>  &lt;groupid&gt;org.springframework.boot&lt;/groupid&gt;<br>  &lt;artifactid&gt;spring-boot-starter-actuator&lt;/artifactid&gt;<br>&lt;/dependency&gt;</pre><p>Now we define a prefix for all the actuator endpoints. We add the following line into the <em>application.properties</em> file. This enables all the actuator endpoints. We can enable specific endpoints by adding a comma delimited list of endpoints. We also deploy management endpoint on a separate port so that we can block its access from something like ELB.</p><pre>management.endpoints.web.base-path=/manage<br>management.server.port=9091<br>management.endpoints.web.exposure.include=*</pre><p>Since we already have a security filter defined, we need to exempt health and info endpoint from security check. We add the following URLs int he SecurityConfiguration configure method.</p><pre>@Override<br>    public void configure(WebSecurity web) throws Exception {<br>        web.ignoring().antMatchers(&quot;/manage/health&quot;);<br>        web.ignoring().antMatchers(&quot;/manage/info&quot;);<br>        web.ignoring().antMatchers(&quot;/webjars/**&quot;);<br>        web.ignoring().antMatchers(&quot;/error&quot;);<br>        web.ignoring().antMatchers(&quot;/swagger-ui.html&quot;);<br>        web.ignoring().antMatchers(&quot;/v2/api-docs/**&quot;);<br>        web.ignoring().antMatchers(&quot;/swagger-resources/**&quot;);<br>    }</pre><p>Here we have added paths related to <em>error</em>, <em>actuator</em>, and <em>swagger.</em><br>This enables actuator endpoints for our server. We can query these endpoints and following is the sample response.</p><pre>$ curl -X GET <a href="http://localhost:9091/manage/health">http://localhost:9091/manage/health</a><br>{&quot;status&quot;:&quot;UP&quot;}</pre><p>This post first appeared in my <a href="https://www.springframework.in/2019/02/11-spring-actuators.html">Spring Framework blog here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d22b8688bed" width="1" height="1" alt=""><hr><p><a href="https://medium.com/springframework/11-spring-actuators-2d22b8688bed">11. Spring Actuators</a> was originally published in <a href="https://medium.com/springframework">Springframework</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10. Application with multiple data sources]]></title>
            <link>https://medium.com/springframework/10-application-with-multiple-data-sources-95f1b4beed3f?source=rss----ad4892889193---4</link>
            <guid isPermaLink="false">https://medium.com/p/95f1b4beed3f</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[multiple-datasources]]></category>
            <dc:creator><![CDATA[Vinay Avasthi]]></dc:creator>
            <pubDate>Tue, 19 Feb 2019 04:22:18 GMT</pubDate>
            <atom:updated>2019-02-19T04:22:17.915Z</atom:updated>
            <content:encoded><![CDATA[<p>Many times it is a practical requirement to have multiple databases for a single application. These databases could be at different locations on the cloud and different entities in your application may be dealing with these databases.<br>Multi-tenancy is a great requirement when multiple data sources are needed. Many tenants may insist on having their own databases. Here we present how we can configure the spring application to interact with multiple databases.<br>The first step is to look at our <em>application.properties</em> file. We have a list of properties defined for the default dataSource which we will need to replicate for our second database. Let’s assume we are going to use two data sources, the first one is called the<em> user</em> and the second one is called <em>other</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4e24497508d01540b8220c20547a5c6/href">https://medium.com/media/a4e24497508d01540b8220c20547a5c6/href</a></iframe><p>As we can see above, we have replicated all the data source properties and given it a new prefix, <em>other</em>. Now, these two databases could have completely independent settings. They could point to totally different databases. Each of these properties could be configured to completely different settings. Here we have just changed the name of the <em>database</em>, <em>username</em>, <em>password</em>.<br>To make this work. we will have to split the repositories and the entity objects for each of the data sources. Here we create the following hierarchy of packages for each of the data sources.</p><pre>src/main/java<br>- in.springframework.blog.tutorials<br> - user<br>    - domain<br>    - repository<br>  - other<br>    - domain<br>    - repository</pre><p>As we can see for each of the data sources, we have a domain package that would contain the entities and a repository package that would contain the repository class. This is needed so that each of the entity managers only searches for its own classes.<br>Now we need to define a configuration of each of the data sources that we have defined. The first data source will contain <em>the user</em> table and will also be the primary data source.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cabc9b00e48c9c0826d8a19e03c81f2/href">https://medium.com/media/4cabc9b00e48c9c0826d8a19e03c81f2/href</a></iframe><p>As we can see in the class above, it uses all the properties prefixed with <em>spring.datasource</em> and scans directories related to the user data source. Now let’s look at the configuration for <em>other</em> data source.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdabbc9d6c8b01ac1f87969dc3324f9c/href">https://medium.com/media/fdabbc9d6c8b01ac1f87969dc3324f9c/href</a></iframe><p>The things to note in the <em>other</em> data source is that the <em>@Primary</em> annotation doesn’t exist because we can have only one set of primary beans of a type. Also, the directories to be searched are for the <em>other</em> data source’s <em>domain</em> and <em>repository</em> objects.<br>At this time we also move the old <em>User</em> and <em>UserRepository</em> classes to their respective subdirectories. We also create <em>Other</em> and <em>OtherRepository</em> classes in their respective subdirectories. We also change <em>CrudRepository</em> to <em>JpaRepository</em> in each of the repository classes.<br>Now, our application is set up to use two different data sources and we can verify that by running the application. Since we have set <em>ddl-auto</em> property to <em>update, </em>it should create a new schedule when the application is run.</p><pre>$ mysql -u tutorial -ptutorial123 tutorial<br>mysql: [Warning] Using a password on the command line interface can be insecure.<br>Reading table information for completion of table and column names<br>You can turn off this feature to get a quicker startup with -A</pre><pre>Welcome to the MySQL monitor.  Commands end with ; or \g.<br>Your MySQL connection id is 115<br>Server version: 8.0.12 Homebrew</pre><pre>Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.</pre><pre>Oracle is a registered trademark of Oracle Corporation and/or its<br>affiliates. Other names may be trademarks of their respective<br>owners.</pre><pre>Type &#39;help;&#39; or &#39;\h&#39; for help. Type &#39;\c&#39; to clear the current input statement.</pre><pre>mysql&gt; show tables;<br>+--------------------+<br>| Tables_in_tutorial |<br>+--------------------+<br>| hibernate_sequence |<br>| user               |<br>+--------------------+<br>2 rows in set (0.00 sec)</pre><pre>mysql&gt; desc user;<br>+------------+--------------+------+-----+---------+-------+<br>| Field      | Type         | Null | Key | Default | Extra |<br>+------------+--------------+------+-----+---------+-------+<br>| id         | bigint(20)   | NO   | PRI | NULL    |       |<br>| email      | varchar(255) | YES  | UNI | NULL    |       |<br>| fullname   | varchar(255) | YES  |     | NULL    |       |<br>| password   | varchar(255) | YES  |     | NULL    |       |<br>| username   | varchar(255) | YES  | UNI | NULL    |       |<br>| auth_token | varchar(255) | YES  | UNI | NULL    |       |<br>| expiry     | datetime     | YES  |     | NULL    |       |<br>| mask       | bigint(20)   | NO   |     | NULL    |       |<br>| authToken  | varchar(255) | YES  |     | NULL    |       |<br>+------------+--------------+------+-----+---------+-------+<br>9 rows in set (0.00 sec)</pre><pre>$ mysql -u other -pother123 other<br>mysql: [Warning] Using a password on the command line interface can be insecure.<br>Reading table information for completion of table and column names<br>You can turn off this feature to get a quicker startup with -A</pre><pre>Welcome to the MySQL monitor.  Commands end with ; or \g.<br>Your MySQL connection id is 116<br>Server version: 8.0.12 Homebrew</pre><pre>Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.</pre><pre>Oracle is a registered trademark of Oracle Corporation and/or its<br>affiliates. Other names may be trademarks of their respective<br>owners.</pre><pre>Type &#39;help;&#39; or &#39;\h&#39; for help. Type &#39;\c&#39; to clear the current input statement.</pre><pre>mysql&gt; show tables;<br>+--------------------+<br>| Tables_in_other    |<br>+--------------------+<br>| hibernate_sequence |<br>| other              |<br>+--------------------+<br>2 rows in set (0.00 sec)</pre><pre>mysql&gt; desc other<br>    -&gt; ;<br>+-----------+--------------+------+-----+---------+-------+<br>| Field     | Type         | Null | Key | Default | Extra |<br>+-----------+--------------+------+-----+---------+-------+<br>| id        | bigint(20)   | NO   | PRI | NULL    |       |<br>| otherData | varchar(255) | YES  |     | NULL    |       |<br>+-----------+--------------+------+-----+---------+-------+<br>2 rows in set (0.00 sec)</pre><p>The source code for this tutorial is available at git repository as <a href="https://github.com/vavasthi/springblog/tree/v1.2">v1.2</a>. This post first appeared on my <a href="https://www.springframework.in/2019/02/10-application-with-multiple-datasources.html">Spring Framework blog here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95f1b4beed3f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/springframework/10-application-with-multiple-data-sources-95f1b4beed3f">10. Application with multiple data sources</a> was originally published in <a href="https://medium.com/springframework">Springframework</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[9. Role-based data access]]></title>
            <link>https://medium.com/springframework/9-role-based-data-access-a115acedc86b?source=rss----ad4892889193---4</link>
            <guid isPermaLink="false">https://medium.com/p/a115acedc86b</guid>
            <category><![CDATA[post-filters]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[conditional]]></category>
            <category><![CDATA[postauthorize]]></category>
            <dc:creator><![CDATA[Vinay Avasthi]]></dc:creator>
            <pubDate>Tue, 19 Feb 2019 04:17:50 GMT</pubDate>
            <atom:updated>2019-02-19T04:17:50.837Z</atom:updated>
            <content:encoded><![CDATA[<p>Many times we have a need to return data from an endpoint based on the role. Spring framework provider easy mechanism for us to be able to do that. Let’s take an example. In the previous example, we want to add a <em>GET</em> method in <em>UserEndpoint</em> that returns all the users. For any safe system, we want to return all the users if the role is <em>ADMIN</em> but if the role is <em>USER</em> then we want to return only that particular user. We don’t want to write multiple methods for that purpose.</p><pre>@RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)<br>    @PostFilter(&quot;hasAuthority(&#39;ADMIN&#39;) or filterObject.authToken == authentication.name&quot;)<br>    public Iterable getUsers() {<br>        Iterable users = userRepository.findAll();<br>        return users;<br>    }</pre><p>The method is described above. As we can see it is an extremely simple method, it calls <em>findAll</em> method on the repository which will return all the valid user records and returns an <em>Iterable</em> collection back. The interesting aspect of this method is in the <em>@PostFilter</em> annotation. Let’s try to understand the annotation. The first condition is <em>hasAuthority(‘ADMIN’)</em>. It implies that if the authenticated role is <em>ADMIN</em> then return the records as it is. The next bit of the filter condition uses an object called <em>filterObject</em>. This is an automatically defined expression that we can use in <em>@PostAuthorize</em> filter. A complete list of all the expressions exists <a href="https://docs.spring.io/spring-security/site/docs/current/reference/html/authorization.html#el-common-built-in">here</a>. The expression <em>filterObject</em> is used for each element of a collection that is returned from the endpoint. Since we know that when this endpoint is called, we would only be authenticating using <em>authToken</em>, the name of authentication in security context is set to the token itself. We can verify this in the code in <em>AuthenticationFilter</em> class.</p><pre>else {</pre><pre>                Optional token = getOptionalHeader(httpRequest,&quot;token&quot;);<br>                TokenPrincipal authTokenPrincipal = new TokenPrincipal(token);<br>                processTokenAuthentication(authTokenPrincipal);<br>            }</pre><p>The code fragment described above creates a TokenPrincipal object with the token as its name. That is the reason we have the condition <em>filterObject.authToken == authentication.name</em>. Taking the complete condition of <em>@PostFilter</em> we can see that the condition implies that <strong>return everything unconditionally if the role is <em>ADMIN</em> otherwise return the users with authToken as the currently authenticated user.</strong><br>We have two users defined on the system. One has a role of the user and the other has a role of admin. Here are the examples of what happens when we call the endpoint with both of these users.<br>The first example is with a user with role <em>USER</em>.</p><pre>$ curl -X GET &quot;http://localhost:8081/user&quot; -H &quot;accept: application/json&quot; -H &quot;token: 3d47912d-73a0-4c4c-95e6-0486273d6221-28fa4f38-0f1b-4740-8e1d-3228288de631&quot; | python -m json.tool<br>[<br>    {<br>        &quot;authToken&quot;: &quot;3d47912d-73a0-4c4c-95e6-0486273d6221-28fa4f38-0f1b-4740-8e1d-3228288de631&quot;,<br>        &quot;email&quot;: &quot;user@springframework.in&quot;,<br>        &quot;expiry&quot;: 1548345909000,<br>        &quot;fullname&quot;: &quot;User&quot;,<br>        &quot;id&quot;: 2,<br>        &quot;mask&quot;: 1,<br>        &quot;password&quot;: &quot;User123&quot;,<br>        &quot;username&quot;: &quot;user&quot;<br>    }<br>]</pre><p>The second example is with a user with role <em>ADMIN</em>.</p><pre>$ curl -X GET &quot;http://localhost:8081/user&quot; -H &quot;accept: application/json&quot; -H &quot;token: a137dd09-11e4-4dcf-a141-0b235d39a505-60d43bf4-3674-4248-be1d-c2669f14589f&quot; | python -m json.tool<br>[<br>    {<br>        &quot;authToken&quot;: &quot;3d47912d-73a0-4c4c-95e6-0486273d6221-28fa4f38-0f1b-4740-8e1d-3228288de631&quot;,<br>        &quot;email&quot;: &quot;user@springframework.in&quot;,<br>        &quot;expiry&quot;: 1548345909000,<br>        &quot;fullname&quot;: &quot;User&quot;,<br>        &quot;id&quot;: 2,<br>        &quot;mask&quot;: 1,<br>        &quot;password&quot;: &quot;User123&quot;,<br>        &quot;username&quot;: &quot;user&quot;<br>    },<br>    {<br>        &quot;authToken&quot;: &quot;a137dd09-11e4-4dcf-a141-0b235d39a505-60d43bf4-3674-4248-be1d-c2669f14589f&quot;,<br>        &quot;email&quot;: &quot;admin@springframework.in&quot;,                                                                                         <br>        &quot;expiry&quot;: 1548348263000,                                                                                                     <br>        &quot;fullname&quot;: &quot;Administrator&quot;,                                                                                                 <br>        &quot;id&quot;: 3,                                                                                                                     <br>        &quot;mask&quot;: 4,                                                                                                                   <br>        &quot;password&quot;: &quot;Admin123&quot;,                                                                                                      <br>        &quot;username&quot;: &quot;admin&quot;                                                                                                          <br>    }<br>]</pre><p>As we can see above, the call with the role USER only returns the object related to that particular user while the call with the role returns all the users present in the system. This is how we can achieve role based object access without writing multiple endpoints.</p><p>This post first appeared on my Spring Framework blog <a href="https://www.springframework.in/2019/01/9-role-based-data-access.html">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a115acedc86b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/springframework/9-role-based-data-access-a115acedc86b">9. Role-based data access</a> was originally published in <a href="https://medium.com/springframework">Springframework</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[8. That little matter of creating a user]]></title>
            <link>https://medium.com/springframework/8-that-little-matter-of-creating-a-user-1e0df57d4132?source=rss----ad4892889193---4</link>
            <guid isPermaLink="false">https://medium.com/p/1e0df57d4132</guid>
            <category><![CDATA[bypass]]></category>
            <category><![CDATA[users]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[create]]></category>
            <dc:creator><![CDATA[Vinay Avasthi]]></dc:creator>
            <pubDate>Tue, 19 Feb 2019 04:15:45 GMT</pubDate>
            <atom:updated>2019-02-19T04:15:44.979Z</atom:updated>
            <content:encoded><![CDATA[<p>Now that our simplified authentication system is in place, we are faced with the little matter of how to create a new user. Since we don’t have a <em>username</em>, <em>password</em>, or <em>token</em> we can’t really create a new user.<br>To accomplish that, we need to make some modifications to our <em>AuthenticationFilter</em>. In the <em>doFilter</em> method, we add a special <em>if</em> block to take care of user creation.</p><pre>if (httpRequest.getRequestURI().toString().equals(&quot;/user&quot;) &amp;&amp; httpRequest.getMethod().equals(&quot;POST&quot;)) {</pre><pre>                Optional username = getOptionalHeader(httpRequest,&quot;username&quot;);<br>                UsernamePasswordPrincipal usernamePasswordPrincipal = new UsernamePasswordPrincipal(username, username, true);<br>                processUsernameAuthentication(usernamePasswordPrincipal);<br>            }<br>            else if (httpRequest.getRequestURI().toString().equals(&quot;/authenticate&quot;) &amp;&amp; httpRequest.getMethod().equals(&quot;POST&quot;)) {</pre><pre>                Optional username = getOptionalHeader(httpRequest,&quot;username&quot;);<br>                Optional password = getOptionalHeader(httpRequest,&quot;password&quot;);<br>                UsernamePasswordPrincipal usernamePasswordPrincipal = new UsernamePasswordPrincipal(username, password);<br>                processUsernameAuthentication(usernamePasswordPrincipal);<br>            }</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46e81a01404fbe286d60e014696cdfa4/href">https://medium.com/media/46e81a01404fbe286d60e014696cdfa4/href</a></iframe><p>As we can see the code fragment, if the call is made to <em>/user</em> endpoint with <em>POST</em> method, we look for a <em>username</em> header and trigger spring authentication. We also need to make a change in the <em>UsernamePasswordPrincipal</em> to take a flag that would tell us if the user is a new user or existing user.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6603bd71c2041a9b94d2303a0cba0d9e/href">https://medium.com/media/6603bd71c2041a9b94d2303a0cba0d9e/href</a></iframe><p>Now that we have modified the principal and filter, we need to handle this in the provider. The provider that gets invoked for username and password authentication is <em>UsernamePasswordAuthenticationProvider</em>.<br>As we can see in the provider’s <em>authenticate</em> method, we have added an if block that checks if this is a new user. In case it is a new user, we authenticate this user with a role <em>NEWUSER</em>. The create user endpoint is only allowed to be called for a role <em>NEWUSER</em>.<br>Now that we have stitched the path for authentication of a new user to create user endpoint, we can see the endpoint itself.</p><pre>@RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)<br>    @PreAuthorize(MyConstants.ANNOTATION_ROLE_NEWUSER)<br>    public Optional createUser(@RequestHeader(value=&quot;username&quot;) String username, @RequestBody User user) {<br>        user.setMask(Role.USER.ordinal());<br>        User storedUser = userRepository.save(user);<br>        storedUser.setPassword(null);<br>        return Optional.of(storedUser);<br>    }</pre><p>As we can see, we have a <em>@PreAuthorize</em> added with <em>NEWUSER</em> role. We also set the role of the user to <em>the USER</em>. Before returning the response, we set the password to null.<br>This fixes our service to allow the creation of a new user. The <a href="https://github.com/vavasthi/springblog/tree/v1.1">complete</a> code is available tagged as v1.1 for this and previous posts.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12f9542bcbd47f91b1b7f5a39448d0cd/href">https://medium.com/media/12f9542bcbd47f91b1b7f5a39448d0cd/href</a></iframe><p>This post first appeared on <a href="https://www.springframework.in/2019/01/8-that-little-matter-of-creating-user.html">my blog here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e0df57d4132" width="1" height="1" alt=""><hr><p><a href="https://medium.com/springframework/8-that-little-matter-of-creating-a-user-1e0df57d4132">8. That little matter of creating a user</a> was originally published in <a href="https://medium.com/springframework">Springframework</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[7. Enabling Swagger]]></title>
            <link>https://medium.com/springframework/7-enabling-swagger-2c2348bc4728?source=rss----ad4892889193---4</link>
            <guid isPermaLink="false">https://medium.com/p/2c2348bc4728</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[springfox]]></category>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[swagger]]></category>
            <dc:creator><![CDATA[Vinay Avasthi]]></dc:creator>
            <pubDate>Tue, 19 Feb 2019 04:11:03 GMT</pubDate>
            <atom:updated>2019-02-19T04:11:03.405Z</atom:updated>
            <content:encoded><![CDATA[<p>Before we proceed any further, let’s enable swagger on our service so that testing it becomes easy. The first step is to add springfox dependencies.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b000051f518d88fbcc87d6113fd78e5/href">https://medium.com/media/3b000051f518d88fbcc87d6113fd78e5/href</a></iframe><p>Now that we have dependencies added, we need to define a swagger configuration. Most of our endpoint will need to have a token passed as HTTP header, we need to configure our swagger configuration to facilitate that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1e17c33490b85b94db87e38ee8aef09/href">https://medium.com/media/c1e17c33490b85b94db87e38ee8aef09/href</a></iframe><p>We create a swagger configuration file as defined above. The <em>globalOperationParameters</em> clause dictates to swagger that each endpoint will have a parameter named <em>token </em>of type <em>header</em> and is mandatory. We know there is two endpoint that will not have a <em>token</em> header but we can just pass some dummy values. We can also make it non-mandatory if we so wish.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69993f7f84a071ad505f02e017c5b442/href">https://medium.com/media/69993f7f84a071ad505f02e017c5b442/href</a></iframe><p>We also modify authentication endpoint to take a <em>username</em> and <em>password</em> header for authentication endpoint. That is defined in the <em>AuthenticateEndpoint</em> as above. Look at the <em>@RequestHeader</em> parameter passed in the <em>login</em> method of the endpoint.</p><pre>web.ignoring().antMatchers(&quot;/swagger-ui.html&quot;);<br>        web.ignoring().antMatchers(&quot;/v2/api-docs/**&quot;);<br>        web.ignoring().antMatchers(&quot;/swagger-resources/**&quot;);</pre><p>Also, make sure that <em>SecurityConfiguration.java</em> that we had defined in one of the previous posts a list of swagger related URLs were made part of an exception list so that these do not go through authentication filter.<br>Now if we rebuild the server and run it and visit <a href="http://localhost:8081/swagger-ui.html"><em>http://localhost:8081/swagger-ui.html</em></a> we see the swagger page with all the API endpoints listed there. Here is the screenshot of the swagger UI as seen on visiting above URL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*gMtOpv1OGbgNkhhH.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c2348bc4728" width="1" height="1" alt=""><hr><p><a href="https://medium.com/springframework/7-enabling-swagger-2c2348bc4728">7. Enabling Swagger</a> was originally published in <a href="https://medium.com/springframework">Springframework</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[6. Introducing Spring Security]]></title>
            <link>https://medium.com/springframework/6-introducing-spring-security-f57b57918344?source=rss----ad4892889193---4</link>
            <guid isPermaLink="false">https://medium.com/p/f57b57918344</guid>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[security-context]]></category>
            <dc:creator><![CDATA[Vinay Avasthi]]></dc:creator>
            <pubDate>Tue, 19 Feb 2019 04:05:22 GMT</pubDate>
            <atom:updated>2019-02-19T04:05:22.123Z</atom:updated>
            <content:encoded><![CDATA[<p>If the web services that we are building require any level of authentication and authorization, it is better to understand Spring security context. Services that are properly built with security context can implement a better level of security at each method and endpoint level.<br>We want to handle all the security, authentication and, authorization related code in a single block so that managing it becomes easier.<br>The first step that we need to do is to add security dependencies in the pom.xml.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1d3df404b510f5b69e1ed38c5e09bf9/href">https://medium.com/media/b1d3df404b510f5b69e1ed38c5e09bf9/href</a></iframe><p>For authentication and authorization to make sense, we need to have a concept of a Role within the system. The roles are required to authorize the users for specific purposes. We define a set of roles in the form of a bitmask defined as an enum.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ba1d810f371100557dced84373c9668/href">https://medium.com/media/2ba1d810f371100557dced84373c9668/href</a></iframe><p>Now that we have defined Roles, we need to add few fields in our <em>User</em> class. We add a field <em>mask</em> for holding allowed roles and two different fields for <em>authToken</em> and <em>expiry</em>. We also add an index in the User entity.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c623722cb6b61dacf099d7da1a6fe16a/href">https://medium.com/media/c623722cb6b61dacf099d7da1a6fe16a/href</a></iframe><p>We also need to add a class that implements GrantedAuthority interface. An authority in the spring security system is represented by a string and we use the Role enum name as the authority in the system.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e66d9ddee51d069991835f57973bf71/href">https://medium.com/media/6e66d9ddee51d069991835f57973bf71/href</a></iframe><p>We probably need to have two different types of authentication and authorization within the server. The first authentication and authorization will work with username and password and the second one will work with the token. Spring security requires two different entities to be defined for authentication and authorization. We need a Principal and a Provider class each for username and token authentication and authorization. Let’s first look at the class required for authentication using username and password. A principal is nothing but the abstraction of credentials that is flowing through spring security. We define it as below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1f9c2b2f5e08f51c9ba1f207bba0733/href">https://medium.com/media/d1f9c2b2f5e08f51c9ba1f207bba0733/href</a></iframe><p>A provider is a class that provides the authentication and authorization functionality for a particular type. The username and password provider is defined as below. As we can see, the provider class extracts the credentials from the Principal and then makes sure the password is correct for the username. It also populates the list of roles granted to the user in the form of Authority.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13a548745ba523fc576ea11a3e9cfdff/href">https://medium.com/media/13a548745ba523fc576ea11a3e9cfdff/href</a></iframe><p>Similarly, we define a Token principal. This principal just contains the token value that is received from the user.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/547dfb080a610e89edb9c307e33957f7/href">https://medium.com/media/547dfb080a610e89edb9c307e33957f7/href</a></iframe><p>We also define a token provider. The token provider looks up the user from the database by querying it from token and authenticates the user. In this example, we are making an implicit assumption that a token will be unique across all the users. If that were not to be the case, we will also have to pass the username or some other identifier for the user along with the token during authentication.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/faaf8ed0b3d274bcd678726682e72a67/href">https://medium.com/media/faaf8ed0b3d274bcd678726682e72a67/href</a></iframe><p>We also define a class RequestContext that will contain a set of thread local variables so that once authenticated, we will not need to look up the user details from the database. We will only need to hit the database in cases where we need to update the record in <em>the User</em> table.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9085406bf9cd2848c54dc88e7efb184/href">https://medium.com/media/c9085406bf9cd2848c54dc88e7efb184/href</a></iframe><p>We can see in both provider classes, after successful authentication of the user, the User is set into the thread local so that we can use it within the thread boundaries of that request.<br>Now the providers and principals are in place, we need to start using them. Rather than using them on a case to case basis, the best way is to define a filter which applies on each request and authentication and authorization can be done on all requests.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4df5be9a8ed6712230b0229617a4052c/href">https://medium.com/media/4df5be9a8ed6712230b0229617a4052c/href</a></iframe><p>AuthenticationFilter provides the <em>doFilter</em> method which is called for each incoming request. As we can see within the doFilter method, if we receive a <em>POST</em> request to <em>/authenticate</em> URL we assume that to be a username and password authentication and we process it as a username and password authentication, in all other cases, it is assumed to be a token-based authentication. All the three parameters, username, password, and token are expected to be passed as headers.<br>Now we need to plug everything in so that it is called by the system. For that, we need to define a security configuration.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ff63de1be995fef25939cbe00f79f78/href">https://medium.com/media/9ff63de1be995fef25939cbe00f79f78/href</a></iframe><p>The <em>SecurityConfiguration</em> class is defined by extending <em>WebSecurityConfigurerAdapter</em> class. We override a few sets of methods. The first method defines a set of authentication providers that are available to the system.</p><pre>@Override<br>    protected void configure(AuthenticationManagerBuilder auth) throws Exception {<br>        auth.authenticationProvider(tokenAuthenticationProvider());<br>        auth.authenticationProvider(usernamePasswordAuthenticationProvider());<br>    }</pre><p>The second method defines a set of URLs that would be ignored by the security system.</p><pre>@Override<br>    public void configure(WebSecurity web) throws Exception {<br>        web.ignoring().antMatchers(&quot;/manage/health&quot;);<br>        web.ignoring().antMatchers(&quot;/swagger-ui.html&quot;);<br>        web.ignoring().antMatchers(&quot;/webjars/**&quot;);<br>        web.ignoring().antMatchers(&quot;/v2/api-docs/**&quot;);<br>        web.ignoring().antMatchers(&quot;/error&quot;);<br>        web.ignoring().antMatchers(&quot;/swagger-resources/**&quot;);<br>    }</pre><p>The third method defines the security rules for all the requests.</p><pre>@Override<br>    protected void configure(HttpSecurity http) throws Exception {<br>        http.csrf().disable().<br>                sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).<br>                and().<br>                authorizeRequests().<br>                antMatchers(actuatorEndpoints()).hasAuthority(Role.ADMIN.name()).<br>                anyRequest().authenticated().<br>                and().<br>                anonymous().disable().<br>                exceptionHandling().authenticationEntryPoint(unauthorizedEntryPoint());;</pre><pre>        http.addFilterBefore(new AuthenticationFilter(authenticationManager()), BasicAuthenticationFilter.class);<br>    }</pre><p>The configuration first disables <em>CSRF</em> and then sets a session management policy. After that, it declares that all the actuator endpoints need to be authenticated by a user having the ADMIN roles. Then all other users need to be authenticated. With this, every request coming into the system will be automatically authenticated and authorized. Now we can annotate our endpoints with specific roles so that unauthorized users can not make the calls. For example, we add the following annotation to our endpoint that we had defined earlier.</p><pre>@PreAuthorize(&quot;hasAuthority(&#39;USER&#39;)&quot;)</pre><p>This annotation implies that a user with the role of USER can only call this endpoint. Any other user would not be able to call this endpoint.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2cd9f21d1781f3109135cc5ca46fc5c/href">https://medium.com/media/d2cd9f21d1781f3109135cc5ca46fc5c/href</a></iframe><p>This is also our AuthenticationEndpoint. This will need to be called when a user wants to login using a username and password. This now provides us with a functioning service with spring security enabled. In future posts, we will provide more details on it. The complete code for this post is available in GitHub repository with version 1.0. Click <a href="https://github.com/vavasthi/springblog/releases/tag/v1.0">here</a> to download it.</p><p>This post appeared on my <a href="https://www.springframework.in/2019/01/6-introducing-spring-security.html">spring framework blog here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f57b57918344" width="1" height="1" alt=""><hr><p><a href="https://medium.com/springframework/6-introducing-spring-security-f57b57918344">6. Introducing Spring Security</a> was originally published in <a href="https://medium.com/springframework">Springframework</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5. Replacing tomcat with jetty]]></title>
            <link>https://medium.com/springframework/5-replacing-tomcat-with-jetty-fd2b3a4d8a80?source=rss----ad4892889193---4</link>
            <guid isPermaLink="false">https://medium.com/p/fd2b3a4d8a80</guid>
            <category><![CDATA[jetty]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-framework]]></category>
            <dc:creator><![CDATA[Vinay Avasthi]]></dc:creator>
            <pubDate>Mon, 18 Feb 2019 09:53:38 GMT</pubDate>
            <atom:updated>2019-02-18T09:53:38.393Z</atom:updated>
            <content:encoded><![CDATA[<p>By default when we run spring boot application, it runs a tomcat server. I have personally found tomcat too heavyweight and I prefer to use Jetty for writing a webservices backend.</p><pre>2018-12-19 10:54:08.403  INFO 16029 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)</pre><pre>2018-12-19 10:54:08.424  INFO 16029 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]</pre><pre>2018-12-19 10:54:08.424  INFO 16029 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/9.0.12</pre><p>To replace tomcat with Jetty, we need to make a couple of changes. The first step is to add Jetty dependencies in the pom.xml.</p><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-jetty&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.eclipse.jetty&lt;/groupId&gt;<br>   &lt;artifactId&gt;jetty-deploy&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.eclipse.jetty&lt;/groupId&gt;<br>   &lt;artifactId&gt;jetty-rewrite&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.eclipse.jetty&lt;/groupId&gt;<br>   &lt;artifactId&gt;jetty-util&lt;/artifactId&gt;<br>  &lt;/dependency&gt;</pre><p>Since springframework boot bom automatically includes a dependency on tomcat in spring-boot-starter-web, we specifically need to exclude it. So we change</p><pre>&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;</pre><p>to</p><pre>&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;exclusions&gt;<br>    &lt;exclusion&gt;<br>     &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>     &lt;artifactId&gt;spring-boot-starter-tomcat&lt;/artifactId&gt;<br>    &lt;/exclusion&gt;<br>   &lt;/exclusions&gt;<br>  &lt;/dependency&gt;</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7dbbb67199330fddb5a7e79aa3ad0829/href">https://medium.com/media/7dbbb67199330fddb5a7e79aa3ad0829/href</a></iframe><p>The next step is to add a customizer for jetty which will allow us to set some parameters related to Jetty.<br>As we can see the customizer uses a set of variables that we can override in <em>application.properties</em> file to modify the behavior of the server.</p><pre>2018-12-19 11:06:44.577  INFO 16219 --- [           main] o.e.jetty.server.AbstractConnector       : Started ServerConnector@42ebece0{HTTP/1.1,[http/1.1]}{0.0.0.0:8081}<br>2018-12-19 11:06:44.580  INFO 16219 --- [           main] o.s.b.web.embedded.jetty.JettyWebServer  : Jetty started on port(s) 8081 (http/1.1) with context path &#39;&#39;</pre><p>Now the logs clearly show that in place of tomcat, it is running jetty.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd2b3a4d8a80" width="1" height="1" alt=""><hr><p><a href="https://medium.com/springframework/5-replacing-tomcat-with-jetty-fd2b3a4d8a80">5. Replacing tomcat with jetty</a> was originally published in <a href="https://medium.com/springframework">Springframework</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[4. More on CrudRepository]]></title>
            <link>https://medium.com/springframework/4-more-on-crudrepository-c3886d495d7b?source=rss----ad4892889193---4</link>
            <guid isPermaLink="false">https://medium.com/p/c3886d495d7b</guid>
            <category><![CDATA[crudrepository]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[endpoints]]></category>
            <dc:creator><![CDATA[Vinay Avasthi]]></dc:creator>
            <pubDate>Mon, 18 Feb 2019 09:51:44 GMT</pubDate>
            <atom:updated>2019-02-18T09:51:44.757Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous post, we used the <em>CrudRepository</em> interface. We only used the methods already provided by the interface. In this post, we look at how we can extend the interface with custom queries. Let’s go back to our UserEndpoint. In the GET method, we can currently get the details of a user given his <em>id</em>. This is an impractical scenario. Most users’ would not know what their <em>id</em> is. It is an internal identifier generated by our service and it makes no sense for our users.<br>Let’s say we want to extend the existing GET/DELETE interface to allow query by id, username, and email address. Since we intend to query the table using the username and email columns, we need some kind of index on those columns. Since these fields are expected to be unique, we put a unique constraint in the @Table annotation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11997bc153ffd0c4978bb3e6c3078eda/href">https://medium.com/media/11997bc153ffd0c4978bb3e6c3078eda/href</a></iframe><p>When this change is deployed, the corresponding changes in database schema would be as below.</p><pre>mysql&gt; desc user;<br>+----------+--------------+------+-----+---------+-------+<br>| Field    | Type         | Null | Key | Default | Extra |<br>+----------+--------------+------+-----+---------+-------+<br>| id       | bigint(20)   | NO   | PRI | NULL    |       |<br>| email    | varchar(255) | YES  | UNI | NULL    |       |<br>| fullname | varchar(255) | YES  |     | NULL    |       |<br>| password | varchar(255) | YES  |     | NULL    |       |<br>| username | varchar(255) | YES  | UNI | NULL    |       |<br>+----------+--------------+------+-----+---------+-------+<br>5 rows in set (0.01 sec)<br>mysql&gt; show create table user\G<br>*************************** 1. row ***************************<br>       Table: user<br>Create Table: CREATE TABLE `user` (<br>  `id` bigint(20) NOT NULL,<br>  `email` varchar(255) DEFAULT NULL,<br>  `fullname` varchar(255) DEFAULT NULL,<br>  `password` varchar(255) DEFAULT NULL,<br>  `username` varchar(255) DEFAULT NULL,<br>  PRIMARY KEY (`id`),<br>  UNIQUE KEY `uq_email` (`email`),<br>  UNIQUE KEY `uq_username` (`username`)<br>) ENGINE=MyISAM DEFAULT CHARSET=utf8<br>1 row in set (0.00 sec)</pre><p>As we can see from the schema both the columns have unique constraints attached to them. The next step is to add methods in the UserRepository.java to query the user for a given username or email.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee702aca9cd761804a7f38390332a342/href">https://medium.com/media/ee702aca9cd761804a7f38390332a342/href</a></iframe><p>Now that we have all the required changes in place, we modify the <em>UserEndpoint</em> to handle the changes. We first create a private method <em>retrieveUser</em> which will retrieve a user from repository given an id, username or email.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc931a554c0e276093b9824609b2b005/href">https://medium.com/media/bc931a554c0e276093b9824609b2b005/href</a></iframe><p>In this method, we take an argument of type String, we first assume it to be the id if id fails we try with email and then with the username.</p><pre>$ curl -X GET <a href="http://localhost:8080/user/jdoe@example.com">http://localhost:8080/user/jdoe@example.com</a><br>{&quot;id&quot;:6,&quot;fullname&quot;:&quot;John Doe&quot;,&quot;username&quot;:&quot;jdoe&quot;,&quot;password&quot;:&quot;JohnDoe123&quot;,&quot;email&quot;:&quot;jdoe@example.com&quot;}</pre><p>Here is the complete UserEndpoint class after modification.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a7cc6c1521e3fe872ad73059c2eec55/href">https://medium.com/media/6a7cc6c1521e3fe872ad73059c2eec55/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3886d495d7b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/springframework/4-more-on-crudrepository-c3886d495d7b">4. More on CrudRepository</a> was originally published in <a href="https://medium.com/springframework">Springframework</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3. All the methods in endpoint]]></title>
            <link>https://medium.com/springframework/3-all-the-methods-in-endpoint-22018c02d1de?source=rss----ad4892889193---4</link>
            <guid isPermaLink="false">https://medium.com/p/22018c02d1de</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[endpoints]]></category>
            <dc:creator><![CDATA[Vinay Avasthi]]></dc:creator>
            <pubDate>Mon, 18 Feb 2019 09:47:55 GMT</pubDate>
            <atom:updated>2019-02-18T09:47:55.359Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous post, we defined a single method for an endpoint. In a typical web application, each endpoint will have multiple methods. To build an example of a complete endpoint, we need to have a persistence layer that can support these endpoints. To enable MySQL support for spring framework, we need to update pom.xml file with following dependencies.</p><p>Now we need to define data sources for MySQL. The first step is to create a database and user in the MySQL database. To do that log in to MySQL using the following command.</p><pre>$ mysql -u root</pre><p>Now run following set of commands to create a database named <em>tutorial</em> with username <em>tutorial</em> and password <em>tutorial123</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3673583f4afa33b75a0253bddd690e22/href">https://medium.com/media/3673583f4afa33b75a0253bddd690e22/href</a></iframe><p>Now we can initialize a data source in spring framework by putting properties in the <em>application.properties </em>file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01ef4b1ccc7d2c3605097acc571e26c4/href">https://medium.com/media/01ef4b1ccc7d2c3605097acc571e26c4/href</a></iframe><p>As we can see in the properties, the value <em>ddl-auto</em> is set to update. This will cause the database schema to be updated based on the definition of entity objects. This is a good practice while developing the system but normally should not be used while in production.<br>Let’s say we want to define a simple endpoint that supports an entity called <em>User.</em> We define the entity in Java as below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93ac433e9c7c6fe08b54d4e678a8cbcb/href">https://medium.com/media/93ac433e9c7c6fe08b54d4e678a8cbcb/href</a></iframe><p>As we can see, the key to an entity class is the annotation <em>@Entity</em>. You can also add an optional annotation <em>@Table</em> which will allow you control over the name of the table that gets created within the database. By default, if you omit the <em>@Table</em> annotation, the table name would be automatically generated.<br>The next step is to generate a Repository interface for accessing the entity from the database. We typically create a subclass of CrudRepository.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/893cfdd6469cfbe9d61c528f34c6567f/href">https://medium.com/media/893cfdd6469cfbe9d61c528f34c6567f/href</a></iframe><p>An empty repository interface provides sufficient functionality for this example. We will see how to add more functionality to repository class in a different post. The <a href="https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/CrudRepository.html">Javadoc</a> of CrudRepository provides details of all the methods that are readily available without any addition to the interface.<br>Let’s run the server to see whether the server can connect to the database. As we run the server, we check what happened to our database.</p><pre>$ mysql -u tutorial -ptutorial123 tutorial<br>mysql: [Warning] Using a password on the command line interface can be insecure.<br>Welcome to the MySQL monitor.  Commands end with ; or \g.<br>Your MySQL connection id is 12<br>Server version: 8.0.12 Homebrew</pre><pre>Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.</pre><pre>Oracle is a registered trademark of Oracle Corporation and/or its<br>affiliates. Other names may be trademarks of their respective<br>owners.</pre><pre>Type &#39;help;&#39; or &#39;\h&#39; for help. Type &#39;\c&#39; to clear the current input statement.</pre><pre>mysql&gt; show tables;<br>+--------------------+<br>| Tables_in_tutorial |<br>+--------------------+<br>| hibernate_sequence |<br>| user               |<br>+--------------------+<br>2 rows in set (0.01 sec)</pre><pre>mysql&gt; desc user;<br>+----------+--------------+------+-----+---------+-------+<br>| Field    | Type         | Null | Key | Default | Extra |<br>+----------+--------------+------+-----+---------+-------+<br>| id       | bigint(20)   | NO   | PRI | NULL    |       |<br>| email    | varchar(255) | YES  |     | NULL    |       |<br>| fullname | varchar(255) | YES  |     | NULL    |       |<br>| password | varchar(255) | YES  |     | NULL    |       |<br>| username | varchar(255) | YES  |     | NULL    |       |<br>+----------+--------------+------+-----+---------+-------+<br>5 rows in set (0.01 sec)</pre><pre>mysql&gt;</pre><p>The database has the user table created mapping our entity class to a table. Now we have confirmed that the server is able to connect to our database server. Now we go back to the old endpoint class that we created in the previous post and create a similar endpoint class called UserEndpoint. In this class, we will define all the methods required for managing users.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba1b423549e138c5488c97528bd85d24/href">https://medium.com/media/ba1b423549e138c5488c97528bd85d24/href</a></iframe><pre>$ curl -X POST \<br>&gt;   <a href="http://localhost:8080/user">http://localhost:8080/user</a> \<br>&gt;   -H &#39;Content-Type: application/json&#39; \<br>&gt;   -H &#39;Postman-Token: d0298724-86d2-49da-a0c0-067ed9e18e1e&#39; \<br>&gt;   -H &#39;cache-control: no-cache&#39; \<br>&gt;   -d &#39;{<br>&gt; &quot;fullname&quot;:&quot;John Doe&quot;,<br>&gt; &quot;username&quot;:&quot;jdoe&quot;,<br>&gt; &quot;password&quot;:&quot;JohnDoe123&quot;,<br>&gt; &quot;email&quot;:&quot;johndoe@example.com&quot;<br>&gt; }&#39;<br>{&quot;id&quot;:1,&quot;fullname&quot;:&quot;John Doe&quot;,&quot;username&quot;:&quot;jdoe&quot;,&quot;password&quot;:&quot;JohnDoe123&quot;,&quot;email&quot;:&quot;johndoe@example.com&quot;}</pre><p>We can also verify the record in the database.</p><pre>$ mysql -u tutorial -ptutorial123 tutorial -e &quot;select * from user&quot;<br>mysql: [Warning] Using a password on the command line interface can be insecure.<br>+----+---------------------+----------+------------+----------+<br>| id | email               | fullname | password   | username |<br>+----+---------------------+----------+------------+----------+<br>|  1 | johndoe@example.com | John Doe | JohnDoe123 | jdoe     |<br>+----+---------------------+----------+------------+----------+</pre><p>Now we can perform other operations on User record.</p><pre>$ curl -X GET <a href="http://localhost:8080/user/1">http://localhost:8080/user/1</a><br>{&quot;id&quot;:1,&quot;fullname&quot;:&quot;John Doe&quot;,&quot;username&quot;:&quot;jdoe&quot;,&quot;password&quot;:&quot;JohnDoe123&quot;,&quot;email&quot;:&quot;johndoe@example.com&quot;}</pre><pre>curl -X DELETE <a href="http://localhost:8080/user/1">http://localhost:8080/user/1</a><br>{&quot;id&quot;:1,&quot;fullname&quot;:&quot;John Doe&quot;,&quot;username&quot;:&quot;jdoe&quot;,&quot;password&quot;:&quot;JohnDoe123&quot;,&quot;email&quot;:&quot;johndoe@example.com&quot;}</pre><p>Now we can run the database query again and see that the record has vanished.</p><pre>mysql&gt; select * from user;<br>Empty set (0.00 sec)</pre><p>Now we create the user again by running the POST command. Since we are using database autoincrement, the id of the user will be 2 now.<br>Now we change the email of the user using PATCH command.</p><pre>curl -X PATCH   <a href="http://localhost:8080/user/2">http://localhost:8080/user/2</a>   -H &#39;Content-Type: application/json&#39;   -H &#39;Postman-Token: d0298724-86d2-49da-a0c0-067ed9e18e1e&#39;   -H &#39;cache-control: no-cache&#39;   -d &#39;{<br>&quot;email&quot;:&quot;jdoe@example.com&quot;<br>}&#39;<br>{&quot;id&quot;:2,&quot;fullname&quot;:&quot;John Doe&quot;,&quot;username&quot;:&quot;jdoe&quot;,&quot;password&quot;:&quot;JohnDoe123&quot;,&quot;email&quot;:&quot;jdoe@example.com&quot;}</pre><p>Here we have it. All the endpoints are functioning properly backed by MySQL as the database.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22018c02d1de" width="1" height="1" alt=""><hr><p><a href="https://medium.com/springframework/3-all-the-methods-in-endpoint-22018c02d1de">3. All the methods in endpoint</a> was originally published in <a href="https://medium.com/springframework">Springframework</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>