Skip to main content

Posts

Showing posts from 2021

RADUS#5 - Unit testing controller

  As we have written few methods in our controller, let's write quick unit tests for couple of methods: @RunWith (SpringRunner . class) @WebMvcTest (TodoController . class) public class TodoControllerTest { @Autowired private MockMvc mvc; @MockBean private TodoServiceImpl todoService; private final String BASE_PATH_V1 = "/api/1/0" ; @Test public void testHello() throws Exception { mvc . perform( get(BASE_PATH_V1 + "/hello" )) . andExpect(status() . isOk()) . andExpect(content() . string( "Hello Rest demo" )); } @Test public void testGetUsers() throws Exception { // Mock setup Map < Integer, String > expected = new HashMap <> (); expected . put( 1 , "Todo - 1" ); expected . put( 2 , "Todo - 2" ); Mockito . when(todoService . getTodos()) . thenReturn(expected); //...

RADUS#4 - Caching the response in REST API's

  Caching in spring boot app: Caching can be used to provide a performance boost to your application users by avoiding the business logic processing involved again and again, load on your DB, requests to external systems if the users request data that's not changed frequently Different types of caching: We'll be focusing more on in-memory caching in this post i listed other options available to have an idea. In-memory caching You'll have a key-value data stores that stores the response of the request after it is served for the first time There are multiple systems like Redis, Memcached that do this distributed caching very well By default Spring provides concurrent hashmap as default cache, but you can override CacheManager to register external cache providers. Database caching Web server caching Dependencies needed: Maven < dependency > < groupId > org . springframework . boot </ groupId > < artifactId > spring - boot - starter - cache ...

RADUS#3 - CRUD and REST API's (focus on HTTP Methods, Annotations and no DB)

  90% of the time services does CRUD operations with REST over HTTP protocol so in this post we'll look into different HTTP methods and annotations we can use to communicate with the service to perform crud operations.  We'll be building a simple todo API where you can: Create a todo (method: HTTP POST, endpoint: **/api/1/0/todos) Read list of todos (method: HTTP GET, endpoint: **/api/1/0/todos) Read a single todo (method: HTTP GET, endpoint: **/api/1/0/todos/{id}) Delete a todo (method: HTTP DELETE, endpoint: **/api/1/0/todos/{id}) **To keep things simple and not shift the focus out of the controller class, we will store all these todos in in-memory using a simple Map controller code using java: package com . artifactsbyrake . restdemo . controller ; import org.springframework.http.HttpStatus ; import org.springframework.http.ResponseEntity ; import org.springframework.util.ObjectUtils ; import org.springframework.web.bind.annotation.* ; import org.springframework...

RADUS#2 - Important classes and Annotations

Once we extract the project into our IDE you'll notice couple of classes already created. Let's focus on one of the important class called Application class, which does all the magic to run your spring boot application package com . artifactsbyrake . restdemo ; import org.springframework.boot.SpringApplication ; import org.springframework.boot.autoconfigure.SpringBootApplication ; @SpringBootApplication public class RestdemoApplication { public static void main ( String [] args ) { SpringApplication . run ( RestdemoApplication . class , args ); } } Notice the main method in the above class which is used to launch the spring application Also pay attention to the annotation " @SpringBootApplication ", this is used to identify the Application class in spring boot What does spring boot do when it runs the app? To run an application, spring does the following things on application start-up: Create's instance of Spring's ApplicationCo...

RADUS#1 - Create Spring Boot App

  To develop REST API's we will be using a spring boot to quickly bootstrap an application and add all the dependencies needed to develop the API's Different ways of creating a spring boot app:  CLI (Command Line Interface) IDE (Eclipse, IDEA, STS...) The above two are not so popular but most developers create spring application using the web app  start.spring.io start.spring.io  provides different options while creating the application. You can choose: Project: Maven, Gradle Language: Java, Kotlin, Groovy Spring Boot Version Project Metadata Group Artifact Name Description Package Name Packaging (Jar, War) Java version Dependencies - Based on the application type you're developing you can choose different dependencies to include in your project Here's a screenshot of an example project i'm creating:   select all the options as shown above click Generate and this will download a zip file of the project  import the project into an IDE that supports Spring Bo...

Types of Mobile Apps

  Different types of mobile apps: Happy Coding  👨‍💻

Spring Boot - RestTemplate PATCH request fix

  In Spring Boot, you make a simple http request as below: 1. Define RestTemplate bean @Bean public RestTemplate restTemplate () { return new RestTemplate (); } 2. Autowire RestTemplate wherever you need to make Http calls @Autowire private RestTemplate restTemplate ; 3. Use auto-wired RestTemplate to make the Http call restTemplate . exchange ( "http://localhost:8080/users" , HttpMethod . POST , httpEntity , String . class ); Above setup works fine for all Http calls except PATCH. The following exception occurs if you try to make a PATCH request as above Exception: I / O error on PATCH request for \ "http://localhost:8080/users\" : Invalid HTTP method: PATCH ; nested exception is java . net . ProtocolException : Invalid HTTP method: PATCH Cause: Above exception happens because of the HttpURLConnection used by default in Spring Boot RestTemplate which is provided by the standard JDK HTTP library. More on this at this  bug Fix: This can b...

Cheatsheet: Kubernetes (K8s)

Namespaces: - Namespaces are used as a means to separate k8s resources Create Namespace kubectl create ns <--namespace--> Get all namespaces kubectl get namespaces Pod: - Pod allows you to run the application in a container - Usually the config for pods are defined in YAML, but you can create a quick pod using " run" command. kubectl run <--pod-name--> --image=nginx:2.3.5 --restart=Never --port=80 --namespace=<--namespace--> View pods details kubectl get pod -n <--namespace--> Describe pod: - This will provide much deeper insight into the pod kubectl describe pod -n <--namespace--> Modify pod *Replace xyzPod with your pod name below   kubectl set image pod xyzPod xyzPod=nginx --namespace=<--namespace--> Check Pod status: kubectl get pod -n <--namespace--> Shell into container: kubectl exec <--pod-name--> -it --namespace=<--namespace--> -- /bin/sh - exit from shell #exit Access Pod logs: kubectl logs <--pod-name--> -n...

Filter in Spring Boot

  We often share few common validations, logging scenarios, modify data for every request/response. To cover these scenarios with some common code, we need to intercept the incoming request and the outgoing response. To intercept the request-response, we can use the Filter interface provided in javax.servlet package. Methods provided by Filter interface:     -  init This method is invoked only once @Override public void init ( FilterConfig filterConfig ) throws ServletException { }     -  doFilter Invoked each time whenever client sends a request or server sends a response.  We can perform all our logic in this method @Override public void doFilter ( ServletRequest request , ServletResponse response , FilterChain chain ) throws IOException , ServletException { }     -  destroy clean up and removes filter from service @Override public void destroy () { } Dependencies that are needed to define filter in Sp...