<?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 Avinash on Medium]]></title>
        <description><![CDATA[Stories by Avinash on Medium]]></description>
        <link>https://medium.com/@aviyadav231?source=rss-1461307648ae------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*i4dtaljBssUGuSfn54PGbA.jpeg</url>
            <title>Stories by Avinash on Medium</title>
            <link>https://medium.com/@aviyadav231?source=rss-1461307648ae------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 00:20:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aviyadav231/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[How to use Annotations and Stackwalker in Java for Annotation based behaviour]]></title>
            <link>https://aviyadav231.medium.com/how-to-use-annotations-and-stackwalker-in-java-for-annotation-based-behaviour-ae2a3f1aeb37?source=rss-1461307648ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae2a3f1aeb37</guid>
            <category><![CDATA[stackwalker]]></category>
            <category><![CDATA[annotations]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[stacktrace]]></category>
            <dc:creator><![CDATA[Avinash]]></dc:creator>
            <pubDate>Thu, 25 May 2023 13:03:10 GMT</pubDate>
            <atom:updated>2023-05-25T13:03:10.908Z</atom:updated>
            <content:encoded><![CDATA[<p>I n Java development, understanding the context and behaviour of code execution is crucial. Traditional approaches for obtaining stack traces often involved parsing exception objects or using the Thread.currentThread().getStackTrace() method. However, starting from Java 9, a new API called StackWalker was introduced, providing a more efficient and flexible way to traverse stack frames programmatically.</p><p>In this article, we will explore the usage of StackWalker in the context of an abstract class, BaseRepository, which dynamically determines the database operation behaviour based on method annotations.</p><h4><strong>Introduction to StackWalker:</strong></h4><p>StackWalker is a powerful utility introduced in Java 9 that allows developers to traverse and interact with the stack frames of the current thread’s execution. It provides a more flexible and convenient way to access information about the call stack, such as class names, method names, and annotations.</p><h4><strong>Benefits of StackWalker:</strong></h4><ol><li>Enhanced Stack Traversal: StackWalker provides a streamlined way to traverse the call stack, enabling developers to efficiently navigate through method invocations.</li><li>Filter and Select Stack Frames: With StackWalker, you can easily filter and select specific stack frames based on criteria such as class names, annotations, or custom conditions, allowing for more targeted analysis.</li><li>Access Method and Class Information: StackWalker enables retrieving detailed information about methods and classes, including method names, parameter types, return types, annotations, and more.</li><li>Custom Stack Walking Logic: Developers can implement custom logic within the StackWalker API to perform specific actions on the call stack, such as logging, profiling, or applying custom annotations.</li><li>Improved Debugging and Troubleshooting: StackWalker empowers developers with better insights into the execution flow of their code, making debugging and troubleshooting more efficient and effective.</li></ol><h4>StackWalker Walking options:</h4><p>StackWalker provides various walking options that developers can utilize to customize their stack traversal. Let’s explore some of the available options:</p><ol><li><strong>RETAIN_CLASS_REFERENCE</strong>: This option retains the class reference of each stack frame, allowing developers to access class-level information like annotations, modifiers, and more.</li><li><strong>SHOW_HIDDEN_FRAMES</strong>: By enabling this option, hidden stack frames (such as native frames or reflection frames) can be included in the traversal, providing a more comprehensive view of the stack.</li><li><strong>SHOW_REFLECT_FRAMES</strong>: Enabling this option includes stack frames from reflective invocations, helping developers understand the dynamic behaviour of their code.</li><li><strong>SHOW_UNKNOWN_FRAMES</strong>: This option includes frames with unknown information, providing developers with visibility into areas where stack frame data might be unavailable.</li></ol><h4>Example Usage and Demonstration</h4><p>In this example main aim is to show how using stack walker we can get calling method and annotations over that and based on this information how we can change behaviour of our programme. We will be using two annotations ReadOnly and ReadWrite to demonstrate this.</p><p>Let’s have a abstract class BaseRepository , in the class JdbiRo supports readOnly operations and jdbiRw both read and write operations.</p><pre>public abstract class BaseRepository&lt;T&gt; {<br>    private static final Logger logger = LoggerFactory.getLogger(BaseRepository.class);<br>    private final Jdbi jdbiRo;<br>    private final Jdbi jdbiRw;<br>    private final Class&lt;T&gt; classType;<br><br>public BaseRepository(DataSource jdbiRo, DataSource jdbiRw, Class&lt;T&gt; classType) {<br>        this.jdbiRo = Jdbi.create(jdbiRo).installPlugin(new SqlObjectPlugin());<br>        this.jdbiRw = Jdbi.create(jdbiRw).installPlugin(new SqlObjectPlugin());<br>        this.classType = classType;<br>    }<br>}</pre><p>NewRepository is extending BaseRepository will look something like this.</p><pre>@Singleton<br>public class NewRepositry extends BaseRepository {<br>    final Logger logger = LoggerFactory.getLogger(NewRepository.class.getName());<br><br>    @Inject<br>    public NewRepositry(final @Named(&quot;readOnly&quot;) DataSource dataSourceRo,<br>                                 final @Named(&quot;readWrite&quot;) DataSource dataSourceRw) {<br><br>        super(dataSourceRo, dataSourceRw, NewRepository.class);<br>    }<br><br>    @ReadWrite<br>    public List&lt;Long&gt; insertDataList(final List&lt;DataDto&gt; dataDtoList) {<br><br>        return this.get().inTransaction(handle -&gt; {<br>            final var dao = handle.attach(DataDao.class);<br>            return dao.insertAll(dataDtoList);<br>        });<br>    }<br><br>    @ReadOnly<br>    public List&lt;DataDto&gt; getNotificationRequestData(final List&lt;String&gt; requestIds) {<br><br>        return this.get().inTransaction(handle -&gt; {<br>            final var dao = handle.attach(DataDao.class);<br>            return dao.getAll(requestIds);<br>        });<br>}</pre><p>if we se function getNotificationRequestData and insertDataList we can clearly say somehow java is able to identify at real time which data source I need to get. Now how we are doing this let’s deep dive in to that.</p><p>This is how this.get() is working it’s identifying whether call is for read operation or for write operation and based on that it’s returning <strong>Jdbi</strong> object.</p><pre>public Jdbi get() {<br><br>        return isWriteOperation() ? jdbiRw : jdbiRo;<br>    }</pre><p>But it’s able to identify that which kind of operation is happening, answer is the annotation that we added to the function, Below is code that give us the notification over the calling function.</p><pre>private boolean isWriteOperation() {<br><br>        StackWalker walker = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);<br>        final var data = walker.walk(frames -&gt; frames<br>                .filter(frame -&gt; frame.getDeclaringClass() == classType &amp;&amp; isMethodAnnotated(frame, ReadWrite.class))<br>                .findFirst()<br>                .map(StackWalker.StackFrame::getMethodName));<br>        return data.isPresent();<br><br>    }</pre><p>we are using Stackwalker to get the right frame and based on that we are getting method and annotation over it.</p><pre>private Optional&lt;Method&gt; getMethodFromStackFrameElement(final StackWalker.StackFrame stackFrame) {<br><br>        try {<br>            final var method = classType.getMethod(stackFrame.getMethodName(),<br>                    stackFrame.getMethodType().parameterArray());<br>            return Optional.of(method);<br>        } catch (NoSuchMethodException e) {<br>            logger.error(&quot;getMethodFromStackFrameElement method not found &quot;, e);<br>        }<br><br>        return Optional.empty();<br>    }</pre><p>using this method we can get exact method that is executing in NewRepository.</p><p><strong>NOTE : → We have to keep this in mind that for getting the method name alone is not sufficient to get the method we need to pass the right parameters as well.</strong></p><pre>classType.getMethod(stackFrame.getMethodName(),<br>                    stackFrame.getMethodType().parameterArray());</pre><p>Now we have our calling method we just need to check if our annotation is present or not over the function.</p><pre>private &lt;A&gt; boolean isMethodAnnotated(final StackWalker.StackFrame stackFrame, final Class&lt;A&gt; annotationType) {<br><br>        final var methodOptional = getMethodFromStackFrameElement(stackFrame);<br><br>        return methodOptional.isPresent() ? methodOptional.get()<br>                .isAnnotationPresent((Class&lt;? extends Annotation&gt;) annotationType) : false;<br>    }</pre><p>using Method object we can simply find whether annotation is present over the method or not.</p><h4>Conclusion:</h4><p>This approach opens up new possibilities for creating flexible and customisable code that adapts to different scenarios based on annotations. Developers can define custom annotations and use them to modify the behaviour of methods at runtime, making their code more adaptable and extensible.</p><p>StackWalker’s ability to traverse stack frames, access method and class information, and check for annotations allows developers to implement dynamic behaviour with ease. Whether it’s applying different business rules, adjusting access levels, or executing custom logic based on annotations, StackWalker provides the necessary tools to achieve these goals.</p><p>By combining StackWalker with other features of Java, such as reflection and annotations, developers can create sophisticated and flexible systems that respond to runtime conditions and adapt to changing requirements. This approach promotes code reusability, maintainability, and extensibility, as the behaviour of methods can be altered without modifying their implementation directly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae2a3f1aeb37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Trace and troubleshoot your Dropwizard application with unique request IDs]]></title>
            <link>https://aviyadav231.medium.com/trace-and-troubleshoot-your-dropwizard-application-with-unique-request-ids-3741da29035f?source=rss-1461307648ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/3741da29035f</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[debugging]]></category>
            <dc:creator><![CDATA[Avinash]]></dc:creator>
            <pubDate>Tue, 09 May 2023 19:39:00 GMT</pubDate>
            <atom:updated>2023-05-23T05:27:30.475Z</atom:updated>
            <content:encoded><![CDATA[<h3>Automatically assign Unique request IDs to logs in Java Dropwizard</h3><p>As a software developer, spending time debugging code can be frustrating and time-consuming. In fact, many developers spend the majority of their time on debugging rather than writing new code. One of the biggest challenges when debugging code is identifying the root cause of the issue. This is where unique identification becomes crucial.</p><p><strong><em>In this post, we’ll explore how this feature works and how to use it in your own Dropwizard applications.</em></strong></p><h3>What are request IDs?</h3><p>Request IDs are unique identifiers that can be used to track a specific request as it travels through a distributed system. They can be especially useful for troubleshooting and debugging purposes, as they allow developers to trace the flow of a request through multiple services and identify any issues or bottlenecks that may be slowing down the request.</p><h3><strong>What is MDCRequestIdFilter?</strong></h3><p>MDCRequestIdFilter is a request filter in Dropwizard that assigns a unique ID to each incoming request. It is implemented using Mapped Diagnostic Context (MDC), which is a thread-local map in log4j. MDC allows the application to set a context for logging statements, such as the user ID or request ID. MDCRequestIdFilter sets a unique request ID for each incoming request and associates it with the current thread. This unique request ID can then be added to log statements using log4j’s pattern layout.</p><h3><strong>How to use MDCRequestIdFilter in Dropwizard?</strong></h3><p><strong><em>Step 1: Create MDCRequestIdFilter</em></strong></p><p>Here is an example of MDCRequestIdFilter</p><pre>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br>import org.slf4j.MDC;<br><br>import javax.servlet.Filter;<br>import javax.servlet.FilterChain;<br>import javax.servlet.FilterConfig;<br>import javax.servlet.ServletException;<br>import javax.servlet.ServletRequest;<br>import javax.servlet.ServletResponse;<br>import javax.servlet.http.HttpServletRequest;<br>import java.io.IOException;<br>import java.util.UUID;<br><br>public class MDCRequestIdFilter implements Filter {<br><br>    private static final Logger logger = LoggerFactory.getLogger(MDCRequestIdFilter.class);<br><br>    @Override<br>    public void init(FilterConfig filterConfig) throws ServletException {<br>        // Do nothing<br>    }<br><br>    @Override<br>    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,<br>                         FilterChain filterChain) throws IOException, ServletException {<br>        try {<br>            // Generate a unique ID for the request<br>            String requestId = UUID.randomUUID().toString();<br><br>            // Set the ID in the MDC for logging purposes<br>            MDC.put(&quot;requestId&quot;, requestId);<br><br>            // Set the ID as a request attribute for use by the application<br>            HttpServletRequest request = (HttpServletRequest) servletRequest;<br>            request.setAttribute(&quot;requestId&quot;, requestId);<br><br>            // Continue processing the request<br>            filterChain.doFilter(servletRequest, servletResponse);<br>        } finally {<br>            // Clear the MDC at the end of the request to avoid leaking memory<br>            MDC.remove(&quot;requestId&quot;);<br>        }<br>    }<br><br>    @Override<br>    public void destroy() {<br>        // Do nothing<br>    }<br>}</pre><p><strong><em>Step 2 : Add MDCRequestIdFilter to Dropwizard</em></strong></p><pre>environment.servlets().addFilter(&quot;MDCRequestIdFilter&quot;, new MDCRequestIdFilter())<br>                .addMappingForUrlPatterns(null, true, &quot;/*&quot;);</pre><p>addMappingForUrlPatterns can be configured based on different dispatcher type and for specific urlpatterns.</p><p>Step 3: Enable logging for the application</p><p>Once we have added the MDCRequestIdFilter to our application, it will automatically assign a unique ID to each incoming request. This ID will be stored in the MDC under the key “requestId”.</p><p>Finally, we need to enable logging for our application. We can do this by adding the following configuration to our YAML file.</p><pre>logging:<br>  level: WARN<br>  appenders:<br>    - type: console<br>      logFormat: &quot;%d{HH:mm:ss.SSS} [%thread] %-5level [%X{requestId}] %logger{36} - %msg%n&quot;</pre><h3><strong>Conclusion</strong></h3><p>Logging unique identification for each request is essential for debugging and troubleshooting code. MDCRequestIdFilter is a request filter in Dropwizard that assigns a unique ID to each incoming request using Mapped Diagnostic Context (MDC). In this article, we discussed how to use MDCRequestIdFilter in Dropwizard for logging request IDs.</p><p>Logs will look something like this. Where f1661aa0–0172–4060–96e4–43505b18f0e9 is the unique request ID assigned to each request.</p><pre>21:19:18.514 [dw-29 - POST /notification/send] WARN  [f1661aa0-0172-4060-96e4-43505b18f0e9] c.b.m.n.r.SendNotificationResource - request received (notificationType=T2, recipientType=F1)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3741da29035f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automatically updating a timestamp column in PostgreSQL using Triggers]]></title>
            <link>https://aviyadav231.medium.com/automatically-updating-a-timestamp-column-in-postgresql-using-triggers-98766e3b47a0?source=rss-1461307648ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/98766e3b47a0</guid>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Avinash]]></dc:creator>
            <pubDate>Thu, 10 Jun 2021 13:36:28 GMT</pubDate>
            <atom:updated>2021-06-10T13:36:28.762Z</atom:updated>
            <content:encoded><![CDATA[<p>Keeping a record of when was a table last modified is very crucial and important for us. Unlike MySql, Postgres doesn’t come with inbuilt functionality for this. So to solve this problem we will be using <strong>Triggers</strong> and <strong>Procedures.<br></strong>Triggers allow us to define functions that execute whenever a certain type of operation is performed. In this case, to update a Postgres timestamp, you need to run a function that automatically sets updated_at(column to store the time of recent update)value before any UPDATE operation. Here’s how you can do this.</p><h3>Step 1: Create the Table</h3><p>Let’s start by creating a table so that we can run all of our operations on this table without breaking anything😜😜.</p><pre>create table user_task<br>(<br>    created_on timestamp default CURRENT_TIMESTAMP not null,<br>    updated_on timestamp default CURRENT_TIMESTAMP not null,<br>    status     varchar                             not null<br>)</pre><p>This will create a table with the name user_task with columns created_on, updated_on, and status. Created_on and Updated_on are by default current time status. Now let’s insert some data into the table.</p><pre>insert into user_task (status) values(&#39;trying&#39;),(&#39;successful&#39;),(&#39;failed&#39;)</pre><h3>Step 2: Create the Function</h3><p>Next step is creating a Postgres function which <a href="https://www.postgresql.org/docs/9.6/plpgsql.html">PL/pgSQL</a> programming supports.</p><pre>CREATE  FUNCTION <em>update_updated_on_user_task</em>()<br>RETURNS TRIGGER AS $$<br>BEGIN<br>    NEW.updated_on = now();<br>    RETURN NEW;<br>END;<br>$$ language &#39;plpgsql&#39;;</pre><p>In this block of code, we defined our function with our logic of updating updated_on with the value of now().</p><ul><li>In the function, <strong>NEW </strong>variable is a Record Object. New contains the data that’s being inserted or updated in the table. This means we can update and read any value of the row before it gets persisted in the Disk.</li><li>NEW.updated_on = now() means update value of updated_on by value of now().</li></ul><p>This way we can update any column using triggers as per our requirements.</p><blockquote>Note: You can find more information on Postgres Functions <a href="https://www.postgresql.org/docs/9.1/sql-createfunction.html">here</a></blockquote><h3>Step 3: Create the Trigger</h3><pre>CREATE TRIGGER update_user_task_updated_on<br>    BEFORE UPDATE<br>    ON<br>        user_task<br>    FOR EACH ROW<br>EXECUTE PROCEDURE <em>update_updated_on_user_task</em>();</pre><p>This trigger will This trigger will execute the update_updated_on_user_task() function that we defined earlier. It will do so <em>whenever</em> a row is updated in the user_task table.</p><blockquote>Note: You can find more information on Postgres trigger <a href="https://www.postgresql.org/docs/9.1/sql-createtrigger.html">here</a></blockquote><h3>Step 4: Automatic PostgreSQL Timestamps</h3><p>Now updated_on will be saved correctly whenever we update rows in the table. That&#39;s all it takes!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98766e3b47a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>