Showing posts with label spring boot. Show all posts
Showing posts with label spring boot. Show all posts

October 07, 2022

[Solution for ] No main manifest attribute, in jar Maven and SpringBoot | SpringBoot no main manifest attribute (maven)

SpringBoot no main manifest attribute (maven)






Add the plugin to the pom.xml:



<plugin>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-maven-plugin</artifactId>
   <configuration>                   
      <mainClass>com.bijusapp.stockmarket.TickerApplication</mainClass>
   </configuration>
   <executions>
      <execution>
      <goals>
         <goal>repackage</goal>
      </goals>
      </execution>
   </executions>
</plugin>





Tags : No main manifest attribute, in jar Maven and SpringBoot, Unable to execute jar- file no main manifest attribute,[Fixed] no main manifest attribute, Maven "No main manifest attribute", How to fix "no main manifest attribute" error , Importance of Main Manifest Attribute in a Self-Executing JAR,It is easy to resolve this error in the Spring Boot project

September 07, 2022

nested exception is org.springframework.core.io.buffer.DataBufferLimitException | Exceeded limit on max bytes to buffer : 262144 | org.springframework.web.reactive.function.client.WebClientResponseException

Hi, While trying to implement a NSE Ticker for stockmarket analysis we encountered the below error

reactor.core.Exceptions$ErrorCallbackNotImplemented: org.springframework.web.reactive.function.client.WebClientResponseException: 200 OK from GET https://www.bijusapp/query?f=DAILY&symbol=adhani&apikey=bijusapp; nested exception is org.springframework.core.io.buffer.DataBufferLimitException: Exceeded limit on max bytes to buffer : 262144
Caused by: org.springframework.web.reactive.function.client.WebClientResponseException: 200 OK from GET https://www.bijusapp/query?f=DAILY&symbol=adhani&apikey=bijusapp; nested exception is org.springframework.core.io.buffer.DataBufferLimitException: Exceeded limit on max bytes to buffer : 262144


Solution


spring.codec.max-in-memory-size=50MB in application properties


Or


/**
 * 
 */


import org.springframework.context.annotation.Configuration;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.config.EnableWebFlux;
import org.springframework.web.reactive.config.WebFluxConfigurer;

/**
 * @author bijusapp
 *
 */
@Configuration
@EnableWebFlux
public class WebFluxConfig implements WebFluxConfigurer {
@Override
public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) {
configurer.defaultCodecs().maxInMemorySize(16 * 1024 * 1024);
}

}

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




December 07, 2021

An application help to know buy or sell stock in stockmaster

Hi Team


We are planning to develop an application where any user who doesnt know about stock master can buy or sell stocks

The application is developed in java spring boot

Git url


Thanks @sanoop kakkoor for his #support

September 21, 2021

Firebase | Firestore | Firestore junit test | deep stubbing mockito

This is a sample code how to perform deep stubbing mockito on firestore
you need to mock all the 


public class FirestoreClientTest{

@Mock
Firestore firestore;

@Mock
DocumentReference documentReference;

@Mock
CollectionReference collectionReference;

@Mock
ApiFuture apiFuture;

@Mock
QuerySnapshot querySnapshot;

@Test
public void test(){
when(firestore.collection(any(String.class)).thenReturn(collectionReference);
when(collectionReference.document(any(String.class)).thenReturn(documentReference);
when(documentReference.get()).thenReturn(apiFuture);
when(apiFuture.get()).thenReturn(querySnapshot);

UserInfo userInfo = firestore.getUserDetails();

//Assert statements
}

}

September 14, 2021

Google Firebase Firestore Spring boot Integration sample code

1. Create a new Cloud Firestore database in your GCP project

2. If you are authenticated in the Cloud SDK, your credentials will be automatically found by the Spring Boot Starter for Google Cloud Firestore.

3. Pom dependency

<!-- https://mvnrepository.com/artifact/com.google.cloud/spring-cloud-gcp-starter -->
<dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>spring-cloud-gcp-starter</artifactId>
    <version>2.0.4</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.google.cloud/google-cloud-firestore -->
<dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-firestore</artifactId>
    <version>3.0.1</version>
</dependency>



4. Repository (writing data)

@Autowired
Firestore firestore;

User data = new User("javabelazy",
Arrays.asList(
new Phone(12345, PhoneType.CELL),
new Phone(54321, PhoneType.WORK)));

WriteResult writeResult = this.firestore.document("users/id").set(data).get();

5. Application.properties

spring.cloud.gcp.firestore.project-id =abcdefg

6. Git URL

July 07, 2021

Spring boot Grpc google remote procedure call full source code

Hi Team

if you are searching for a GRPC server spring boot project, here is the link. the running code




GRPC is google Remote Procedure Call introduced in the year 2016.
The application runs in port 9090.


June 07, 2021

IllegalArgumentException no serializer found for class org.mockito and no properties discovered to create beanserializer [Solved]

Solution : (Mockito.anyObject(), Mockito.any(TypeReference.class))


Hi 

Recently I went through a scenario and got the below error while using object Mapper

java.lang.illegalargumentexception :no serializer found for class org.mockito.internal.invocation.mock ref.mock weakreference and no properties discovered to create beanserializer (to avoid exception disable serializationfeature.fail_on_empty_beans [ Solved ]

Here is the scenario


public class A{

@Autowired
private ObjectMapper obj;

private boolean isWar(Test abc){

  obj.convertValue(object, new TypeReference<Map<String,Object>>(){});
}

}


and my junit class is here



@Test
public void testSomething(){
when (objectMapper.convertValue(obj,map.class)).thenReturn(something);
}


Changing the convertValue parameter as (Mockito.anyObject(), Mockito.any(TypeReference.class)) solved the problem

December 28, 2020

Could not determine type for: com.google.model.user.adminuser, at table: amazon, for columns: [org.hibernate.mapping.Column(business_seller)]

Could not determine type for: com.fp.ordermanagementservice.model.user.FP_Business_User, at table: fp_order, for columns: [org.hibernate.mapping.Column(business_seller)]


solution

You need to provide mapping annotations like @onetoone

December 21, 2020

No validator could be found for constraint 'javax.validation.constraints.NotBlank' validating type 'java.lang.Long'. Check configuration for 'WorldEnd'



 No validator could be found for constraint 'javax.validation.constraints.NotBlank' validating type 'java.lang.Long'. Check configuration for 'Bean validation in spirng boot'


Solutions

As clearly mentioned in the  problem, to solve this error you MUST use correct annotations.

In above case, 

@NotBlank or @NotEmpty annotation are used in String datatype.

you need to use @NotNull for Long datatypes.


November 21, 2020

org.springframework.security.authentication.InternalAuthenticationServiceException | UserDetailsService returned null

org.springframework.security.authentication.InternalAuthenticationServiceE

xception: UserDetailsService returned null, which is an interface contract 

violation\r\n\tat 

org.springframework.security.authentication.dao.DaoAuthenticationProvider

.retrieveUser(DaoAuthenticationProvider.java:110)\r\n\tat 

org.springframework.security.authentication.dao.AbstractUserDetailsAuthen

ticationProvider.authenticate

(AbstractUserDetailsAuthenticationProvider.java:144)\r\n\tat 

org.springframework.security.authentication.ProviderManager.authenticate

(ProviderManager.java:175)\r\n\tat 

org.springframework.security.authentication.ProviderManager.authenticate

(ProviderManager.java:195)


Solution

if your service class is implementing org.springframework.security.core.userdetails.UserDetailsService
you should implement loadUserByUsername()
and returns a new User(username,pass,rolesList)



public class yourServiceClass implements UserDetailsService {

//unimplemented method
loadUserByUsername(){
return new User(x,y,z);
}}

November 14, 2020

Auto Configuration in spring boot

Auto Configuration...


All auto configuration logic is executed in spring-boot-autoconfigure.jar. All auto configuration logic for MVC, JMS, data, and other frameworks is available in a JAR.

Auto-configuration @Conditional

If specific classes are offered in the classpath, then the configuration for that feature is enabled via auto configuration. Annotations such as @ConditionalOnMissingBean, @ConditionalOnClass, help in providing these functions.

Example 1
@Configuration
@ConditionalOnClass({ DataSource.class, EmbeddedDatabaseType.class })
@EnableConfigurationProperties(DataSourceProperties.class)
@Import({ Registrar.class, DataSourcePoolMetadataProvidersConfiguration.class })
public class DataSourceAutoConfiguration {
@ConditionalOnClass({ DataSource.class, EmbeddedDatabaseType.class })

This configuration is enabled only when the classes are present in the classpath.

November 07, 2020

The injection point has the following annotations: - @org.springframework.beans.factory.annotation.Autowired(required=true)

Errors and solution
=============

Description:

Field customAuthProvider in com.proximotech.zhw.WebServiceAuthProviderSecurityConfig required a bean of type 'com.proximotech.zhw.WebServiceAuthenticationProvider' that could not be found.

The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'com.proximotech.zhw.WebServiceAuthenticationProvider' in your configuration.

Solution:
Annotation @component missing in the class
com.proximotech.zhw.WebServiceAuthenticationProvider

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





August 28, 2020

Swagger- api in spring boot


@ApiModel(value = "UserDTO", description = "User Data Transfer Object description")
public class UserDTO {



@ApiModelProperty(value="user ID",position = 0 , hidden = true)
private String userId; 

August 07, 2020

Spring boot failed Field customAuthProvider in SecurityConfig required a bean of type 'AuthProvider' that could not be found.

Description:

Field customAuthProvider in com.proximotech.zhw.WebServiceAuthProviderSecurityConfig required a bean of type 

'com.proximotech.zhw.WebServiceAuthenticationProvider' that could not be found.

The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'com.proximotech.zhw.WebServiceAuthenticationProvider' in your configuration.

Solution:
Annotation @component missing in the class
com.proximotech.zhw.WebServiceAuthenticationProvider

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.

July 07, 2020

Maven : Changing the Version of Java in pom.xml file

Changing the Version of Java


If you wish to change the Java version, you can include a java.version property to pom.xml.

<properties>
    <java.version>1.8</java.version>
</properties>



Facebook comments