Notes

My latest writings


Tuesday, March 13, 2018

Eclipse essential 30 Keyboard Shortcuts for Java Programmers

Here is list of 30 chosen Eclipse IDE keyboard shortcuts for Java developers.
It's useful for both core Java developer and Java web application developer using Eclipse IDE for web development.

1)   Ctrl + Shift + T for finding class even from jar
This keyboard shortcut in Eclipse is my most used and favorite shortcut. While working with a high-speed trading system which has a complex code, I often need to find classes with the just blink of the eye and this eclipse keyboard shortcut is just made for that. No matter whether you have class in your application or inside any JAR, this shortcut will find it.

2)   Ctrl + Shift + R for finding any resource (file) including config xml files
This is similar to above Eclipse shortcut with only difference that it can find out not only Java files but any files including XML, configs, and many others, but this eclipse shortcut only finds files from your workspace and doesn’t dig at jar level.

3)    Ctrl + 1 for quick fix
This is another beautiful Eclipse shortcut which can fix up any error for you in Eclipse. Whether it’s missing declaration, missing semi-colon or any import related error this eclipse shortcut will help you to quickly sort that out.

4)    Ctrl + Shift + o for organize imports
Another Eclipse keyboard shortcut for fixing missing imports. Particularly helpful if you copy some code from other file and what to import all dependencies.

Eclipse Shortcut for Quick Navigation

In this section, we will see some eclipse keyboard shortcut which helps to quickly navigate within the file and between file while reading and writing code in Eclipse.

7) Ctrl + o for quick outline going quickly to method
9) Alt + right and Alt + left for going back and forth while editing.
12) Alt + Shift + W for show in package explorer
13) Ctrl + Shift + Up and down for navigating from member to member (variables and methods)
15) Ctrl + k and Ctrl + Shift +K for find next/previous
24) Go to a type declaration: F3, This Eclipse shortcut is very useful to see function definition very quickly.

Eclipse Shortcut for Editing Code

These Eclipse shortcuts are very helpful for editing code in Eclipse.
5) Ctrl + / for commenting, uncommenting lines and blocks, see here for live example.
6) Ctrl + Shift + / for commenting, uncommenting lines with block comment, see here for example.
8) Selecting class and pressing F4 to see its Type hierarchy
10) Ctrl + F4 or Ctrl + w for closing current file
11) Ctrl+Shirt+W for closing all files.
14) Ctrl + l go to line
16) Select text and press Ctrl + Shift + F for formatting.
17) Ctrl + F for find, find/replace
18) Ctrl + D to delete a line
19) Ctrl + Q for going to last edited place

Miscellaneous Eclipse Shortcuts

These are different Eclipse keyboard shortcuts which doesn’t fit on any category but quite helpful and make life very easy while working in Eclipse.

20) Ctrl + T for toggling between supertype and subtype
21) Go to other open editors: Ctrl + E.
22) Move to one problem (i.e.: error, warning) to the next (or previous) in a file: Ctrl +. For next, and Ctrl +, for the previous problem
23) Hop back and forth through the files you have visited: Alt + ← and Alt + →, respectively.
25) CTRL+Shift+G, which searches the work-space for references to the selected method or variable
26) Ctrl+Shift+L to view listing for all Eclipse keyboard shortcuts.
27) Alt + Shift + j to add Javadoc at any place in java source file.
28) CTRL+SHIFT+P to find closing brace. Place the cursor at the opening brace and use this.
29) Alt+Shift+X, Q to run Ant build file using keyboard shortcuts in Eclipse.
30) Ctrl + Shift +F for Auto-formatting.

Here is the nice image to remember these useful Eclipse shortcuts for Java programmers:



Sunday, July 7, 2024

Twelve-Factor App methodology applying the Developing a Microservice with Spring Boot


12-Factor App Methodology

The 12-Factor App methodology is a set of best practices for building modern web-based applications. It provides guidelines for creating scalable, maintainable, and portable applications that can be deployed across various environments. Here are the twelve factors with examples:

1. Codebase

One codebase tracked in revision control, many deploys. Example: A single Git repository for your e-commerce application that includes all code for various environments (development, staging, production). Branches can be used for feature development and bug fixes.
git clone https://github.com/username/ecommerce-app.git

2. Dependencies

Explicitly declare and isolate dependencies. Example: Using pom.xml in a Maven-based Java project to declare dependencies.
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.5.4</version>
</dependency>

3. Config

Store config in the environment. Example: Using environment variables to manage configuration.
# application.properties
spring.datasource.url=${DATABASE_URL}
spring.datasource.username=${DATABASE_USERNAME}
spring.datasource.password=${DATABASE_PASSWORD}
Setting environment variables:
export DATABASE_URL=jdbc:mysql://localhost:3306/mydb
export DATABASE_USERNAME=root
export DATABASE_PASSWORD=secret

4. Backing Services

Treat backing services as attached resources. Example: Configuring a database connection in Spring Boot.
spring.datasource.url=${DATABASE_URL}
This allows you to switch databases easily without changing the code.

5. Build, Release, Run

Strictly separate build and run stages. Example: Using Jenkins to manage build and release pipelines. Build stage: Compile the code, run tests, and package the application.
mvn clean package
Release stage: Combine the build with environment-specific configuration.
java -jar target/myapp.jar --spring.config.location=/path/to/config/
Run stage: Execute the application.
java -jar target/myapp.jar

6. Processes

Execute the app as one or more stateless processes. Example: Running a Spring Boot application as a stateless process.
java -jar target/myapp.jar
State (like session data) is stored in external services like Redis.

7. Port Binding

Export services via port binding. Example: Configuring a Spring Boot application to run on a specific port.
server.port=8080
Accessing the application:
curl http://localhost:8080

8. Concurrency

Scale out via the process model. Example: Running multiple instances of a Spring Boot application using Docker.
docker run -d -p 8080:8080 myapp:latest
docker run -d -p 8081:8080 myapp:latest
Load balancing these instances using Nginx or another load balancer.

9. Disposability

Maximize robustness with fast startup and graceful shutdown. Example: Implementing graceful shutdown in Spring Boot.
@Bean
public ServletWebServerFactory servletContainer() {
    TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
    tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> {
        connector.setProperty("server.shutdown.graceful", "true");
    });
    return tomcat;
}

10. Dev/Prod Parity

Keep development, staging, and production as similar as possible. Example: Using Docker to ensure the same environment in all stages.
docker build -t myapp:latest .
docker run -e DATABASE_URL=jdbc:mysql://localhost:3306/mydb myapp:latest

11. Logs

Treat logs as event streams. Example: Using a logging framework like Logback to write logs to stdout.
<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss} - %msg%n</pattern>
        </encoder>
    </appender>
    <root level="info">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>

12. Admin Processes

Run admin/management tasks as one-off processes. Example: Running a database migration using Flyway in a Spring Boot application.
java -cp myapp.jar org.flywaydb.core.Flyway migrate


Developing a Microservice with Spring Boot: Applying the Twelve-Factor Methodology

Developing a microservice using Spring Boot involves several steps, from setting up your development environment to implementing features and ensuring the application adheres to best practices, including the twelve-factor methodology. Here's a step-by-step guide:

Step 1: Set Up Your Development Environment

  1. Install JDK: Ensure you have Java Development Kit (JDK) installed. Spring Boot typically requires JDK 8 or later.
  2. Install an IDE: Use an Integrated Development Environment (IDE) like IntelliJ IDEA, Eclipse, or Visual Studio Code.
  3. Install Maven/Gradle: These build tools help manage project dependencies and build lifecycle. Maven is commonly used with Spring Boot.

Step 2: Create a Spring Boot Application

  1. Initialize the Project:
    • Use Spring Initializr (https://start.spring.io/) to generate a basic Spring Boot project. Select dependencies such as Spring Web, Spring Data JPA, and any database connector (e.g., H2, MySQL).
    • Download the generated project and import it into your IDE.
  2. Structure Your Project: A typical Spring Boot project follows the Maven structure:
    ├── src
    │   ├── main
    │   │   ├── java
    │   │   │   └── com
    │   │   │       └── example
    │   │   │           └── mymicroservice
    │   │   │               ├── MyMicroserviceApplication.java
    │   │   │               ├── controller
    │   │   │               ├── service
    │   │   │               └── repository
    │   │   ├── resources
    │   │       └── application.properties
    │   └── test

Step 3: Develop Your Microservice

  1. Define Models: Create Java classes representing your data model.
    package com.example.mymicroservice.model;
    
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    
    @Entity
    public class Product {
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;
        private String name;
        private Double price;
    
        // getters and setters
    }
  2. Create Repositories: Use Spring Data JPA to handle database interactions.
    package com.example.mymicroservice.repository;
    
    import com.example.mymicroservice.model.Product;
    import org.springframework.data.jpa.repository.JpaRepository;
    
    public interface ProductRepository extends JpaRepository<Product, Long> {
    }
  3. Implement Services: Write business logic in service classes.
    package com.example.mymicroservice.service;
    
    import com.example.mymicroservice.model.Product;
    import com.example.mymicroservice.repository.ProductRepository;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    @Service
    public class ProductService {
    
        @Autowired
        private ProductRepository productRepository;
    
        public List getAllProducts() {
            return productRepository.findAll();
        }
    
        public Product getProductById(Long id) {
            return productRepository.findById(id).orElse(null);
        }
    
        public Product saveProduct(Product product) {
            return productRepository.save(product);
        }
    
        public void deleteProduct(Long id) {
            productRepository.deleteById(id);
        }
    }
  4. Create Controllers: Define REST endpoints to handle HTTP requests.
    package com.example.mymicroservice.controller;
    
    import com.example.mymicroservice.model.Product;
    import com.example.mymicroservice.service.ProductService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.*;
    
    import java.util.List;
    
    @RestController
    @RequestMapping("/products")
    public class ProductController {
    
        @Autowired
        private ProductService productService;
    
        @GetMapping
        public List getAllProducts() {
            return productService.getAllProducts();
        }
    
        @GetMapping("/{id}")
        public Product getProductById(@PathVariable Long id) {
            return productService.getProductById(id);
        }
    
        @PostMapping
        public Product createProduct(@RequestBody Product product) {
            return productService.saveProduct(product);
        }
    
        @DeleteMapping("/{id}")
        public void deleteProduct(@PathVariable Long id) {
            productService.deleteProduct(id);
        }
    }

Step 4: Apply the Twelve-Factor Methodology

  1. Codebase: One codebase tracked in version control, many deploys. Use a version control system like Git.
  2. Dependencies: Explicitly declare and isolate dependencies. Manage dependencies using Maven or Gradle.
  3. Config: Store config in the environment.
    server.port=8080
    spring.datasource.url=jdbc:mysql://localhost:3306/mydb
    spring.datasource.username=root
    spring.datasource.password=secret
  4. Backing Services: Treat backing services as attached resources. Configure external resources (e.g., databases, message brokers) using environment variables.
  5. Build, Release, Run: Strictly separate build and run stages. Use CI/CD pipelines to automate the build and deployment process.
  6. Processes: Execute the app as one or more stateless processes. Ensure the application is stateless, storing any needed state in a database or external service.
  7. Port Binding: Export services via port binding. Spring Boot applications bind to a port and serve requests.
  8. Concurrency: Scale out via the process model. Scale the application horizontally by running multiple instances.
  9. Disposability: Maximize robustness with fast startup and graceful shutdown. Implement graceful shutdown and ensure the application can handle interruptions.
  10. Dev/Prod Parity: Keep development, staging, and production as similar as possible. Use Docker or similar technologies to ensure consistency across environments.
  11. Logs: Treat logs as event streams. Use a logging framework like Logback and externalize logs to a centralized logging system.
  12. Admin Processes: Run admin/management tasks as one-off processes. Use tools like Spring Boot Actuator for management and monitoring.

Step 5: Testing and Deployment

  1. Write Tests: Implement unit tests, integration tests, and end-to-end tests.
    package com.example.mymicroservice;
    
    import com.example.mymicroservice.model.Product;
    import com.example.mymicroservice.service.ProductService;
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    
    import static org.junit.jupiter.api.Assertions.assertNotNull;
    
    @SpringBootTest
    class MyMicroserviceApplicationTests {
    
        @Autowired
        private ProductService productService;
    
        @Test
        void testGetAllProducts() {
            assertNotNull(productService.getAllProducts());
        }
    }
  2. Package and Deploy: Package the application as a JAR or WAR file and deploy it to your server or cloud platform.
    mvn clean package

Step 6: Monitoring and Maintenance

  1. Monitoring: Use tools like Prometheus and Grafana for monitoring application performance.
  2. Logging: Implement centralized logging using tools like ELK Stack (Elasticsearch, Logstash, Kibana).
  3. Security: Regularly update dependencies and use security practices like OAuth2 for authentication and authorization.
By following these steps and adhering to the twelve-factor methodology, you can develop a robust, scalable, and maintainable microservice using Spring Boot.

Friday, June 26, 2020

Lombok with Spring Tool Suite 4

I have installed Lombok in Spring Tool Suite 4 just some days ago for Mac and Windows and no issues.

Project Lombok is a Java library tool that generates code for minimizing boilerplate code. The library replaces boilerplate code with easy-to-use annotations.

Download the lombok.jar 

  • 👉 Execute  java -jar lombok.jar 
    • Note: normally or by default, it does not find the installer, it is the common scenario in my experience.
  • 👉 Press the Specify Location button. 
    • Note: for Mac, go to the Contents directory within the .app file and find the  STS.ini  file, it could be  SpringToolSuite4.ini  too.
    • Conclusion: therefore for any OS, the goal is find the unique file with the  .ini  extension
    • Normally, I do this after IDE closed.

👉 Once done with the installation, Add following dependency to your project  pom.xml , restart your Spring Tool Suite 4 and after 5 mins all the Lombok packages will be available in your workspace to use Lombok annotations.


<dependencies>
         <dependency> 
                 <groupid>org.projectlombok</groupid> 
                 <artifactid>lombok</artifactid> 
                 <version>1.18.12</version> 
                 <scope>provided</scope> 
        </dependency> 
</dependencies>


Follow this https://projectlombok.org/setup/eclipse for more information to install Lombok in various Compilers, Build tools,  IDEs & Platforms.

Lombok Features

For example, by adding a couple of annotations, you can get rid of code clutters, such as getters and setters methods, constructors, hashcode, equals, and toString methods, and so on. 


val

Finally! Hassle-free final local variables.

var

Mutably! Hassle-free local variables.

@NonNull

or: How I learned to stop worrying and love the NullPointerException.

@Cleanup

Automatic resource management: Call your close() methods safely with no hassle.

@Getter/@Setter

Never write public int getFoo() {return foo;} again.

@ToString

No need to start a debugger to see your fields: Just let lombok generate a toString for you!

@EqualsAndHashCode

Equality made easy: Generates hashCode and equals implementations from the fields of your object..

@NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor

Constructors made to order: Generates constructors that take no arguments, one argument per final / non-nullfield, or one argument for every field.

@Data

All together now: A shortcut for @ToString@EqualsAndHashCode@Getter on all fields, and @Setter on all non-final fields, and @RequiredArgsConstructor!

@Value

Immutable classes made very easy.

@Builder

... and Bob's your uncle: No-hassle fancy-pants APIs for object creation!

@SneakyThrows

To boldly throw checked exceptions where no one has thrown them before!

@Synchronized

synchronized done right: Don't expose your locks.

@With

Immutable 'setters' - methods that create a clone but with one changed field.

@Getter(lazy=true)

Laziness is a virtue!

@Log

Captain's Log, stardate 24435.7: "What was that line again.?

Monday, December 3, 2018

Best tips to be a Better Java Developer


If you are a Java developer in early phases of your career, here are some concepts you should read about and learn to be an outstanding Java developer.

All books have been written about these concepts. We will just summarise them here and encourage you to find and read more about them.

1. Thread Safety
All web-applications are multi-threaded applications. If you didn’t know, read about how application containers e.g. Tomcat start a new thread or pick one from a thread pool, to render a new web request. Thread safety is about ensuring access to shared resources is serializable. The most common thread safety mistake? Declaring a private field on a singleton class in your application which is changed by multiple threads.

2. Functional Programming
This came late to Java, specifically in version 1.8. But you should learn and use Streams & Lambda functions in your programs. They make for readable, elegant & concise code, often with improved performance.

3. Thread Local variables
Thread safety was about accessing shared variables safely. Thread local allows you to do just that. Think of them as a HashMap of variables by thread id. However, handle their initialization and clean up with care, especially when using thread pools or you can get into thread safety issues and memory leaks.

4. Mapped Diagnostic Contexts in Logging
Underlying, this works as a thread local variable. But you don’t have to worry about it because most logging frameworks will support it out of the box. The idea is to start and end contexts when logging messages. For instance, at the entry of a request, you can log the API URL and user id, so the logs inside would always carry that context.

5. Understand Classpath
It seems easy. But can cause problems or be the reason for some weird effects such as – Why does this work on my local but not on production? It may be because of class-path ordering wherein a production application container loaders an older jar from a shared class-path.

6. Class-path & Class Loaders
Class loaders work as a hierarchy. Learn about class-loaders that come with running an application in tomcat. Find if the same class can be loaded twice in memory and how.

7. Hot Loading
Did you know JVM supports hot reloading of Java classes? You change the code and then don’t have to re-compile everything and restart the application. Just the class changed is recompiled and its in-memory byte-code is updated. Find which cases this can happen and configure it in your development environment if you haven’t already.

8. Dependency Injection
You don’t call me. I call you. That’s inversion of control and the principle behind dependency injection, popularised by Spring Framework. You already knew it, but do you know the alternative to dependency injection? Learn and understand why dependency injection is better and leads to more extensible and testable code.

9. Properties
You know about properties files. But what are the principles to decide if something should be a system property, an environment variable or a command line argument? The hint is in runtime i.e. when does the property become available and is provided. Nevertheless, you should know how to accept and use each and override when needed e.g. in a test environment.

10. Fat Jar Deployment
Most application frameworks, spring boot comes to mind, have an embedded container deployment mode. That is a DevOps friendly way to deploy on the cloud, instead of tweaking application container settings. Even if there is an operations team managing deployment for you, learn it as its the way forward.

11. ORM & Persistence
ORM (JPA & Hibernate) give you convenience and power. And often people shoot themselves in their leg with it. Learn to use them responsibly and without performance impact. Transaction boundaries, Lazy vs Eager fetching, different types of caching and how to debug performance. But most importantly, when not to use an ORM and just write a SQL query. Hint – when the amount of data is large or is distributed in too many tables.

12. Fault Tolerance and Isolation
Let’s say one of your application API calls another rest API. If the other rest API becomes slow, will your application go down? It will. Because of the slow API, all threads will be consumed and your application will become unresponsive. So design it to be fault tolerant with proper timeouts. You can make it more robust by using Resilience4j that allows setting up retry & fallback, circuit breakers, rate limiters and more.

13. Deployment and run-time environment
Do you know how your application works in production? Whether its a Paas like Heroku or Iaas like AWS, you should know the memory available, available CPUs, disk latency, network latency within different components to design a performant application.

14. Monitoring
Will you know if some API in your application is slow? What are the key performance indicators you should monitor? You can use an APM provider like New Relic, or build your own health checks and metrics using spring boot actuator.

15. Build Lifecycle and Dependency Management
Can you configure a new java project by hand using Maven or Gradle? Setup development and production environment configuration, create build lifecycles tasks to run checkstyle or find bugs, create build commands to run test-cases and generate coverage and so on.

16. Debugging Setup
Many developers do not know how to set this up.  This is a must when running test-cases, but JVM also allows remote debugging by opening up a port your IDE can connect to. Learn how to set it up and you will be finding bugs 10 times faster than your teammates who don’t have it set up.

17. Know your IDE
Whether its Eclipse or IntelliJ, shame on you if you can’t set up a new or existing project in your IDE. The ideas IDE setup will have static code analyser, run and debug test environment, can connect to debug a running JVM with has libraries source code also downloaded. A good workman knows their tools.

18. Learn to Refactor SensiblyMost code is not perfect. Learn to improve some of it as you go, but not all of it in one go. Unlike the others, this one will take time and experience to master. 
Start today.

©hashedin.com

Works

What can I do


Branding

Social media Branding is far and away the best technique a company has to boost engagement with its customer base. Even a minimum of involvement, such as making one post a day.

Web Design

Web design is the process of creating websites. It encompasses several different aspects, including webpage layout, content production, and graphic design.

Development

Web Development refers to building, creating, and an maintaining websites. It includes aspects such as web design, web publishing, web programming and database management.

Graphic Design

Graphic design is the process of visual communication and problem-solving through the use of typography, photography, and illustration. The field is considered a subset of visual communication and communication design.

Photography

Photography is the art, application and practice of creating durable images by recording light or other electromagnetic radiation, either electronically by means of an image sensor, or chemically by means of a light-sensitive material such as photographic film.

User Experience

User experience (UX) design is the process design teams use to create products that provide meaningful and relevant experiences to users. This involves the design of the entire process of acquiring and integrating the product, including aspects of branding, design.

Contact

Get in touch with me


Adress/Street

Bangalore, India