<?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 Madhusudhanan on Medium]]></title>
        <description><![CDATA[Stories by Madhusudhanan on Medium]]></description>
        <link>https://medium.com/@madhusdhnn?source=rss-2f2b676c8129------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mp4L_nI-oYWBNNY5r1ud1g.jpeg</url>
            <title>Stories by Madhusudhanan on Medium</title>
            <link>https://medium.com/@madhusdhnn?source=rss-2f2b676c8129------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 11:41:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@madhusdhnn/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[Learn how to secure Spring Boot application using Amazon Cognito]]></title>
            <link>https://levelup.gitconnected.com/learn-how-to-secure-spring-boot-application-using-amazon-cognito-67e76cd617eb?source=rss-2f2b676c8129------2</link>
            <guid isPermaLink="false">https://medium.com/p/67e76cd617eb</guid>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[cognito]]></category>
            <dc:creator><![CDATA[Madhusudhanan]]></dc:creator>
            <pubDate>Mon, 18 Dec 2023 14:30:41 GMT</pubDate>
            <atom:updated>2024-03-06T08:57:20.703Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, we’ll learn how to secure a Spring boot web application using <em>Amazon Cognito</em>. If you’re already familiar with the basics of OAuth 2.0 and Amazon Cognito, fantastic! However, if you need a quick refresher or are new to it, feel free to check out <a href="https://blog.bytebytego.com/i/135955829/oauth-explained-with-simple-terms">here</a> and for Cognito refer <a href="https://docs.aws.amazon.com/cognito/latest/developerguide/what-is-amazon-cognito.html">here</a>. Our focus will be exclusively on the Spring Boot side, assuming you’re already familiar with Amazon Cognito. Now, let’s get started.</p><p>Imagine we have a full-stack application built using Spring Boot and any front-end library. In this setup, we’ll efficiently manage user authentication through the Amazon Cognito User Pool. Since it is OAuth 2.0-based authentication, we can leverage the same to secure our backend.</p><p>The initial step involves creating a User Pool in Cognito, opting for a public app client configuration. Why public? Because users will interact with the service through the user interface. In alignment with the OAuth 2.0 specifications, our Spring Boot application takes on the role of the resource server. For simplicity, let’s assume that a user pool is already established, complete with a set of users. Our specific focus is on the ‘iss’ (issuer) part within the JWT token generated by Cognito. It will have the value in the below format. This is all we need from Cognito.</p><pre>https://cognito-idp.&lt;AWS-REGION&gt;.amazonaws.com/&lt;USER-POOL-ID&gt;</pre><p>Commonly, we’d use AWS Amplify to connect our front-end application with Amazon Cognito. This configuration simplifies user authentication and facilitates the retrieval of the JWT Token. Cognito gives us three tokens upon successful authentication namely: <em>access_token</em>, <em>refresh_token</em> and <em>id_token</em>. Of these, the <em>id_token</em> is the one we require for inclusion in the “Authorization” header. Remember to add the word “Bearer” right before the token in the header.</p><p>Alright, the next step is to configure Spring Security in the Spring boot application. We only need two dependencies which are listed below.</p><pre>implementation &#39;org.springframework.boot:spring-boot-starter-security&#39;<br>implementation &#39;org.springframework.boot:spring-boot-starter-oauth2-resource-server&#39;</pre><p>And if you are using Maven, add these in your pom.xml file</p><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>  &lt;artifactId&gt;spring-boot-starter-security&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-oauth2-resource-server&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>In the <em>application.yml</em> or <em>application.properties</em> file, add the following line. Replace AWS-REGION and USER-POOL-ID with whatever values you have.</p><pre>cognito:<br>  issuer-uri: https://cognito-idp.&lt;AWS-REGION&gt;.amazonaws.com/&lt;USER-POOL-ID&gt;</pre><p>The final step is to write a configuration class that defines the security parameters for the application. Below is the sample code in Java.</p><pre>@Configuration<br>@EnableWebSecurity<br>public class SecurityConfiguration {<br><br>    private final String issuerUri;<br>    private final UserAuthenticationFilter userAuthenticationFilter;<br><br>    @Autowired<br>    public SecurityConfiguration(@Value(&quot;${cognito.issuer-uri}&quot;) String issuerUri,<br>                                 UserAuthenticationFilter userAuthenticationFilter) {<br>        this.issuerUri = issuerUri;<br>        this.userAuthenticationFilter = userAuthenticationFilter;<br>    }<br><br>    @Bean<br>    public SecurityFilterChain apiSecurity(HttpSecurity http) throws Exception {<br>        return http.csrf(AbstractHttpConfigurer::disable)<br>                .addFilterAfter(userAuthenticationFilter, BearerTokenAuthenticationFilter.class)<br>                .authorizeHttpRequests((httpRequestsAuthorizer) -&gt; <br>                     httpRequestsAuthorizer<br>                         .requestMatchers(HttpMethod.GET, &quot;/faq&quot;).permitAll()<br>                         .requestMatchers(&quot;/any/other/public/apis&quot;).permitAll()<br>                         .anyRequest().authenticated()<br>                )<br>                .oauth2ResourceServer(oAuth2ResourceServerConfigurerCustomizer())<br>                .build();<br>    }<br><br>    private Customizer&lt;OAuth2ResourceServerConfigurer&lt;HttpSecurity&gt;&gt; oAuth2ResourceServerConfigurerCustomizer() {<br>        final JwtDecoder decoder = JwtDecoders.fromIssuerLocation(issuerUri);<br>        return (resourceServerConfigurer) -&gt; resourceServerConfigurer.jwt(<br>                jwtConfigurer -&gt; jwtConfigurer.decoder(decoder)<br>        );<br>    }<br>}</pre><p>Let me walk you through the code.</p><p>@EnableWebSecurity annotation informs Spring Boot that this class serves as a configuration class for Spring Security, housing relevant beans. Make sure to annotate it with @Configuration. Then, we will inject the issuer URL from the application.yml file. I’ll get back to the filer class (optional) UserAuthenticationFilter shortly.</p><p>Moving forward, the subsequent task involves defining the SecurityFilterChain bean, and let’s break it down sequentially.</p><ol><li>It takes the HttpSecurity object and constructs our security configuration. Disable CSRF as we don’t need it.</li><li>authorizeHttpRequests — here we define which APIs are publicly accessible and which demand authentication. We define access control for our APIs, leveraging Spring’s elegant customization options.</li><li>oauth2ResourceServer — This segment is dedicated to configuring our resource server settings. Given that we possess the issuer URL, our primary task involves defining the JWT token decoder object. The intricacies of this process will be handled seamlessly by Spring Security and the Spring Security-OAuth Resource server package. I’ll explain a bit more about this when we dive into the aforementioned filter class.</li><li>build — And that’s it! A simple invocation of the build method finalizes the construction of the bean.</li></ol><p>Spring Security is full of Servlet filters that are orchestrated by the mighty SecurityFilterChain. If you want to learn more about it, take a look at it <a href="https://docs.spring.io/spring-security/reference/servlet/architecture.html#servlet-securityfilterchain">here</a>. Additionally, on my other blog, I’ve provided a comprehensive explanation of Spring Security’s token-based authentication, and how it works under the hood with an example code. Feel free to explore and deepen your understanding <a href="https://medium.com/gitconnected/learn-how-to-build-a-token-based-authentication-server-using-spring-boot-and-spring-security-14a82d186f88">here</a>.</p><p>So, back to filters, out of those, BearerTokenAuthenticationFilter is the one used for decoding and verifying the JWT token passed in the request. It delegates the JwtAuthenticationProvider class where the actual decoding and validation of the JWT token happens. Should the token prove valid, the request is duly fulfilled; otherwise, a 401 Unauthorized status is dispatched.</p><p>Now, let’s pivot to the UserAuthenticationFilter. While considered an optional filter, it becomes indispensable when your system relies on user details. For eg: If there are database tables that have <em>user_id</em> as a foreign key column. In such cases, it becomes imperative to synchronize user details between the Cognito User Pool and your database’s user table. You can expose user APIs to do so. To populate currently logged user details in the request, we strategically place this filter right after validating the JWT token. Here’s the sample code for it.</p><pre>@Component<br>public class UserAuthenticationFilter extends OncePerRequestFilter {<br>    public static final String CURRENT_USER_ATTRIBUTE = &quot;currentUser&quot;;<br><br>    private final UserRepository userRepository;<br><br>    @Autowired<br>    public UserAuthenticationFilter(UserRepository userRepository) {<br>        this.userRepository = userRepository;<br>    }<br><br>    @Override<br>    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {<br>        // Here we are for sure, context object holds a valid and decoded JWT token.<br>        SecurityContext context = SecurityContextHolder.getContext();<br>        try {<br>            if (context.getAuthentication() instanceof JwtAuthenticationToken) {<br>                JwtAuthenticationToken auth = (JwtAuthenticationToken) context.getAuthentication();<br>                String cognitoSub = auth.getName();<br>                User user = userRepository.findByCognitoSub(cognitoSub);<br>                if (user == null) {<br>                    throw new UsernameNotFoundException(&quot;User not found!&quot;);<br>                }<br>                request.setAttribute(CURRENT_USER_ATTRIBUTE, user);<br>            }<br>        } catch (UsernameNotFoundException ex) {<br>            log.error(&quot;Encountered error while finding user with current authentication token&quot;, ex);<br>            sendUnAuthorized(response, ex);<br>            return;<br>        }<br><br>        chain.doFilter(request, response);<br>    }<br><br>    private void sendUnAuthorized(HttpServletResponse response, UsernameNotFoundException ex) {<br>        response.setStatus(HttpStatus.FORBIDDEN.value());<br><br>        if (ex != null) {<br>            try (Writer writer = response.getWriter()) {<br>                writer.write(ex.getMessage());<br>            } catch (IOException ioEx) {<br>                throw new RuntimeException(ioEx);<br>            }<br>        }<br>    }<br>}</pre><p>Again! let me walk you through the code.</p><p>Once the token is validated, Spring Security steps in, creating and storing the SecurityContext object in SecurityConextHolder. This object encapsulates our Authentication object ideally of type JwtAuthenticationToken. With this configuration, we will seamlessly extract user details from the database (using the Spring JPA repository class). You might wonder, who creates these user detail records? Indeed, there are various approaches, but in my implementation, I opted for a “post-confirmation” Lambda trigger for Cognito — a Lambda function. This trigger takes charge, creating user detail records in our PostgreSQL database running on RDS. I know the system is asynchronous in creating records. But, that is beyond the scope of the blog. That’s it!</p><p>Here’s a sample code for GET API that requires a currently logged-in user. @RequestAttribute is the convenient annotation to access the servlet request attributes in the controller methods.</p><pre>@GetMapping<br>public ApiResponse getAllContacts(@RequestAttribute(name = UserAuthenticationFilter.CURRENT_USER_ATTRIBUTE) User user) {<br>  // Voila! access user.getFirstName(), user.getEmail(), etc<br>}</pre><p>That’s all! I hope you found this informative. Have a nice day :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67e76cd617eb" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/learn-how-to-secure-spring-boot-application-using-amazon-cognito-67e76cd617eb">Learn how to secure Spring Boot application using Amazon Cognito</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn how to implement pagination with API Gateway, Lambda, and DynamoDB (TypeScript)]]></title>
            <link>https://levelup.gitconnected.com/how-to-implement-pagination-with-api-gateway-lambda-and-dynamodb-8e6b93e97f07?source=rss-2f2b676c8129------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e6b93e97f07</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[pagination]]></category>
            <category><![CDATA[dynamodb]]></category>
            <dc:creator><![CDATA[Madhusudhanan]]></dc:creator>
            <pubDate>Wed, 18 Jan 2023 06:06:38 GMT</pubDate>
            <atom:updated>2023-01-24T14:20:46.280Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, we’ll learn how to implement pagination with <em>API Gateway, Lambda</em>, and<em> DynamoDB</em>. I assume you already know at least the basics of these services and this blog is mainly focused on DynamoDB. Simply put pagination is the process of dividing the entire data into smaller chunks. This chunk of data can be fetched gradually. Pagination usually involves the following terms.</p><ol><li>Page — a pointer that represents the current chunk of data</li><li>Count — total no of items to fetch on a page</li><li>Total — count of all items present in the database (the data which we want to paginate)</li></ol><p>Additionally, there can be filters applied to those data to refine the search results. This is a typical design of a pagination API. The client (website) will send the current page number and count properties as the query string parameters of the endpoint. But here it will be a bit different.</p><p>Let’s start by developing a REST endpoint that will be deployed on the API Gateway. The API will use the Lambda function as the backend to implement pagination in DynamoDB. You can use whatever runtime you’d like. But, I’m gonna use Typescript. Assume we are developing a discussion forum website and we want to list all the posts on a topic. We’ll have the following models/ entities.</p><ol><li>Topics — Root-level grouping of all posts</li><li>Posts — There will be zero or more posts in a channel</li></ol><p>Our endpoint would look something like this.</p><pre>GET /posts?topicId=1&amp;count=10</pre><p>A short intro about supported read operations in DynamoDB for the collection of items. There are two types: <em>Scan</em> and <em>Query</em>. I’m not gonna go into this in detail. But, <em>Scan</em> should be avoided as it involves a “full-table scan”. This is a costly operation. <em>Query</em> fetches records only on a specific partition. Generally, you should always favor <em>Query</em> over <em>Scan</em>. More info <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-query-scan.html">here</a>. So, we are gonna use the <em>Query</em> operation. Please note that for <em>Query</em> we need to specify the primary key (partition key and optional sort key).</p><p>As I said earlier, in DynamoDB things are a bit different for pagination. Although it divides the data into pages, there’s no <em>Page</em> involved; well, not directly. There are two different ways we can implement it. The process is quite similar in both ways but the place where it is implemented will differ. The process is explained in AWS’s official documentation. Here’s the <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.Pagination.html">link</a>. In short, the process starts by executing a <em>Query</em> operation with the given input. If there are records more than 1 MB in size or if we have applied the limit, then the DynamoDB returns a property called <em>LastEvaluationKey</em>. We’d repeat the <em>Query</em> operation until this property becomes null or undefined.</p><pre>async function getAllPosts(topicId) {<br>  let queryResult;<br>  let items = [];<br>  let params = {...}; // For brevity this is not written<br>  <br>  do {<br>    queryResult = await ddbClient.query(params).promise();<br>    items = items.concat(queryResult.Items);<br>    params.ExclusiveStartKey = queryResult.LastEvaluationKey;<br>  } while (typeof queryResult.LastEvaluationKey !== &quot;undefined&quot;);<br>  <br>  return items;<br>}</pre><p>Simply speaking, this property is like a cursor in the database. This will contain the primary key of the item where the operation was stopped (same as in the documentation). Here we don’t iterate over the records. Instead, we’d stop and send the response. Our response body comprises the result set and the <em>LastEvaluationKey.</em> Here’s where the difference comes in.</p><p>The check for the existence of the <em>LastEvaluationKey</em> property is done on the client side. If it is not null, we need to pass this property in the subsequent API calls. Because this is going to be the start of fetching the next page. For subsequent <em>Query</em> operations, we’d pass this value to the <em>ExclusiveStartKey</em> property — a property that takes <em>LastEvaluationKey</em> and continue the read operation; it’s more like OFFSET in SQL. If <em>LastEvaluationKey</em> is null or undefined, then we have reached the “last page”. Note that there may be a case where <em>LastEvaluationKey</em> is not null, but the result set is empty. This is because you may have applied any filters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*z0VIsDs56b_GLRklDJ4ZwA.png" /><figcaption>api-flow.png</figcaption></figure><p>In the above diagram, after the third API call, the <em>LastEvaluationKey</em> property is not sent, which means we have reached the last page. Once fetching all paged records is done, it’s up to the client how to maintain them on the browser. Notice I have used <em>nextPageKey</em>. This is just a meaningful name I wanted to use in the endpoint. You can name it anything you like. The main difference with this approach is the iteration of all pages is done on the client side rather than on the server side (given in the documentation). This way we are achieving the typical pagination concept with the <em>LastEvaluationKey</em> property. The TypeScript code is given below. For brevity, I added only a few lines of code. You can extend this by adding filters like getting all posts between the range of date &amp; time, by author, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2fgcNrxV_cdEpig3VlDvFQ.png" /><figcaption>code.ts</figcaption></figure><p>Let me walk you through the code. We start by getting the input from API query string parameters. The <em>nextPageKey</em> property might be null on the first call. So we construct <em>Query</em> operation params accordingly. Note that I have encoded &amp; decoded the value of <em>LastEvaluationKey</em> as a Base64 string. This is just to have cleaner look. Also if you have a sort key or index defined, this can be in JSON. I designed the <em>Topics</em> table to have an attribute (column) called <em>totalPosts</em>. Whenever a new post is created under a topic, I increment its value by 1 and whenever the post is deleted, I decrement its value by 1. So, it is easy for me to get the total number of posts for a given <em>topicId</em>. And finally, we send the response. Note that the response body has additional fields. Because this lambda function handler is defined as “<a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-output-format">Lambda proxy integration</a>” in API Gateway. But our final response body from API Gateway would look like this.</p><pre>{<br>  &quot;data&quot;: [{}, {}, {}...],<br>  &quot;pagination&quot;: {<br>    &quot;count&quot;: 10,<br>    &quot;total&quot;: 100,<br>    &quot;nextPageKey&quot;: &quot;776f726c64&quot;<br>  }<br>}</pre><p>That’s it. Thank you! Have a nice day :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e6b93e97f07" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-to-implement-pagination-with-api-gateway-lambda-and-dynamodb-8e6b93e97f07">Learn how to implement pagination with API Gateway, Lambda, and DynamoDB (TypeScript)</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn how to create an RDS instance using AWS CDK (TypeScript)]]></title>
            <link>https://levelup.gitconnected.com/learn-how-to-create-an-rds-instance-using-aws-cdk-typescript-a688d9f13cba?source=rss-2f2b676c8129------2</link>
            <guid isPermaLink="false">https://medium.com/p/a688d9f13cba</guid>
            <category><![CDATA[rds]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cdk]]></category>
            <dc:creator><![CDATA[Madhusudhanan]]></dc:creator>
            <pubDate>Sat, 08 Oct 2022 15:03:22 GMT</pubDate>
            <atom:updated>2023-07-26T13:57:43.100Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, you will learn how to create an RDS instance running PostgreSQL using AWS CDK. CDK is becoming quite popular now. Before going into the topic, I assume you have at least some amount of experience in using AWS services.</p><p>CDK is an infrastructure automation tool written in your favourite programming language. Each resource you want to create is called a Construct and multiple Constructs together are called a Stack and multiple Stacks make up an App. Ultimately, it provisions our cloud infrastructure using AWS CloudFormation. There are two versions in which V1 is in maintenance mode. So, we will use only V2. To learn more, visit this <a href="https://docs.aws.amazon.com/cdk/index.html">link</a>.</p><p>Ok, let’s start writing the code. The first step, as usual, is to create a new CDK project. For this, you need to have the <em>aws-cdk</em> CLI installed on your system. It’s very easy. Just run the command: <em>npm install -g aws-cdk</em>. Yes, you are right; you also need Node JS installed on your system. Now that we have the CLI installed, the next step is to create a new CDK project. Create a new folder for the project and run the command inside that folder: <em>cdk init — language typescript</em>, and hit Enter. Sit back and relax, until it’s done……. Ok, now open it in your favourite IDE (I use VS code).</p><p>There’s a file under the <strong>bin</strong> folder. This is like the main function in any programming language. If you change the name of this main file, don’t forget to update it in the <em>cdk.json</em> file. Anyway, we will spend most of our time in the <strong>lib</strong> folder only. Run <em>cdk bootstrap</em> to prepare the environment. This includes creating execution roles in IAM, an S3 bucket to store our CloudFormation templates, etc. (<a href="https://docs.aws.amazon.com/cdk/v2/guide/bootstrapping.html">more info</a>)</p><p>Now, we will create a new TypeScript file under the <strong>lib</strong> folder. You may delete existing files, if any, under the <strong>lib</strong> folder. Let’s name this file <em>database.stack.ts</em>. And then, we will create a new class that extends the class <em>Stack</em>. Let’s name it <em>DatabaseStack</em>. Till now, your file should look like the image below.</p><pre>import { Stack, StackProps } from &quot;aws-cdk-lib&quot;;<br>import { Construct } from &quot;constructs&quot;;<br><br>export class DataBaseStack extends Stack {<br>  constructor(scope: Construct, id: string, props: StackProps) {<br>    super(scope, id, props);<br><br>    // your code goes here<br>  }<br>}</pre><p>In the CDK project, almost all of our classes will have the same format in the constructor. In other words, you must have the scope and the id parameters and optional stack props parameters.</p><p>Now let’s write more code. We are gonna deploy the database in a private subnet which means either you change the default public subnet in the default VPC to private by removing the route from the destination 0.0.0.0/0 to the internet gateway (<a href="https://docs.aws.amazon.com/vpc/latest/userguide/default-vpc.html">more info</a>) or we can create our own VPC and subnets. I’ll leave this up to you, but I’m going to create a new VPC and configure one public subnet and one private subnet in one AZ (to keep it simple).</p><p>To create a new RDS instance, we will need the following fields, although most of these are optional while creating the CDK stack objects.</p><ol><li>Master username &amp; password — We will put this in AWS Secrets Manager to securely access it</li><li>A security group — Allow any IPv4 connection only within our VPC on port 5432 (PostgreSQL default port)</li><li>Instance Type — The RDS database instance type. For eg: <em>db.t3.micro</em></li><li>Engine — Postgres with version number</li><li>Port — The database port</li><li>Database Name</li><li>Removal Policy — DESTROY. Note, this is only for development purposes</li><li>VPC — VPC configuration</li><li>Backup settings</li></ol><p>With the above details, your code should look like this.</p><pre>import { Duration, RemovalPolicy, Stack, StackProps } from &quot;aws-cdk-lib&quot;;<br>import {<br>  InstanceClass,<br>  InstanceSize,<br>  InstanceType,<br>  Peer,<br>  Port,<br>  SecurityGroup,<br>  SubnetType,<br>  Vpc,<br>} from &quot;aws-cdk-lib/aws-ec2&quot;;<br>import { Credentials, DatabaseInstance, DatabaseInstanceEngine, PostgresEngineVersion } from &quot;aws-cdk-lib/aws-rds&quot;;<br>import { Secret } from &quot;aws-cdk-lib/aws-secretsmanager&quot;;<br>import { Construct } from &quot;constructs&quot;;<br><br>export class DataBaseStack extends Stack {<br>  constructor(scope: Construct, id: string, props: StackProps) {<br>    super(scope, id, props);<br><br>    const engine = DatabaseInstanceEngine.postgres({ version: PostgresEngineVersion.VER_13_7 });<br>    const instanceType = InstanceType.of(InstanceClass.T3, InstanceSize.MICRO);<br>    const port = 5432;<br>    const dbName = &quot;my_awesome_db&quot;;<br><br>    // create database master user secret and store it in Secrets Manager<br>    const masterUserSecret = new Secret(this, &quot;db-master-user-secret&quot;, {<br>      secretName: &quot;db-master-user-secret&quot;,<br>      description: &quot;Database master user credentials&quot;,<br>      generateSecretString: {<br>        secretStringTemplate: JSON.stringify({ username: &quot;postgres&quot; }),<br>        generateStringKey: &quot;password&quot;,<br>        passwordLength: 16,<br>        excludePunctuation: true,<br>      },<br>    });<br><br>    // We know this VPC already exists<br>    const myVpc = Vpc.fromLookup(this, &quot;my-vpc&quot;, { vpcId: &quot;vpc-098sdfs3452&quot; });<br><br>    // Create a Security Group<br>    const dbSg = new SecurityGroup(this, &quot;Database-SG&quot;, {<br>      securityGroupName: &quot;Database-SG&quot;,<br>      vpc: myVpc,<br>    });<br><br>    // Add Inbound rule<br>    dbSg.addIngressRule(<br>      Peer.ipv4(myVpc.vpcCidrBlock),<br>      Port.tcp(port),<br>      `Allow port ${port} for database connection from only within the VPC (${myVpc.vpcId})`<br>    );<br><br>    // create RDS instance (PostgreSQL)<br>    const dbInstance = new DatabaseInstance(this, &quot;DB-1&quot;, {<br>      vpc: myVpc,<br>      vpcSubnets: { subnetType: SubnetType.PRIVATE_ISOLATED },<br>      instanceType,<br>      engine,<br>      port,<br>      securityGroups: [dbSg],<br>      databaseName: dbName,<br>      credentials: Credentials.fromSecret(masterUserSecret),<br>      backupRetention: Duration.days(0), // disable automatic DB snapshot retention<br>      deleteAutomatedBackups: true,<br>      removalPolicy: RemovalPolicy.DESTROY,<br>    });<br><br>    // DB connection settings will be appended to this secret (host, port, etc.)<br>    masterUserSecret.attach(this.dbInstance);<br>  }<br>}</pre><p>Let me explain the code. Please note the imports. All the resources we used are neatly modularized under <em>aws-cdk-lib</em>.</p><ol><li>Secret — This class is used to create a new secret in the Secrets Manager with a name and value. The <em>generateSecretString</em> block will generate a password for us and append it to the JSON <em>{“username”: “postgres”}</em> with a name <em>password</em>. So, the resulting JSON will be <em>{“username”: “postgres”, “password”: “ewry324748h”}</em> (Password is just Gibberish). Note that, if you want to have additional users in the RDS database, say users for your backend applications, you can put them in Secrets Manager as well. But, make sure you actually create them in the database (refer to this <a href="https://www.postgresql.org/docs/13/sql-createuser.html">link</a>)</li><li>Vpc — This class represents VPC. Since we manually created our VPC, we will just look it up with the option passed to it. Tip: You can also create the VPC using CDK too!</li><li>SecurityGroup — This class creates a new Security Group with the given name and the VPC. As the security group is stateful, we don’t need to explicitly define the outbound rules (<a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-rules.html">more info</a>)</li><li>DatabaseInstance — This class is used to create our RDS instance passing the necessary details like instance type, VPC, subnet groups, credentials, etc</li><li>Credentials — This class creates a username and password credentials from the secret we created above</li></ol><p>The next step is to create an instance of this stack in our main file. This will look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B01mqGUU7mPoPXiOWvKMQg.png" /><figcaption>main.ts</figcaption></figure><p>That’s it. Now it’s time to deploy this stack. Make sure you have <em>CDK_DEFAULT_ACCOUNT</em> and <em>CDK_DEFAULT_REGION</em> environment variables set. To see the CloudFormation template, run the command: <em>cdk synth</em>. To deploy, run the command: <em>cdk deploy</em>. If you have multiple stacks defined in your app, say an EC2 instance, or an SQS queue, mention the stack name to deploy. Eg: <em>cdk deploy &lt;STACK_NAME&gt;</em>. Sit back and relax, until it is done…. You can check the progress of CloudFormation in the AWS console. If everything goes well, you would see the new RDS database instance created successfully. The final architecture diagram may look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x0E1QzEZLMKsTfkjpczofQ.png" /></figure><p>That’s it. To delete this stack just run the command: <em>cdk destroy DatabaseStack</em>. And make sure you also delete the bootstrap stack created by CDK in CloudFormation.</p><p>Thank you! Have a nice day :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a688d9f13cba" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/learn-how-to-create-an-rds-instance-using-aws-cdk-typescript-a688d9f13cba">Learn how to create an RDS instance using AWS CDK (TypeScript)</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn how to create job schedulers in  Spring Boot application]]></title>
            <link>https://levelup.gitconnected.com/learn-how-to-create-job-schedulers-in-spring-boot-application-8def2c476424?source=rss-2f2b676c8129------2</link>
            <guid isPermaLink="false">https://medium.com/p/8def2c476424</guid>
            <category><![CDATA[task-scheduler]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Madhusudhanan]]></dc:creator>
            <pubDate>Wed, 19 Aug 2020 15:20:45 GMT</pubDate>
            <atom:updated>2023-03-06T16:12:05.659Z</atom:updated>
            <content:encoded><![CDATA[<h3>Learn how to create job scheduler in the Spring Boot application</h3><p>Hey folks, what’s up? In this blog, we will learn how to create a job scheduler in the Spring Boot application with a unique example.</p><p>As always, we’ll create a project from <a href="https://start.spring.io/">start.spring.io</a>. With just a simple setup of the Spring Boot application, we can create as many schedulers as we want. The required dependencies are captured in the below image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eXmTPWY4tHlgy8HZVP6WSg.png" /></figure><p>Say we have a microservice that can export some data, as a zip file or any kind, stored in the database. An obvious way is to initiate the process via a REST endpoint and wait for the file generation. If the data is not complex and the size is small, you get what you expected within some seconds. This is called a synchronous job. However, what if the data is complex, involves many database queries and other internal operations, and would take more time to generate? The result is a bad user experience. Of course, we can solve this by increasing the timeout between the client and the server. Again, it is not an efficient solution.</p><p>Here comes our scheduler handy. We’ll have the same endpoint still which will be used to initiate the process. But this time, instead of waiting for it to complete, we initiate and then immediately return a 200 OK with metadata. Be careful, we are dealing with a state now; you’ll know later, why. This process is captured below. For simplicity, I have just mimicked the initiate-export process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*14LGJd9A_e3elvdA18nqpA.png" /><figcaption>FileExportController.java</figcaption></figure><p>And the response of the above API will be as in the below image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*4L9u8CRYgswS66fwJpIuJQ.png" /><figcaption>response.json</figcaption></figure><p>Now it is time to write our job scheduler. In Spring way, we’ll write a component. The reason I love Spring boot is its auto-configuration concept. With just one annotation called<em> @EnableScheduling</em>, we can write simple schedulers. In the below code, I haven’t added this annotation. You may add it here or in the main class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vRFLQqqas0k5b9rEcUzfRA.png" /><figcaption>FileExportScheduler.java</figcaption></figure><p>Let us walk through the file. All we need is a method to run jobs and Java’s ExecutorService and a Map to handle concurrency. This way we can ensure thread safety. Spring provides different types of schedulers like cron jobs, fixed-delay type jobs, etc. But now, we will see the fixed-delay type. The only difference between this and the fixed-rate type is the latter doesn’t wait for the previous wake-up call to finish. So fixed-delay type has more control between jobs.</p><p>Using the annotation <em>@Scheduled,</em> we have marked the <em>wakeUp()</em> method as a scheduler. Spring will take care of the rest and we can focus on our logic. In the previous step, we initiated the job by saving the status as PENDING. We will see later, why IN_PROGRESS is also considered. To avoid duplicate submission of jobs in the <em>Executor</em> we have a <em>ConcurrentHashMap</em>. That is, we would submit the job only when it is not already on the map. Now you might be thinking why do we need to maintain this state on a map? That brings me to another scenario. Say we have some other source that may call this same method. At the end of the day, the <em>wakeUp()</em> method is a public method. Instead of duplicating, the state is maintained in a single place(this scheduler class) and no matter how many sources in the application would try to do the same job, the map will take care. A small tip to prefer this map to <em>SynchronizedMap</em> is the former one will have the locking at its bucket level. More info can be found in this <a href="https://stackoverflow.com/a/20417527/6487148">link</a>.</p><p>We will mark the current status as IN_PROGRESS. Once the process is completed successfully, we mark the job as COMPLETED and in the event of an exception, it is marked as FAILED. And also we notify the client via any notification mechanism. For better readability and type safety, these status values can be maintained as an enum.</p><p>The main problem that is achieved with this concept is, “how to handle when the service stops abruptly or any other technical fault that may disturb the process”. Because the whole process is done in the background. The user never knows what happens behind the scenes. That’s the reason we’ve included IN_PROGRESS in the select query. Once the service is up and running, after the disaster, the <em>wakeUp()</em> method will be executed after 30 seconds of the initial delay and the rest will be executed again. Of course, IO cleanup would be required which you can do as “post-processing”.</p><p>So, I guess this is it. You can try this by yourself. You can combine this with the event listener that is available out of the box in Spring Boot. The endpoint will publish the event and the listener method will consume the event object and trigger the file export method. All these steps can be executed asynchronously. The scheduler will take care of the disaster recovery.</p><p>Thanks and have a good day!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8def2c476424" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/learn-how-to-create-job-schedulers-in-spring-boot-application-8def2c476424">Learn how to create job schedulers in  Spring Boot application</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn how to build a token-based authentication server using Spring Boot and Spring Security]]></title>
            <link>https://levelup.gitconnected.com/learn-how-to-build-a-token-based-authentication-server-using-spring-boot-and-spring-security-14a82d186f88?source=rss-2f2b676c8129------2</link>
            <guid isPermaLink="false">https://medium.com/p/14a82d186f88</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Madhusudhanan]]></dc:creator>
            <pubDate>Sat, 09 May 2020 18:08:14 GMT</pubDate>
            <atom:updated>2023-03-06T16:21:14.077Z</atom:updated>
            <content:encoded><![CDATA[<h3>Learn how to build a token-based authentication service using Spring Boot and Spring Security</h3><p>Hey folks, what’s up? Let’s build an authentication service using Spring Boot and Spring Security. Before that, the reason I’m writing this article is I struggled a lot in understanding the whole architecture of Spring Security when I worked on it. So, I thought I can share this with everyone. And by the way, I’m not gonna explain the whole architecture here as the title says. So, if you want to know about the architecture, I have given the official documentation link at the end of this blog. Getting onto the topic, we’ll be using <a href="https://jwt.io/">JWT</a><strong>, </strong>which is fast and stateless, and also has its equivalent disadvantages, as auth token to authenticate our clients.</p><p>Typically, this type of authentication mechanism will be used in microservices architecture where the entire application is broken up into small and individual modules that work independently. Of course, they are deployed on the distributed system, and the common data among the services will be shared either via on-demand HTTP requests or using messaging tools like Apache Kafka. Alright, let’s get started.</p><p>First things first. We’ll create a project from <a href="https://start.spring.io/">start.spring.io</a> and add the list of dependencies that are required for the project. Besides the Spring dependencies, I have also included the <a href="https://github.com/jwtk/jjwt">Java library for JWT</a> as part of the dependencies. Just for brevity, I have included only the required dependencies. This is captured in the below image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mz4was-mjxMZ2U2auE3Txg.png" /><figcaption>build.gradle</figcaption></figure><p>Since it’s a Spring Boot application, with just one annotation, called <em>@EnableWebSecurity</em>, and with a basic setup, Spring will give the default configuration for Spring Security. Although we need to enable it, we don’t wanna go with the default one. We will customize the configuration such that it supports “stateless authentication”. This will become apparent soon.</p><p>Three main components are involved in configuring Spring Security for our application. They are,</p><ol><li>A security configuration — Holds authentication and authorization-related configuration</li><li>Authentication Provider — Handles the authentication part or the logic that authenticates the user. For example, fetch the user by username passed in the request. If not successful, throw the corresponding <em>AuthenticationException</em></li><li>Authentication Filter — Validates the token and bootstraps the authentication process</li></ol><p>There is a root component above all of these which is called <em>AuthenticationManager.java</em>. This is solely responsible for doing the authentication. It identifies the right provider and calls the <em>authenticate()</em> method. Spring Security intercepts the HTTP request with a list of Filters in a particular order. Keep in mind that the order is important. This set of filters together is called <em>FilterChainProxy</em>. There is a detailed explanation regarding the Spring Security Filters in <a href="https://stackoverflow.com/a/41482134/6487148">this</a> StackOverflow link. Now let’s start implementing them one by one.</p><p><strong>Step 1</strong>: Create a class and annotate it with <em>@Configuration</em> and let’s call it <em>SecurityConfig.java</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wWm4fx1oIm1tJLvoI1v5xg.png" /><figcaption>SecurityConfig.java</figcaption></figure><p>As you can see, we have defined a public method that will create a bean of <em>SecurityFilterChain</em>. We’ll get to this soon.</p><p><strong>Step 2: </strong>Create a class that extends <em>OncePerRequestFilter.java </em>to create a servlet filter. Remember that this filter should intercept all the HTTP endpoints in the application except for “/<em>authenticate”</em> and other public endpoints, if you have any and it will be included as part of Spring Security filters in our configuration</p><p><strong>Step 3:</strong> Before going into the filter, we also need to create two more classes.</p><ol><li>JwtAuthenticationTokenProvider.java — An implementation of <em>AuthenticationProvider.java</em> that processes the type of <em>Authentication.java</em>. This will have two methods namely <em>authenticate() </em>and <em>supports()</em>.</li><li>JwtAuthenticationToken.java — Implementation of <em>Authentication.java</em> that holds the credentials, principal, and granted authorities and maintains the authentication state. Technically, this class can extend <em>AbstractAuthenticationToken.java </em>which is the base class for all authentication objects, and also our class should be <strong>immutable</strong>. A sample image for both is shown below.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tFqfxjKtmtJF1VpmJfpLbA.png" /><figcaption>JwtAuthenticationToken.java</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n9NCE3_-5hS-032C9qwFfg.png" /><figcaption>JwtAuthenticationProvider.java</figcaption></figure><p>The <em>supports()</em> method should return true if the Class parameter is of type <em>JwtAuthenticationToken.java</em>. Because, the <em>AuthenticationManager</em> will loop the list of providers, that we’ll give it in security configuration, to identify the right provider to authenticate this particular request. It is designed such that your application may support different types of authentication mechanisms like OAuth2.0 or traditional username-password-based login etc.</p><p>Once our authentication is successful, an instance of <em>JwtAuthenticationToken</em> class will be stored in a thread-local variable of Spring Security like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TDIakUw_V5t2SZjpIiF3tQ.png" /></figure><p>But what if our authentication fails? How Spring Security handles the negative scenario? Well, there’s this guy in Spring Security filters, called <em>ExceptionTranslationFilter.java</em>, who handles this part. It tries to continue the chain of filters and if it catches any Exception, this filter has something called <em>AuthenticationEntrypoint.java</em> which we configure in our security configuration. This entry point is the place for commencing our response. Here we get the current request (<em>HttpServletRequest</em>) and response (<em>HttpServletResponse</em>) objects and also the corresponding <em>AuthenticationException</em> object that was thrown during the authentication process. So we use them to send the response, usually with a non-successful HTTP status code based on the exception thrown.</p><p>Now getting back to our Filter class. We take the token from the header passed in the HTTP request and validate the JWT token with our JWT Java library. If it is a valid token, we bootstrap the authentication process by constructing the <em>JwtAuthenticationToken</em> object and putting it in <em>SecurityContextHolder</em>. Again, the reason we are doing this is that the authentication manager will loop the list of authentication providers and identify the right provider by calling the <em>supports()</em> method. Once it identifies the right provider, it will call the <em>authenticate()</em> method of that implementation. Only here the actual authentication happens and this time we use another constructor of <em>JwtAuthenticationToken</em> class that takes in the granted authorities of the authenticable user. Our filter class is shown in the below image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mOx4Js6gDQDRx0SFJYAqkQ.png" /><figcaption>JwtTokenAuthenticationFilter.java</figcaption></figure><p>As you can see, we use <em>JwtParser </em>to parse the token. I used an unhealthy secret key which is not recommended for production. This should be something very strong. Last but not the least, we need to create the security configuration with all the above classes. Let’s cook that now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oGTov9UrR-8OOBMjxUCfVg.png" /><figcaption>SecurityConfig.java</figcaption></figure><p>So there are two beans created. The first one (<em>authenticationManager()</em>) registers our Authentication Provider to the Authentication Manager via its <a href="https://en.wikipedia.org/wiki/Builder_pattern">builder</a> object. The latter (<em>filterChain()</em>) configures the security part. This type of continuous method call is called “method chaining” in Java. It looks like a lot of calls happening inside <em>filterChain()</em> method, right? Let’s break it down.</p><ol><li>disable() — HTTP basic and CSRF support. Since we are dealing with our authentication system, we don’t want these. So use this method to disable those</li><li>cors() — enable the CORS filter which will take care of CORS errors</li><li>STATELESS session — we disable the session-based authentication that creates JSESSIONID to maintain the authentication state</li><li>addFilter() — As I said earlier, there is a set of Spring Security filters and one of them is <em>UsernamePasswordAuthenticationFilter.java</em>. We place our filter before this filter, because from the set of filters, at this filter only the authentication process starts. So we need to place it right before it as we update the <em>SecurityContextHolder</em> thread-local object.</li><li>authorizeRequests() — restrict the access of resources by matching the request patterns. Here just for the sake of the tutorial, I have mentioned only one URI pattern. <em>permitAll()</em> method will permit the path that matches the given pattern to be able to access it publicly. In a typical production application, there can be numerous URI patterns to permit or forbid users. For example, if there is an API that registers a new user which logically does not require authentication, then you can allow it by doing like <em>.antMatchers(“**/register”).permitAll()</em></li><li>.anyRequest().authenticated() — the rest of all the APIs that are available in this application should be protected. Meaning that only a user with valid authentication can access those APIs</li></ol><p>So, I guess that’s it. It’s a very basic configuration. You can create more complex configurations like ROLE-based authentication where you can allow some of the endpoints to be accessible only for those having the role ADMIN. There is good documentation from which you can refer to build a custom authentication server application. You can learn more about Spring Security <a href="https://spring.io/guides/topicals/spring-security-architecture">here</a>.</p><p>Thanks and have a good day!</p><p><a href="https://skilled.dev/">Coding Interview Questions + Land Your Dev Job | Skilled.dev</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14a82d186f88" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/learn-how-to-build-a-token-based-authentication-server-using-spring-boot-and-spring-security-14a82d186f88">Learn how to build a token-based authentication server using Spring Boot and Spring Security</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn how to build a server applicationto to upload files using Spring Boot]]></title>
            <link>https://levelup.gitconnected.com/uploading-files-in-spring-boot-a2f6e3f653e1?source=rss-2f2b676c8129------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2f6e3f653e1</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Madhusudhanan]]></dc:creator>
            <pubDate>Mon, 07 Oct 2019 07:53:36 GMT</pubDate>
            <atom:updated>2023-03-06T16:23:38.025Z</atom:updated>
            <content:encoded><![CDATA[<h3>Learn how to create an application to upload files using Spring Boot</h3><p>Hey folks, in this blog we are going to build an application using Spring Boot, that will be used to upload and process it. This can be any file, but I’m gonna explain it with a simple text file. Let’s get started.</p><p>But before going further, I assume you already know the below points.</p><p>1. Gradle<br>2. Spring Boot<br>3. Java 8<br>4. REST API</p><p>Let’s create a new project from <a href="https://start.spring.io/">start.spring.io</a>. I have added only two dependencies, <em>web</em> and <em>Lombok</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*931npp48g-orMlrE6ksOQw.png" /><figcaption>build.gradle</figcaption></figure><p>We will start by writing a simple REST Controller. In this Controller, we are having one method, which handles POST request, and it will ask Spring to give the uploaded file, in the client, as <em>MultipartFile</em> object. Upon receiving the file, we will read each line in the file and print them just for this tutorial purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X4joGTXGGvnD6yWkACFPwA.png" /><figcaption>UploadController.java</figcaption></figure><p>We <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/annotation/Autowired.html">autowire</a> the service class, which will be given by Spring as bean, and calls the <em>consumeFile()</em> method. That’s it. Let’s write our service class which will handle this part.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qxtjIOFMvXMrWQ8a-GzcPA.png" /><figcaption>UploadService.java</figcaption></figure><p>We have only one method that takes the uploaded file as a <em>MultipartFile</em> object and processes it.</p><ol><li>Create an <em>InputStream</em> of the multipart file. We are using Java 7’s <em>try-with-resource</em> to automatically close the <em>InputStream</em>.</li><li>Next is copying the contents in the <em>MultipartFile</em> object to a text file in the <em>temp</em> directory.</li><li>Next, we read all the lines from the text file that we just created in the previous step and print it.</li><li>Finally, we are deleting the text file, created at temp directory, because it is meaningless in storing it on our disk.</li></ol><p>There is another way of consuming the uploaded file and operate on it. Yes, instead of creating a temp file, we can directly use the <em>inputStream</em> by <em>buffering</em> it. This method is more efficient than the previous one. Below is the screenshot that does so. We create a <em>BufferedReader </em>and use <em>lines()</em> method to get each line as <em>Stream&lt;String&gt;</em> and then processing it which in this case is just printing them out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vorEVE7aohKkCr8XXXfl6g.png" /><figcaption>UploadService.java</figcaption></figure><p>Voila. We are done. This is a short example. But you can extend this with any of your logic. For example, if you want to upload a master data, which is in a spreadsheet document, you can do this easily. Or you may create a “file storage service” that will internally store the uploaded file to cloud storage and we can return the reference of the file(maybe a short URL) in response. With this reference, we can get the file anytime and anywhere.</p><p>Let’s run and test the application. I’m using the <em>Gradle wrapper </em>to build the jar and run it as a standalone application as Spring will provide the embedded Tomcat server by default. Run the below command to build up the jar and to run the application.</p><blockquote>./gradlew clean build</blockquote><blockquote>java -jar ./build/libs/upload-demo-0.0.1-SNAPSHOT.jar</blockquote><p>To test the API, we can use <em>Postman</em>. Below is the output displayed in the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*26DcfGckhAWPAv96HdMQNg.png" /></figure><p>Simple, right? Share your feedback. Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2f6e3f653e1" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/uploading-files-in-spring-boot-a2f6e3f653e1">Learn how to build a server applicationto to upload files using Spring Boot</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stubby to the rescue]]></title>
            <link>https://medium.com/@madhusdhnn/stubby-to-the-rescue-2d4ad8ffd99d?source=rss-2f2b676c8129------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d4ad8ffd99d</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Madhusudhanan]]></dc:creator>
            <pubDate>Tue, 16 Apr 2019 16:28:00 GMT</pubDate>
            <atom:updated>2020-08-19T12:57:44.698Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2KU20kfLXeV2SFb1" /><figcaption>Photo on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hey folks, when you are working on Front end technologies like ReactJS or Angular, you may also depend on server side code like NodeJS or Spring Framework and also complex database queries. This is cumbersome as you will have to develop both back end code and front end code, but your main focus is on the client side. Of course there can be back end developers. But what if the back end is not ready. What to do now? Do you really wanna proceed or give up? Let’s see..</p><p>Use something like <a href="https://jsonplaceholder.typicode.com/">JSON Placeholder</a> to solve your problem. This is good. But you can not find your requirements exactly. Search for back end APIs in GitHub to avoid back end coding. This is also nice. But why should I care and search, when I’m curious about Front end. So, anything else available?</p><p><a href="https://www.npmjs.com/package/stubby">stubby4node</a> is the excellent npm package. No matter what back end developer your are, It is very simple to setup and their documentation says</p><blockquote>A configurable server for mocking/stubbing external systems during development. stubby takes endpoint descriptors in the form of a YAML or JSON file that tell it how to respond to incoming requests. For each incoming request, configured endpoints are checked in-order until a match is found.</blockquote><p>You just need a single YAML or JSON file to configure the endpoint descriptors.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6331f432e4337a6172a5949c61d97689/href">https://medium.com/media/6331f432e4337a6172a5949c61d97689/href</a></iframe><p>Like the above configuration, you can add any number of endpoints and their responses with different statuses. This simple package can save lot of your development time. As I mentioned above, you can write a shell script file to automate the start/stop of stubs. Below is the shell script file, I always use.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6fdbdabbd5ed3b11d008713c4e1a720/href">https://medium.com/media/f6fdbdabbd5ed3b11d008713c4e1a720/href</a></iframe><p>The above script runs the mock server on port 8081 and admin portal on 5558(defaults to 8889). You can run the stubs programmatically also, as like given below.</p><pre>var Stubby <strong>=</strong> require(&#39;stubby&#39;).Stubby;</pre><pre>var stubby1 <strong>=</strong> <strong>new</strong> Stubby();</pre><pre>var stubby2 <strong>=</strong> <strong>new</strong> Stubby();</pre><pre>stubby1.start({</pre><pre>  stubs<strong>:</strong> 80,</pre><pre>  admin<strong>:</strong> 81,</pre><pre>  location<strong>:</strong> &#39;localhost&#39;,</pre><pre>  data<strong>:</strong> [{</pre><pre>    request<strong>:</strong> { url<strong>:</strong> &quot;/anywhere&quot; }</pre><pre>  },{</pre><pre>    request<strong>:</strong> { url<strong>:</strong> &quot;/but/here&quot; }</pre><pre>  }]</pre><pre>  });</pre><pre>  stubby2.start({</pre><pre>    stubs<strong>:</strong> 82,</pre><pre>    admin<strong>:</strong> 83,</pre><pre>    location<strong>:</strong> &#39;127.0.0.2&#39;</pre><pre>  });</pre><p>With this, you can explore front end technologies without worrying about back end code and database maintenance. What can I do with it, you ask? It has a great documentation, which you can take a look and you have to. It is integrated with other languages such as Java, .NET, grunt and gulp. So, I hope it helps. Thank you guys for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d4ad8ffd99d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing tests help me to deliver good quality code]]></title>
            <link>https://medium.com/@madhusdhnn/writing-tests-help-me-to-deliver-good-quality-code-37a1a04e28a5?source=rss-2f2b676c8129------2</link>
            <guid isPermaLink="false">https://medium.com/p/37a1a04e28a5</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[quality]]></category>
            <dc:creator><![CDATA[Madhusudhanan]]></dc:creator>
            <pubDate>Sun, 13 Jan 2019 10:24:55 GMT</pubDate>
            <atom:updated>2020-08-19T12:58:29.960Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey folks, first of all short intro about me. I’m a beginner Software Developer who always love to learn new technologies. I started my career in 2018. I’d love to teach what I learn. I’m working as a Full Stack Developer. The tech stacks I use are ReactJS, Spring Boot, PostgreSQL and NodeJS. End of intro. Okay, let’s dive into the topic.</p><p>This is fully based on my experience about writing tests. When I started my career, I was thinking, “Why should a Developer write tests?”. After few months I realised that writing tests can help us deliver good quality code. For example, If we are developing a calculator app, the use cases are arithmetic operations. It seems to be a small app, but without certifying it, the code is error prone. We can cover edge cases like, the very famous “divide by zero”. We can refactor the code very well. Of course, there may be bugs. But the scope of bugs is greatly reduced. There are lot of testing frameworks available with lot of features out of the box.</p><p>Some of the popular testing frameworks are Cucumber for Behavior testing, JUnit, Mockito for Java and Jest, Mocha for JavaScript. I’m not an expert in providing example code snippets, but I suggest you to take a look at these frameworks. They have good documentation.</p><ul><li><a href="https://junit.org/junit5/">https://junit.org/junit5/</a></li><li><a href="https://site.mockito.org/">https://site.mockito.org/</a></li><li><a href="https://cucumber.io/">https://cucumber.io/</a></li><li><a href="https://mochajs.org/">https://mochajs.org/</a></li></ul><p>Thank you for reading my post 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37a1a04e28a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>