Categories
Git

Git reverted branch is now ready to merge again issue

Note:- always rebase your branch with master before you create PR 🙂.

Lets say you have worked on Defect DEF-143 after you have fixed the issue and is ready to merge with PR and branch name DEF-143 , you will merge the code but just before release to production team decide to revert the your branch changes and release it in upcoming release date. 

In this case since branch DEF-143 was merged and reverted , GIT/Bitbucket will remember the commit ID which was merged , so when you try to recreate the PR to merge you will see no code diff 😦😞. 

what should we do? 

Go to your IDE for me it intelliJ terminal or git terminal where you are in your branch . 

git reset –soft HEAD-1

git add .

git commit –amend  

once you have finished your steps above perform git force push and now the PR will show difference in the code clearly.

The same command is used when you have multiple commit in one branch and you want to Squash all the commits with one commit and create PR. 

why the command above works ? 

Because, above ste of command gives you new commit ID and will not confuse GIT/Bitbucket. 

Categories
Java

Unleash Your Java 8 Superpowers: Code Examples Included!

Are you ready to unleash your Java 8 superpowers? With the latest version of Java, you can do more than ever before. From streamlining your code to improving performance, Java 8 has everything you need to become a Java superhero. In this article, we’ll explore some fun code snippets to help you level up your programming skills and tap into the full potential of Java 8.

Be a Java 8 Superhero!

With Java 8, you have a powerful set of tools at your disposal. Some of the new features introduced in Java 8 include lambda expressions, functional interfaces, and streams. These features allow you to write cleaner, more concise code that is easier to read and understand.

One of the most exciting features of Java 8 is lambda expressions. These expressions allow you to write code that is both concise and expressive. For example, instead of writing out a long, complex method, you can use a lambda expression to simplify the code. This makes it much easier to write, test, and maintain your code.

Learn with These Fun Code Snippets!

Let’s take a look at some fun code snippets to help you learn more about Java 8. First up, we have a simple example of a lambda expression. This expression is used to sort a list of names in alphabetical order:

List names = Arrays.asList("Alice", "Bob", "Charlie", "Dave");
Collections.sort(names, (String a, String b) -> a.compareTo(b));
System.out.println(names);

Next, let’s look at an example of how to use streams in Java 8. In the following code snippet, we use a stream to filter out all the even numbers from a list of integers:

List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List evenNumbers = numbers.stream().filter(n -> n % 2 == 0).collect(Collectors.toList());
System.out.println(evenNumbers);

Finally, let’s explore the power of functional interfaces in Java 8. In this example, we define a functional interface that takes two integers as input and returns the sum of those integers. We then use this interface to create a lambda expression that calculates the sum of two numbers:

@FunctionalInterface
interface Calculator {
    int calculate(int a, int b);
}

Calculator add = (a, b) -> a + b;
System.out.println(add.calculate(5, 10));

These fun code snippets are just the tip of the iceberg when it comes to Java 8. With a little practice and experimentation, you can use these features to write better, more efficient code and become a Java superhero.

Java 8 has opened up a whole new world of possibilities for Java developers. With these powerful new features, you can write cleaner, more concise code that is easier to read and maintain. So go ahead and unleash your Java 8 superpowers – the sky’s the limit!

Categories
Java SpringBoot

How to make API call from SpringBoot application?

To make an API call from a Spring Boot application, you can use the RestTemplate or WebClient class provided by Spring. These classes offer methods for making HTTP requests and handling the responses. Here’s how you can make an API call using RestTemplate:

  1. Add the necessary dependency to your pom.xml file if you haven’t already done so. The RestTemplate class is available in the spring-web module, so make sure you have the following dependency:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
  1. In your Spring Boot application, create an instance of RestTemplate and use its methods to make the API call. You can inject it as a dependency in your class or create a new instance.
@RestController
public class MyRestController {

    private final RestTemplate restTemplate;

    public MyRestController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @GetMapping("/api/call")
    public String makeAPICall() {
        String apiUrl = "https://api.example.com/endpoint";
        ResponseEntity<String> response = restTemplate.getForEntity(apiUrl, String.class);
        return response.getBody();
    }
}
  1. In the above example, the makeAPICall() method sends a GET request to the specified API endpoint (https://api.example.com/endpoint) and retrieves the response as a ResponseEntity object. You can then extract the response body using response.getBody() and return it from the endpoint.
  2. By default, RestTemplate uses a simple HTTP connection pool and blocking I/O. If you’re using Spring Boot 2.1 or later, it’s recommended to use WebClient instead of RestTemplate. The WebClient class is non-blocking and provides a more flexible and reactive approach to making API calls.
@RestController
public class MyRestController {

    private final WebClient webClient;

    public MyRestController(WebClient.Builder webClientBuilder) {
        this.webClient = webClientBuilder.build();
    }

    @GetMapping("/api/call")
    public Mono<String> makeAPICall() {
        String apiUrl = "https://api.example.com/endpoint";
        return webClient.get()
                .uri(apiUrl)
                .retrieve()
                .bodyToMono(String.class);
    }
}
  1. In the WebClient example, the makeAPICall() method returns a Mono<String> instead of a plain String. Mono is a reactive type that represents a potentially asynchronous result. You can handle it asynchronously using reactive programming techniques.

These are the basic steps to make an API call from a Spring Boot application. Depending on your requirements, you can customize the request headers, handle request parameters, handle error responses, and perform other operations using the available methods of RestTemplate or WebClient.

Categories
Java SpringBoot

How to write simple REST API call in SpringBoot

In Spring Boot, you can create RESTful APIs using the Spring Web module, which provides convenient annotations and classes for building RESTful endpoints. Here’s a step-by-step guide to creating a REST API in Spring Boot:

1. Set up a new Spring Boot project or use an existing one. You can use Spring Initializr (https://start.spring.io/) to generate a basic project structure with the required dependencies.

2. Create a new Java class for your REST controller. This class will handle incoming HTTP requests and define the API endpoints. Annotate the class with `@RestController` to indicate that it’s a REST controller.

“`java@RestControllerpublic class MyRestController { // API endpoints will be defined here}“`

3. Define your API endpoints as methods within the controller class. Use appropriate annotations to specify the HTTP method (`@GetMapping`, `@PostMapping`, `@PutMapping`, `@DeleteMapping`, etc.) and the URL path for each endpoint.

“`java@RestControllerpublic class MyRestController { @GetMapping(“/api/greeting”) public String getGreeting() { return “Hello, World!”; } @PostMapping(“/api/user”) public User createUser(@RequestBody User user) { // Process the user object and return a response }}“`

4. In the example above, the `getGreeting()` method handles GET requests to `/api/greeting` and returns a simple greeting string. The `createUser()` method handles POST requests to `/api/user`, expecting a JSON payload in the request body representing a `User` object. You can define your own custom classes like `User` to model the request and response payloads.

5. Within each endpoint method, you can implement the necessary business logic and return the desired response. The response can be a simple string, an object, or a collection of objects. Spring Boot automatically serializes objects to JSON (or XML) based on the request’s `Accept` header.

6. Run your Spring Boot application. By default, Spring Boot will start an embedded Tomcat server that listens for incoming HTTP requests.

7. You can now test your REST API endpoints using a tool like cURL, Postman, or any web browser. For example, to test the `getGreeting()` endpoint, open a browser and navigate to `http://localhost:8080/api/greeting`. You should see the “Hello, World!” message returned.That’s it! You’ve created a basic REST API using Spring Boot. You can add more endpoints, handle request parameters, implement data persistence, and perform other advanced operations as per your application’s requirements.

Categories
Java SpringBoot

SpringBoot DisableSecurityConfiguration

Lets say you have a SpringBoot application and you want to test some functionality but this application is a consumer and you are dependent on Kafka queue or SQS Queue .
In this case you can create a controller and disable the security and call the function in your controller and call this controller using postman .

Code to disable security

import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@Order(1)
public class DisableSecurityConfigurationAdapater extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().antMatcher("/**").authorizeRequests().anyRequest().permitAll();
    }
}

Code for controller (Something like this)

import com.dharmeshpatel.integration.Scheduled.Scheduler;
import javax.annotation.Resource;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/export/")
public class ABCController {

    @Resource
    Scheduler scheduler1;

    @RequestMapping(value = "/startReport", method = RequestMethod.POST)
    public ResponseEntity<String> startExport(@RequestParam(value = "startDate") String startDate,
                                              @RequestParam(value = "endDate") String endDate) {
        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            scheduler1.startExport(startDate, endDate);
            return new ResponseEntity<>("The export WritesReport has started", HttpStatus.OK);
        } else {
            return new ResponseEntity<>(
                "The export WritesReport has not started, startDate expected in format dd-MM-yy",
                HttpStatus.BAD_REQUEST);
        }
    }
}