Home Navigation

Saturday, 12 September 2020

ClassNotFoundException vs NoClassDefFoundError

ClassNotFoundException and NoClassDefFoundError both are runtime exceptions. They occur when a class not found in the classpath. 

ClassNotFoundException:

It is a checked exception. It happens when a program tries to load a class using the Class.forName() or loadClass() or findSystemClass() method. For example class.forName("oracle.jdbc.driver.OracleDriver") and oracle jdbc driver is not present in the classpath the program will try to load the class and throw the classNotFoundException.

Resolution: Make sure you add the related dependencies in the classpath.

NoClassDefFoundError:

It is a fatal error and happens when jvm can not find the definition of the class by instantiating (new keyword) and load a class with method call. The definition is present at the compile time but missing at runtime.

It usually happens when there is an exception while executing a static block or initializing static fields of the class, so class initialization fails.

Resolution: Sometimes, it can be quite time-consuming to diagnose and fix these two problems. 

  • Make sure whether class or jar containing that class is available in the classpath.
  • If it's available on application's classpath then most probably classpath is getting overridden. To fix that we need to find the exact classpath used by our application
  •  Also, if an application is using multiple class loaders, classes loaded by one classloader may not be available by other class loaders.

Ref: https://www.baeldung.com/java-classnotfoundexception-and-noclassdeffounderror

Tuesday, 1 September 2020

Git stash commands

#git stash save “Your stash message” //Git stash with message

Stashing untracked files
#git stash save -u
or
#git stash save --include-untracked

view the list of stashes you made at any time.
#git stash list

#git stash apply // applies the latest stash stash@{0}

if you want some other stash to apply
#git stash apply stash@{2} // third one

#git stash pop   // applies the latest stash stash@{0} and removes it
#git stash pop stash@{1} // applies the second one and removes it


#git stash show // summary of stash diff of the stash content
#git stash show -p // shows full diff of the stash content
#git stash show stash@{1} // specific stash diff and contents

#git stash branch <name> // creates a new branch with latest stash and removes it
#git stash branch <name> stash@{1} // if you want to specify a stash id

#git stash clear // deletes all the stashes made in the repo
#git stash drop stash@{2} // specify id to delete the stash
 

Monday, 20 July 2020

Postgres docker volume backup and restore

They way we are going to backup and restore postgres database docker volume we will use docker exec to get into the container and will use pg_dump utility to achieve our goal.

Postgres volume backup:

start your postgres container using docker or docker-compose.
execute the below command to get the container id
$docker ps

Backup database: 
    $docker exec -u postgres <containerId> pg_dump -Fc -d <databaseName> > dabase-backup.dump

Restore database:
    $docker exec -u <postgresUser> <containerId > psql -c 'DROP DATABASE <databaseName>'

    $docker exec -i -u < postgresUser > <containerId> pg_restore --clean -C -d postgres < dabase-backup.dump


Backup Schema:
    $docker exec -u postgres <containerId> pg_dump -Fc -d <databaseName> -n <schemaName> > schema-db-backup.dump
Restore Schema:
    $docker exec -it -u postgres <containerId> psql 
you will be in interactive mode, in the prompt terminal execute the below commands
    postgres=# \connect bdd
    # drop schema <schemaName> cascade
    # create schema <schemaName>
    \q to quit the interactive mode postgres
    Then execute the below command to reload db
    $docker exec -i -u postgres <containerId> pg_restore --clean -C -d <databaseName> -n <schemaName> < schema-db-backup.dump
Last step, validate your data using a database browser or you can use the below command to get into the database terminal and use sql query to validate your data.

    $docker exec -it -u postgres <containerId> psql 

Friday, 10 July 2020

Spring bean life cycle overview

Spring beans are components which are handled and managed by spring IoC container. When the beans get created it is required to perform some initialization to get the beans usable. And when beans are no longer required and gets removed from IoC needs some clean up.

We define beans in three ways
  • XML Config (Load xml definitions ) -> instantiation & constr injection -> property injection
  • Annotation config ( @Component scanning) -> instantiation & @Autowired on constructor -> injection of @Autowired methods & fields
  • Java Config ( Read @Bean method signature ) -> call @Bean method implementations

We can divide the life cycle of a bean as below

Callback Interfaces
  • InitializingBean.afterPropertiesSet() called after properties are set
  • DisposableBean.destroy() called during bean destruction in shutdown
Life Cycle Annotations
  • @PostConstruct annotated methods will be called after the bean has been constructed, but before its returned to the requesting object   
  • @PreDestroy is called just before the bean is destroyed by the container
Bean Post Processors
  • Gives you a means to tap into the Spring context life cycle and interact with beans as they are processed
  • postProcessBeforeInitialization - Called before bean initialization method
  • postProcessAfterInitialization - Called after bean initialization
‘Aware’ Interfaces
  • Spring has over 14 ‘Aware’ interfaces.
  • These are used to access the Spring Framework infrastructure
  • These are largely used within the framework
  • Rarely used by Spring developers


Note: BeanFactoryPostProcessor implementations are "called" during startup of the Spring context after all bean definitions will have been loaded while BeanPostProcessor are "called" when the Spring IoC container instantiates a bean.

BeanFactoryPostProcessor kicks in at the phase of the container life-cycle, when no bean has been created but the bean definition has already been parsed, while BeanPostProcessor comes into play after bean creation.

Thursday, 9 July 2020

Spring mvc life cycle summary



  • First request lands to the different sort of filters and it applies to all request. eg, application provided filters, authentication filters etc
  • The DispatcherServlet consults with the HandlerMapping 
  • Handler Mapping resolves controller to invoke. Usually org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping is used. This class reads @RequestMapping annotation from the Controller and uses the method of Controller that matches with URL as Handler class.
  • Handler Adapter calls the appropriate controller. org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter is used. RequestMappingHandlerAdapter class calls the method of handler class (Controller) selected by HandlerMapping.
  • HandlerInterceptor to perform actions before handling, after handling or after completion (when the view is rendered) of a request.
  • Controller executes the business logic
  • Controller resolves the model and view to send to the user
  • The DispatcherServlet sends the view name to a ViewResolver to find the actual View to invoke. ViewResolvers resolves the view according to the implementation and configuration of the view, normally JSP org.springframework.web.servlet.view.InternalResourceViewResolver is used, Some other view resolvers are FreeMarkerViewResolver, TilesViewResolver, ThymeleafViewResolver, BeanNameViewResolver etc
  • Now the DispatcherServlet will pass the model object to the View to render the result.


Thursday, 30 April 2020

SOLID Principle

SOLID Principle

  • The principles are from Robert "Uncle Bob" Martin
  • Michael Feathers is credited with coming up with the SOLID acronym
    • S = Single Responsibility Principle
    • O = Open/Closed Principle
    • L = Liskov Substitution principle
    • I = Interface Segregation Principle
    • D = Dependency Inversion Principle

Why?


  • OOP does not always lead to quality software
  • Poor dependency management leads to code that is brittle, fragile, and hard to change
  • Proper dependency management leads to quality code that is easy to maintain.
  • The 5 principles focus on dependency management
The one thing you can always count on in software engineering is CHANGE, no matter how well you design an application over time an application must grow and change or it will die.

Single Responsibility Principle

  • Every Class should have a single responsibility.
  • There should never be more than one reason for a class to change.
  • Your classes should be small. No more than a screen full of code.
  • Avoid ‘god’ classes.
  • Split big classes into smaller classes.
You can avoid these problems by asking a simple question before you make any changes: What is the responsibility of your class/component?

If your answer includes the word “and”, you’re most likely breaking the single responsibility principle. Then it’s better to take a step back and rethink your current approach.

Example: please follow the github link with bad and good example. explanation is class comment.


Real world example:
  • Java Persistence API (JPA) specification. defines a standardized way to manage data persisted in a relational database by using the object-relational mapping concept.
  • Spring Data Repository
  • Logging

Open/Closed Principle

  • Your classes should be open for extension but closed for modification
  • You should be able to extend a classes behavior, without modifying it.
  • Use private variables with getters and setters - ONLY when you need them.
  • Use abstract/interface base classes
  • Design should be ploymorphic to allow different implementations which you can easily substitute without changing the code that uses them
Example: please follow the github link with bad and good example. explanation is class comment.


Liskov Substitution Principle

  • By Barbara Liskov, in 1998
  • Objects in a program would be replaceable with instances of their subtypes WITHOUT altering the correctness of the program.
  • Violations will often fail the “Is a” test.
  • A Square “Is a” Rectangle
  • However, a Rectangle “Is Not” a Square
  • Can most usually be recognized by a method that does nothing, or even can’t be implemented.
  • The solution to these problems is a correct inheritance hierarchy/ correct interface
  • If it looks like a Duck, Quacks like a Duck but needs batteries. You probably Have the wrong abstraction.
Example: please follow the github link with bad and good example. explanation is class comment.


Interface Segregation Principle

  • No matter what should never be forced to implement an interface that it does not use or the client should never be obliged to depend on any method, which is not used by them.
  • Make fine grained interfaces that are client specific
  • Many client specific interfaces are better than one “general purpose” interface
  • Keep your components focused and minimize dependencies between them
  • Changing one method in a class should not affect classes that don't depend on
  • Notice relationship to the Single Responsibility Principle?
  • ie avoid ‘god’ interfaces
Example: please follow the github link with bad and good example. explanation is class comment.

Dependency Inversion Principle

  • Abstractions should not depend upon details
  • Details should depend upon abstractions
  • Important that higher level and lower level objects depend on the same abstract interaction
  • Able to change an implementation easily without altering the high level code.
  • This is not the same as Dependency Injection - which is how objects obtain dependent objects
Example: please follow the github link with bad and good example. explanation is class comment.

Some of other design principles
  • Encapsulate what varies ( identify the aspect of your application that vary and separate them from what stays the same)
  • Program to an interface not an implementation
  • Favor composition over inheritance ( HAS- A can better than IS - A)
  • Composition gives you a lot more flexibility. Not only does it let you encapsulate a family of algorithms into their own set of classes, but it also lets you change behavior at runtime as long as the object you are composing with implements correct behavior interface.