Showing posts with label SpringBoot. Show all posts
Showing posts with label SpringBoot. Show all posts

June 11, 2024

Replace H2 with a real database in spring boot application

Springboot application facing bellow error or need to implement real test data base:

Senario:

Could not prepare statement [Table “XXXX” not found (this database is empty); SQL statement

Solution:

Add bellow configuration in test application.yml
spring:
 test: 
  database:
       replace: none

---

Code:

@DataJpaTest @TestPropertySource(properties = { "spring.test.database.replace=none", "spring.datasource.url=jdbc:tc:postgresql:16-alpine:///db" //Need to update based on the database })

Plugins:

testImplementation("org.springframework.boot:spring-boot-testcontainers")
testImplementation("org.testcontainers:junit-jupiter")
testImplementation("org.testcontainers:mariadb")

Test containers:

 https://testcontainers.com/






References:

test container examples here


Read more ...

August 01, 2021

Spring Boot question and explanations

 Question: What is diff BeanFactory and ApplicationContextFactory?

Solution:

The Spring Framework comes with two IOC containers – BeanFactory and ApplicationContext. The BeanFactory(Lazy Loading is the most basic version of IOC containers, and the ApplicationContext ( Eager Loading) extends the features of BeanFactory.BeanFactory loads beans on-demand, while ApplicationContext loads all beans at startup. 

Ex:  

Resource res = new ClassPathResource("ioc-container-difference-example.xml"); BeanFactory factory = new XmlBeanFactory(res); 

Student student = (Student) factory.getBean("student");

Or 

ApplicationContext context = new ClassPathXmlApplicationContext("ioc-container-difference-example.xml");

Reference: https://www.baeldung.com/spring-beanfactory-vs-applicationcontext

 

Question: What Is Spring Security?

Solution:

Spring Security is a separate module of the Spring framework that focuses on providing authentication and authorization methods in Java applications. It also takes care of most of the common security vulnerabilities such as CSRF attacks.

To use Spring Security in web applications, we can get started with the simple annotation @EnableWebSecurity.

For more information, we have a whole series of articles related to security.

Question: Name Some of the Design Patterns Used in the Spring Framework?

Solution:

  • Singleton Pattern – singleton-scoped beans
  • Factory Pattern – Bean Factory classes
  • Prototype Pattern – prototype-scoped beans
  • Adapter Pattern – Spring Web and Spring MVC
  • Proxy Pattern – Spring Aspect-Oriented Programming support
  • Template Method Pattern – JdbcTemplateHibernateTemplate, etc.
  • Front Controller – Spring MVC DispatcherServlet
  • Data Access Object – Spring DAO support
  • Model View Controller – Spring MVC

Reference: https://www.baeldung.com/spring-interview-questions

 

Question: Spring WebFlux?

Solution:

The original web framework included in the Spring Framework, Spring Web MVC, was purpose-built for the Servlet API and Servlet containers. The reactive-stack web framework, Spring WebFlux, was added later in version 5.0. It is fully non-blocking, supports Reactive Streams back pressure, and runs on such servers as Netty, Undertow, and Servlet 3.1+ containers.

Reference: https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html#webflux



Question: Spring REST – HTTP OPTIONS Request Handler Example

Solution:

HTTP OPTIONS Method

The HTTP OPTIONS method is used to describe the communication options for the target resource. This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.

  • If the Request-URI is an asterisk (“*”), the OPTIONS request is intended to apply to the server in general rather than to a specific resource.
  • If the Request-URI is not an asterisk, the OPTIONS request applies only to the options that are available when communicating with that resource.
  • Responses to this method are not cacheable.


@RequestMapping(value="/buckets", method = RequestMethod.OPTIONS)

    ResponseEntity<?> collectionOptions() 

    {

         returnResponseEntity

                 .ok()

                 .allow(HttpMethod.GET, HttpMethod.POST, HttpMethod.OPTIONS)

                 .build();

    }

 

Reference: https://howtodoinjava.com/spring-rest/http-options-request-handler/


Question: Spring – Inversion of Control vs Dependency Injection

Solution:

What is Inversion of Control (IoC)

In traditional programming, the flow of the business logic is determined by objects that are statically assigned to one another. With inversion of control, the flow depends on the object graph that is instantiated by the assembler and is made possible by object interactions being defined through abstractions. The binding process is achieved through dependency injection, although some argue that the use of a service locator also provides inversion of control.

Inversion of control as a design guideline serves the following purposes:

  1. There is a decoupling of the execution of a certain task from implementation.
  2. Every module can focus on what it is designed for.
  3. Modules make no assumptions about what other systems do but rely on their contracts.
  4. Replacing modules has no side effect on other modules.

What is Dependency Injection (DI)

IoC is a design paradigm with the goal of giving more control to the targeted components of your application, the ones getting the work done. While Dependency injection is a pattern used to create instances of objects that other objects rely on without knowing at compile time which class will be used to provide that functionality. IoC relies on dependency injection because a mechanism is needed in order to activate the components providing the specific functionality.

How to implement IoC

In object-oriented programming, there are several basic techniques to implement inversion of control. These are:

  1. using a factory pattern
  2. using a service locator pattern
  3. using a dependency injection of any given below type:
    • a constructor injection
    • a setter injection
    • an interface injection

Inversion of control in Spring

The org.springframework.beans and org.springframework.context packages provide the basis for the Spring Framework’s IoC container. The BeanFactory interface provides an advanced configuration mechanism capable of managing objects of any nature. The ApplicationContext interface builds on top of the BeanFactory (it is a sub-interface) and adds other functionality such as easier integration with Spring’s AOP features, message resource handling (for use in internationalization), event propagation, and application-layer specific contexts such as the WebApplicationContext for use in we

Reference: https://stackoverflow.com/questions/3715967/when-should-we-call-system-exit-in-java


Question: What  is System.exit()?

Solution:

The java.lang.System.exit() method exits current program by terminating running Java virtual machine. This method takes a status code. A non-zero value of status code is generally used to indicate abnormal termination. This is similar exit in C/C++.

Following is the declaration for java.lang.System.exit() method:

public static void exit(int status)

exit(0) : Generally used to indicate successful termination.
exit(1) or exit(-1) or any other non-zero value – Generally indicates unsuccessful termination.


Additional info:

System.exit(0);

System.out.println("This line will never be reached");


System.exit(0) terminates the JVM. The parameter is passed back to the OS and is normally used to indicate abnormal termination (eg some kind of fatal error), so if you called java from a batch file or shell script you'd be able to get this value and get an idea if the application was successful.

System.exit(42)  == A script that called the application. Works in Windows, Unix and all other scriptable environments.


Reference: https://www.geeksforgeeks.org/system-exit-in-java/


Question: What is spring bean lifecycle?

Solution:


Bean life cycle is managed by the spring container. When we run the program then, first of all, the spring container gets started. After that, the container creates the instance of a bean as per the request, and then dependencies are injected. And finally, the bean is destroyed when the spring container is closed

  

Reference: https://www.geeksforgeeks.org/bean-life-cycle-in-java-spring/

https://reflectoring.io/spring-bean-lifecycle/


Question: Error Handling for REST with Spring  or Spring Boot @ControllerAdvice

Solution:

There are couple of ways to handle exception in springbok

Solution 1: the Controller-Level @ExceptionHandler

Solution 2: the HandlerExceptionResolver

Solution 3: @ControllerAdvice

Solution 4: ResponseStatusException (Spring 5 and Above)

Handle the Access Denied in Spring Security


Default Spring Boot Support exception messages:

In a nutshell, it serves a fallback error page for browsers (a.k.a. the Whitelabel Error Page) and a JSON response for RESTful, non-HTML requests:

{

    "timestamp": "2019-01-17T16:12:45.977+0000",

    "status": 500,

    "error": "Internal Server Error",

    "message": "Error processing the request!",

    "path": "/my-endpoint-with-exceptions"

}


Using @ControllerAdvice:

  • SpringBoot @ControllerAdvice tutorial shows how to use @ControllerAdvice annotation to manage exceptions in a Spring Boot application.
  • @ControllerAdvice is a specialization of the @Component annotation which allows to handle exceptions across the whole application in one global handling component. It can be viewed as an interceptor of exceptions thrown by methods annotated with @RequestMapping and similar.
  • ResponseEntityExceptionHandler is a convenient base class for @ControllerAdvice classes that wish to provide centralized exception handling across all @RequestMapping methods through @ExceptionHandler methods. It provides an methods for handling internal Spring MVC exceptions. It returns a ResponseEntity in contrast to DefaultHandlerExceptionResolver which returns a ModelAndView.


Using the Controller-Level @ExceptionHandler:

The first solution works at the @Controller level. We will define a method to handle exceptions and annotate that with @ExceptionHandler:

public class FooController{

    //...

    @ExceptionHandler({ CustomException1.class, CustomException2.class })

    public void handleException() {

        //

    }

}

Reference: https://zetcode.com/springboot/controlleradvice/

https://www.baeldung.com/exception-handling-for-rest-with-spring


Read more ...

July 31, 2021

AWS S3 CURD Operations using spring boot

AWS S3 CURD Operations including spring boot actuator features

README file mentioned to run procedure

GITURL: https://github.com/ramanujadasu/aws-curd-apis

GIT SSH link:

git@github.com:ramanujadasu/aws-curd-apis.git


Spring Boot AWS Cloud Support

https://spring.io/projects/spring-cloud-aws#overview

 

Samples:

https://github.com/spring-cloud-samples

https://github.com/ramanujadasu/aws-refapp

Read more ...

November 23, 2018

How to encrypt values in application properties in spring boot application (using Jasypt)

Jasypt (Java Simplified Encryption) Spring Boot provides utilities for encrypting property sources in Boot applications. In this article, we’ll discuss how we can add jasypt-spring-boot‘s support and use it. For more information on using Jasypt as a framework for encryption, take a look at our Introduction to Jasypt here.

Why Jasypt?
Whenever we need to store sensitive information in the configuration file – that means we’re essentially making that information vulnerable; this includes any kind of sensitive information, such as credentials, but certainly a lot more than that.
By using Jasypt, we can provide encryption for the property file attributes and our application will do the job of decrypting it and retrieving the original value.
Unfortunately we can't use user personal values plain text in application.properties file.
Jasypt (Java Simplified Encryption) is a java library which allows the developer to add basic encryption capabilities to his/her projects with minimum effort, and without the need of having deep knowledge on how cryptography works.

First, add the related dependency to the project. I am using maven so I will add the maven dependency to my pom.xml
https://mvnrepository.com/artifact/com.github.ulisesbocchio/jasypt-spring-boot-starter

    com.github.ulisesbocchio
    jasypt-spring-boot-starter
    2.0.0

In the application.properties (or yaml), we will write our encrypted properties between parenthesis and put ENC keyword before it. Like;
MyProperty=ENC(23ClLWiedLx8v6XT6Wk+Bg==)

How to generate those encrpyted values? We will use Jasypt for that! Go to http://www.jasypt.org/ and download the latest version. When you are done, go into jasypt\bin and use the encrypt.sh or encrypt.bat to encrypt your variables. There are several algorithms to pick but I will leave it as default and only give my property value and secret to encrpyt it.

We only need to add @EnableConfigurationProperties annotation to our application and jasypt will automaticly detect encrypted values and decrypt them before they are being used. The CommandLineRunner I have added below is just to test the decryption mechanism.

@EnableEncryptableProperties
@SpringBootApplication
public class JasyptExampleApplication {

  public static void main(String[] args) {
    SpringApplication.run(JasyptExampleApplication.class, args);
  }
 
  @Component
  public class MyRunner implements CommandLineRunner {
   
    @Value("${myProperty}")
    private String myProperty;

    @Override
    public void run(String... args) throws Exception {
      System.out.println("My property is = " + myProperty);
    }
   
  }
}

But if you run your code like this, you will get the below error:
Error creating bean with name 'demo.JasyptExampleApplication$MyRunner': Injection of autowired dependencies failed; nested exception is java.lang.IllegalStateException: Required Encryption configuration property missing: jasypt.encryptor.password
This is because Jasypt needs to know the secret(password) to decrypt the property. We can tell this to our program several ways:
1- We can give it as a command line argument when running the application;
–jasypt.encryptor.password=MY_SECRET
2- We can set it as an environment variable, this is also useful when you are running your application on Tomcat. You can give it to Tomcat’s setenv.sh file;
export CATALINA_OPTS=”-Djasypt.encryptor.password=MY_SECRET”
You can also unset the environment variable after running the application, so there will be no doorway left behind, at least in a human-readable sense.
3- You can give it in application.properties but this might be the dumbest way as it has no difference with giving the property as plain text.
If you know a better way, write a comment below!


2018-04-25 14:03:26.948 INFO 10028 --- [ main] demo.JasyptExampleApplication : Started JasyptExampleApplication in 1.264 seconds (JVM running for 2.06)
My property is MBcoder


As you can see it picked up the PBEWithMD5AndDES algorithm as default value and with the given password, MY_SECRET, it successfully decrypted myProperty
I hope this article was useful, see you another time!

Reference:
https://www.baeldung.com/spring-boot-jasypt
http://mbcoder.com/spring-boot-how-to-encrypt-properties-in-application-properties/
Read more ...

November 08, 2018

Fail to initialize due to unknown Zone Id while running springboot application


Fail to initialize due to unknown Zone Id while running springboot application:

> Errors while running application:

- Application startup failed java.time.zone.ZoneRulesException: Unknown time-zone ID: America/Fort_Nelson

- Caused by: java.time.zone.ZoneRulesException: Unknown time-zone ID: America/Fort_Nelson
at java.time.zone.ZoneRulesProvider.getProvider(ZoneRulesProvider.java:272)
at java.time.zone.ZoneRulesProvider.getRules(ZoneRulesProvider.java:227)
at java.time.ZoneRegion.ofId(ZoneRegion.java:120)


> For using the latest version of Timeshape, the 2018d.3 or 2018d.4: We are facing this issue,



net.iakovlev
timeshape
2018d.5


> After so much analysis, released 2018d.5 where this change is merged and working fine with out any issues.

For applicaiton instalization:

@Component
public class AppStartUpConfig implements ApplicationListener {
@Autowired
TimeZone timeZone;
@Override
public void onApplicationEvent(ApplicationReadyEvent arg0) {
timeZone.setTimeZoneEngine(TimeZoneEngine.initialize());
}
}

In dto:
@GeoSpatialIndexed
private Point geoCoordinates;

For actual usage class:
@Autowired
TimeZone timeZoneEngine;

To get the geoCoordinates:
Optional zoneId = timeZoneEngine.getTimeZoneEngine().query(
geoCoordinates.getY(),
geoCoordinates.getX());
String timezoneId = zoneId.get().getId();


Reference:
https://github.com/RomanIakovlev/timeshape/issues/12

Read more ...

March 28, 2018

Upload a file in cloud space(multipart upload operation) using HttpClient

To use below program, to upload a file easily in could space.
we will illustrate how to do a multipart upload operation using HttpClient.



import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.LinkedHashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItem;
import org.springframework.web.multipart.MultipartFile;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

/**
* This class is used for uploading image in cloud
*/
public class UploadImage {

public static void main(String[] args) throws IOException {
httpImageTest();
//convertFileFromMultipartFile - convert multipart file to file object

     }

    private static void httpImageTest() throws ClientProtocolException, IOException {
        File file = new File(""); //c:/image/test.jpeg
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost("");
        post.addHeader("", "");
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addTextBody("Content-Type", "image/jpeg");
        builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, "fileName.jpeg");

        HttpEntity entity = builder.build();
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        System.out.println(response.getStatusLine());
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null)
            result.append(line);
        System.out.println(formatXML(result.toString()));
        client.close();
    }

private static File convertFileFromMultipartFile(MultipartFile file) throws IOException {
        File convFile = new File(file.getOriginalFilename());
        convFile.createNewFile();
        FileOutputStream fos = new FileOutputStream(convFile);
        fos.write(file.getBytes());
        fos.close();
        return convFile;
    }

    private static String formatXML(String input) {
        try {
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");

            StreamResult result = new StreamResult(new StringWriter());
            DOMSource source = new DOMSource(parseXml(input));
            transformer.transform(source, result);
            return result.getWriter().toString();
        } catch (Exception e) {
            e.printStackTrace();
            return input;
        }
    }

    private static Document parseXml(String in) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            InputSource is = new InputSource(new StringReader(in));
            return db.parse(is);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

Reference: http://www.baeldung.com/httpclient-multipart-upload

Read more ...

My Favorite Site's List

#update below script more than 500 posts