Showing posts with label SpringBootApplication. Show all posts
Showing posts with label SpringBootApplication. Show all posts

July 21, 2022

org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException

Problem

org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException

This issue happens due to version mismatch between swaggerfox and spring boot framework.


Solution




/**
 * @author aswathi sajeevan
 *
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {

@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any()).build();
}
}


Pom.xml



<!--  swagger  -->

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>


Spring boot version



<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.2-SNAPSHOT</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>



Swagger url


http://localhost:9090/swagger-ui/index.html




June 27, 2022

Sources must not be empty | java.lang.IllegalArgumentException | Spring boot application

Issue reported


2022-06-27 16:13:04.789  INFO 6348 --- [           main] o.s.boot.SpringApplication               : Starting SpringApplication v2.6.0 using Java 11.0.7 on apple-pc with PID 6348 (E:\Aswathi\maven_repo\org\springframework\boot\spring-boot\2.6.0\spring-boot-2.6.0.jar started by aswathi in E:\Aswathi\repo\stockmaster\nyseticker)
2022-06-27 16:13:04.793  INFO 6348 --- [           main] o.s.boot.SpringApplication               : No active profile set, falling back to default profiles: default
2022-06-27 16:13:04.828 ERROR 6348 --- [           main] o.s.boot.SpringApplication               : Application run failed

java.lang.IllegalArgumentException: Sources must not be empty
at org.springframework.util.Assert.notEmpty(Assert.java:470) ~[spring-core-5.3.13.jar:5.3.13]
at org.springframework.boot.SpringApplication.prepareContext(SpringApplication.java:403) ~[spring-boot-2.6.0.jar:2.6.0]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:301) ~[spring-boot-2.6.0.jar:2.6.0]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1301) ~[spring-boot-2.6.0.jar:2.6.0]
at org.springframework.boot.SpringApplication.main(SpringApplication.java:1317) ~[spring-boot-2.6.0.jar:2.6.0]

Solution

Go to class where you have your @SpringBootApplication and right click -> run as java application.



  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.6.0)

2022-06-27 16:19:32.454  INFO 3160 --- [           main] c.p.nyseticker.NysetickerApplication     : Starting NysetickerApplication using Java 11.0.7 on apple-pc with PID 3160 (E:\Aswathi\repo\stockmaster\nyseticker\target\classes started by apple in E:\Aswathi\repo\stockmaster\nyseticker)
2022-06-27 16:19:32.460  INFO 3160 --- [           main] c.p.nyseticker.NysetickerApplication     : No active profile set, falling back to default profiles: default
2022-06-27 16:19:34.141  INFO 3160 --- [           main] c.p.nyseticker.NysetickerApplication     : Started NysetickerApplication in 2.955 seconds (JVM running for 4.258)



October 14, 2020

Creating a custom validation for bean validation in spring boot

Creating a custom validation for bean validation in spring boot


Why we create a custom bean validation?

To test whether the input are valid one before the inputs reach our application.


How to create a custom annotation java code?

/**
 * Custom annotation
 */
package com.javabelazy.validators;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

/**
 * @author Java code
 *
 */

@Target({ ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = { OrderStatusValidator.class })
public @interface Status {

String message() default "Invalid order status";

Class<?>[] groups() default {};

Class<? extends Payload>[] payload() default {};

}


@Target  denotes the context where the annotation type is applicable, here we mentioned on a method or a field.
@Retention  denotes the annotation is available at the run time.
@Constraint denotes the class where the validation  logic is implemented


How to create a custom validator?

/**
 *  Custom annotation validator class
 */
package com.javabelazy.validators;

import java.util.stream.Stream;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;



/**
 * @author Java source code
 *
 */
public class OrderStatusValidator implements ConstraintValidator<Status, String> {

@Override
public void initialize(Status constraintAnnotation) {
}

@Override
public boolean isValid(String orderStatus, ConstraintValidatorContext context) {
System.out.println(" ****** "+orderStatus);

if (orderStatus.isBlank()) {
return true;
}

boolean isValid = Stream.of(OrderStatus.values()).anyMatch(v -> v.name().equals(orderStatus));

return isValid;
}

}

How to use this annotation?


@Status
private String orderStatus;


Thanks





July 21, 2020

Debugging Auto Configuration in spring boot application


Debugging Auto Configuration


There are two approaches you can debug and discover more information about auto 
configuration.

1. Using Spring Boot Actuator

2. Turning on debug logging

You can switch on debug logging by including a simple property value to 
application.properties.

In this example, we are switching on Debug level for all logging from org.springframework 

package (and sub packages).

logging.level.org.springframework: DEBUG

When the application is restarted, you will view an auto configuration report printed in the log.

January 17, 2019

Spring Boot Application for Rest API - micro service api example

Consumerfed application - An Expense Rest API

Diagram



A sample spring boot application

Main class

package com.etrade.expenses;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.etrade.expenses.services.ExpensesService;
/**
 *
 * @author Consumerfed IT Section Kozhikode
 * consfedkozhikode@gmail.com
 */
@SpringBootApplication
@RestController
public class EtradeExpensesApplication {

@Autowired
ExpensesService expenseService;

public static void main(String[] args) {
SpringApplication.run(EtradeExpensesApplication.class, args);
}

@RequestMapping(value= "/getAllExpenseHead", method=RequestMethod.GET, headers="Accept=application/json")
public List getExpensesDetails() {
return expenseService.getExpensesHead() ;
}

}


SpringBootServletInitializer class


package com.etrade.expenses;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
/**
 *
 * @author Consumerfed I T Section kozhikode
 *
 * Since we are developing a web application
 * we need to extends SpringBootServletInitializer
 *
 * we can also do the following
 *
 * EtradeExpensesApplication extends SpringBootServletInitializer
 *
 * For our convenience we did like this
 *
 */
public class ServletInitializer extends SpringBootServletInitializer {

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(EtradeExpensesApplication.class);
}

}

Service class


/**
 *  Expense service class is an implementation of ExpenseService Interface
 */
package com.etrade.expenses.servicesImpl;

import java.util.List;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.etrade.expenses.dao.ExpensesDao;
import com.etrade.expenses.services.ExpensesService;

/**
 * @author Consumerfed IT Section kozhikode
 *
 */
@Service("expensesService")
public class ExpensesServiceImpl implements ExpensesService {

@Autowired
ExpensesDao expenseDao;


@Override
@Transactional
public List getExpensesHead() {
return expenseDao.getExpensesHead();
}
}

Data Access Object class

/**
 *Phone : +918281808029
 */
package com.etrade.expenses.daoImpl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.etrade.expenses.dao.ExpensesDao;
/**
 * Expense Data Access Object class is an implementation of DAO interface
 */
import com.etrade.expenses.entities.ExpenseHead;

/**
 * @author Consumerfed I T Section kozhikode
 *
 */
@Repository
public class ExpensesDaoImpl implements ExpensesDao {

@Autowired
private SessionFactory sessionFactory;

public void setSessionFactory(SessionFactory sf) {
this.sessionFactory = sf;
}

@Override
public List getExpensesHead() {
Session session = sessionFactory.getCurrentSession();
Criteria criteria = session.createCriteria(ExpenseHead.class);
List<ExpenseHead> expenseList = criteria.list();
return expenseList;
}

}

Entity class


package com.etrade.expenses.entities;

import java.io.Serializable;
import javax.persistence.*;
import javax.xml.bind.annotation.XmlRootElement;

import com.fasterxml.jackson.annotation.JsonProperty;

//import org.springframework.boot.autoconfigure.domain.EntityScan;


/**
 * The persistent class for the tbl_expense_head database table.
 * Phone : +918281808029
 */
@Entity
@Table(name="expense_head")
@XmlRootElement(name="expense")
//@NamedQuery(name="TblExpenseHead.findAll", query="SELECT t FROM TblExpenseHead t")
public class ExpenseHead implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@Column(name="expense_head_id_pk")
@GeneratedValue(strategy=GenerationType.AUTO)
@JsonProperty("id")
private int expenseHeadIdPk;

@JsonProperty("description")
@Column(name="expense_head_description")
private String expenseHeadDescription;

@JsonProperty("name")
@Column(name="expense_head_name")
private String expenseHeadName;

@JsonProperty("status")
@Column(name="expense_head_status")
private String expenseHeadStatus;

public ExpenseHead() {
}

public int getExpenseHeadIdPk() {
return this.expenseHeadIdPk;
}

public void setExpenseHeadIdPk(int expenseHeadIdPk) {
this.expenseHeadIdPk = expenseHeadIdPk;
}

public String getExpenseHeadDescription() {
return this.expenseHeadDescription;
}

public void setExpenseHeadDescription(String expenseHeadDescription) {
this.expenseHeadDescription = expenseHeadDescription;
}

public String getExpenseHeadName() {
return this.expenseHeadName;
}

public void setExpenseHeadName(String expenseHeadName) {
this.expenseHeadName = expenseHeadName;
}

public String getExpenseHeadStatus() {
return this.expenseHeadStatus;
}

public void setExpenseHeadStatus(String expenseHeadStatus) {
this.expenseHeadStatus = expenseHeadStatus;
}

}

Hibernate configuration class


/**
 *  Hibernate Configuration class
 *
 *  datasource, sessionfactory, transaction manager
 */
package com.etrade.expenses;

import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
//import org.springframework.orm.hibernate4.HibernateTransactionManager;
//import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * @author Consumerfed I T section kozhikode

 * Phone : 8281808029
 */
@Configuration
@EnableTransactionManagement
public class HibernateConfiguration {

@Value("${db.driver}")
private String DRIVER;

@Value("${db.username}")
private String USERNAME;

@Value("${db.password}")
private String PASSWORD;

@Value("${db.url}")
private String URL;

@Value("${hibernate.dialect}")
private String DIALECT;

@Value("${hibernate.show_sql}")
private String SHOW_SQL;

@Value("${hibernate.hbm2ddl.auto}")
private String HBM2DDL_AUTO;

@Value("${entitymanager.packagesToScan}")
private String PACKAGE_TO_SCAN;

@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(DRIVER);
dataSource.setUrl(URL);
dataSource.setPassword(PASSWORD);
dataSource.setUsername(USERNAME);
return dataSource;
}

@Bean
public LocalSessionFactoryBean sessionFactory() {

LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(PACKAGE_TO_SCAN);

Properties properties = new Properties();
properties.put("hibernate.dialect", DIALECT);
properties.put("hibernate.show_sql", SHOW_SQL);
properties.put("hibernate.hbm2ddl.auto", HBM2DDL_AUTO);
sessionFactory.setHibernateProperties(properties);

return sessionFactory;
}

@Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}

}

application property file


# Database
db.driver: com.mysql.jdbc.Driver
db.url: jdbc:mysql://localhost:3306/consumerfedBithesh
db.username: bithesh
db.password: bithesh@gmail.com

# Hibernate
hibernate.dialect: org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql: true
hibernate.hbm2ddl.auto: create
entitymanager.packagesToScan: com

spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true

Output


[{"id":1,"description":"The expense for taking photostats and xerox","name":"PHOTOCOPIER","status":"A"},{"id":2,"description":"Expenses like auto, taxi, bus fares below 100 rupees","name":"LOCAL CONVEYANCE","status":"A"},{"id":3,"description":"Amount paid for packing goods in units","name":"PACKING CHARGES","status":"A"},{"id":4,"description":"Expenses for tea","name":"TEA EXPENSES","status":"I"}]

Notes

@RequestMapping(value= "/createExpense", method=RequestMethod.POST, headers="Accept=application/json")

can be replaced by

@PostMapping(value= "/createExpense",headers="Accept=application/json")

Description

Working as an assistant of kozhikode regional office Information Manager, we developed this project. This project is working on producer consumer model. We don't follow any specific methodology ,uml diagrams and all as our organization is not a software development company, we have a efficient team who develop software for the organization. This project was developed for kozhikode Regional office , Regional Manager who is a good support for all Information Technology related works.

This Rest API what it does is, will give the consumer , who ever it is the details of all expense head, as the data is in the format of json, it can be consumed even by mobile application very fast. The application is a stand alone application. We build the whole application as a combination of many standalone which has their own functionality. We are not sure is it a good practice or not, as there is not top layer above us to clear our doubts.

The project was developed in the year 2015

Reader can contact us at any time if they any queries

Hire us!!! Or for projects contact us !!! 

Facebook comments