Showing posts with label Exception. Show all posts
Showing posts with label Exception. Show all posts

Monday, April 25, 2022

Http failure response for http://localhost:8080/alluser: 0 Unknown Error","error":{"isTrusted":true}

For a mini project I used spring boot as API and angular as UI.  In Spring boot I have added spring-boot-starter-security for secured my application. And I added my implementation for add/update/view data. After that I started working with Angular front end with mock data. 

Then I started integration part of UI with API. The first call I made from UI to API to fetch the uses available in DB and display them in list. While calling from UI, backend did not allow the UI request, because we have security check in API. In API I added security username and password. 

spring.security.user.name=user
spring.security.user.password=user

So we need to added security config to resolve this issue. I will post the solution
in next post.


Here is full error stack trace:
 main.js:1 ERROR Error: Uncaught (in promise): s1: {"headers":{"normalizedNames":{},"lazyUpdate":null,"headers":{}},"status":0,"statusText":"Unknown Error","url":"http://localhost:8080/alluser","ok":false,"name":"HttpErrorResponse","message":"Http failure response for http://localhost:8080/alluser: 0 Unknown Error","error":{"isTrusted":true}}
    at _e (polyfills.js:1:160289)
    at _e (polyfills.js:1:159769)
    at polyfills.js:1:161152
    at X.invokeTask (polyfills.js:1:154522)
    at Object.onInvokeTask (main.js:1:255253)
    at X.invokeTask (polyfills.js:1:154442)
    at X.runTask (polyfills.js:1:149526)
    at te (polyfills.js:1:156890)
    at X.invokeTask [as invoke] (polyfills.js:1:155703)
    at ee (polyfills.js:1:169257)

Thank you.

the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is application/json

Hi,

Today I created mini project using spring boot and angular to maintain user data. While adding the user from angular I got below error. 

org.apache.tomcat.util.http.fileupload.impl.InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is application/json
at org.apache.tomcat.util.http.fileupload.impl.FileItemIteratorImpl.init(FileItemIteratorImpl.java:151) ~[tomcat-embed-core-9.0.60.jar:9.0.60]
at 

And code is like this.

@RequestMapping(value="adduser", method = RequestMethod.POST)
@ResponseBody
public User createNewUser(@RequestPart User user){
user.setCreatedDate(LocalDateTime.now());
return userService.createNewUser(user);
}

<form [formGroup]="userForm"  (ngSubmit)="onUserDetail()">
<div class="container">
Username: <input class="input_filed" type="text" name="username" formControlName="username">
Email: <input class="input_filed" type="text" name="email" formControlName="email">
Title: <input class="input_filed" type="text" name="title" formControlName="title">
<button >Add</button>
</div>
</form>
So clearly it says the format of input param of createNewUse() method was not expected.
I tried to add the @RequestPart("user") also I end up with same error.

Then I used @RequestBody instead of @RequestPart. This works for me I am able to send the
user data from UI to backend.

Working code:


@RequestMapping(value="adduser", method = RequestMethod.POST)
@ResponseBody
public User createNewUser(@RequestBody User user){
user.setCreatedDate(LocalDateTime.now());
return userService.createNewUser(user);
}

Thanks all. Full error stack trace is below.


org.apache.tomcat.util.http.fileupload.impl.InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is application/json
at org.apache.tomcat.util.http.fileupload.impl.FileItemIteratorImpl.init(FileItemIteratorImpl.java:151) ~[tomcat-embed-core-9.0.60.jar:9.0.60]
at 
 org.apache.tomcat.util.http.fileupload.impl.InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is application/json
at org.apache.tomcat.util.http.fileupload.impl.FileItemIteratorImpl.init(FileItemIteratorImpl.java:151) ~[tomcat-embed-core-9.0.60.jar:9.0.60]
at org.apache.tomcat.util.http.fileupload.impl.FileItemIteratorImpl.getMultiPartStream(FileItemIteratorImpl.java:205) ~[tomcat-embed-core-9.0.60.jar:9.0.60]
at org.apache.tomcat.util.http.fileupload.impl.FileItemIteratorImpl.findNextItem(FileItemIteratorImpl.java:224) ~[tomcat-embed-core-9.0.60.jar:9.0.60]
at org.apache.tomcat.util.http.fileupload.impl.FileItemIteratorImpl.<init>(FileItemIteratorImpl.java:142) ~[tomcat-embed-core-9.0.60.jar:9.0.60]
at org.apache.tomcat.util.http.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:252) ~[tomcat-embed-core-9.0.60.jar:9.0.60]
at org.apache.tomcat.util.http.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:276) ~[tomcat-embed-core-9.0.60.jar:9.0.60]
at org.apache.catalina.connector.Request.parseParts(Request.java:2932) ~[tomcat-embed-core-9.0.60.jar:9.0.60]
at org.apache.catalina.connector.Request.getParts(Request.java:2834) ~[tomcat-embed-core-9.0.60.jar:9.0.60]
at org.apache.catalina.connector.RequestFacade.getParts(RequestFacade.java:1098) ~[tomcat-embed-core-9.0.60.jar:9.0.60]
at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.parseRequest(StandardMultipartHttpServletRequest.java:95) ~[spring-web-5.3.18.jar:5.3.18]
at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.<init>(StandardMultipartHttpServletRequest.java:88) ~[spring-web-5.3.18.jar:5.3.18]
at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.<init>(StandardMultipartHttpServletRequest.java:72) ~[spring-web-5.3.18.jar:5.3.18]
at org.springframework.web.multipart.support.MultipartResolutionDelegate.asMultipartHttpServletRequest(MultipartResolutionDelegate.java:82) ~[spring-web-5.3.18.jar:5.3.18]
at org.springframework.web.multipart.support.RequestPartServletServerHttpRequest.<init>(RequestPartServletServerHttpRequest.java:68) ~[spring-web-5.3.18.jar:5.3.18]
at org.springframework.web.servlet.mvc.method.annotation.RequestPartMethodArgumentResolver.resolveArgument(RequestPartMethodArgumentResolver.java:139) ~[spring-webmvc-5.3.18.jar:5.3.18]
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:122) ~[spring-web-5.3.18.jar:5.3.18]
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:179) ~[spring-web-5.3.18.jar:5.3.18]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:146) ~[spring-web-5.3.18.jar:5.3.18]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117) ~[spring-webmvc-5.3.18.jar:5.3.18]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895) ~[spring-webmvc-5.3.18.jar:5.3.18]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) ~[spring-webmvc-5.3.18.jar:5.3.18]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.3.18.jar:5.3.18]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067) ~[spring-webmvc-5.3.18.jar:5.3.18]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963) ~[spring-webmvc-5.3.18.jar:5.3.18]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.18.jar:5.3.18]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) ~[spring-webmvc-5.3.18.jar:5.3.18]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:681) ~[tomcat-embed-core-9.0.60.jar:4.0.FR]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.18.jar:5.3.18]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:764) ~[tomcat-embed-core-9.0.60.jar:4.0.FR]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) ~[tomcat-embed-core-9.0.60.jar:9.0.60]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.60.jar:9.0.60]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.60.jar:9.0.60]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.60.jar:9.0.60]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.60.jar:9.0.60]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.18.jar:5.3.18]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.18.jar:5.3.18]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.60.jar:9.0.60]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.60.jar:9.0.60]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.18.jar:5.3.18]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.18.jar:5.3.18]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.60.jar:9.0.60]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.60.jar:9.0.60]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.18.jar:5.3.18]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.18.jar:5.3.18]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.60.jar:9.0.60]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.60.jar:9.0.60]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197) ~[tomcat-embed-core-9.0.60.jar:9.0.60]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) [tomcat-embed-core-9.0.60.jar:9.0.60]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) [tomcat-embed-core-9.0.60.jar:9.0.60]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135) [tomcat-embed-core-9.0.60.jar:9.0.60]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.60.jar:9.0.60]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) [tomcat-embed-core-9.0.60.jar:9.0.60]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360) [tomcat-embed-core-9.0.60.jar:9.0.60]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399) [tomcat-embed-core-9.0.60.jar:9.0.60]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.60.jar:9.0.60]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:889) [tomcat-embed-core-9.0.60.jar:9.0.60]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1743) [tomcat-embed-core-9.0.60.jar:9.0.60]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.60.jar:9.0.60]
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) [tomcat-embed-core-9.0.60.jar:9.0.60]
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) [tomcat-embed-core-9.0.60.jar:9.0.60]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.60.jar:9.0.60]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_231]


Tuesday, April 19, 2022

java.lang.IllegalArgumentException: Not a managed type: class com.example.demo.entity.Customer

I tried to add couple of new entity classes in my project, service implementation and repository for those entity. Once after all done I tried to run my application, my IDE show up to below exception to me.


"org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customerRepo' defined in com.example.demo.repo.CustomerRepo defined in @EnableJpaRepositories declared on DemoApplication: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.example.demo.entity.Customer"

Here my Repo and Customer class

public interface CustomerRepo extends JpaRepository<Customer, Integer> {
}
public class Customer {
private Integer id;
private String name;
private String mobile;
private String email;
}

Its clearly says Customer class is not able to manage by JpaRepository. So JPA not able to consider this Customer class as entity. Because I used Customer class in Repo class as JpaRepository. 

Here the mistake is I forget to change the POJO to Entity. I missed to annotate Customer class with @Entity.


@Entity
@Table(name= "customer", schema = "public")
public class Customer {

So we need to add @Entity annotation to tell jpa this is a entity class to resolve 
this error.

This solve the above exception.

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured

 I have faced "

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured" error while setting up my learning project using spring boot with postgres.


After spending an hour on searching to fix this issue I have found the solution for it.

Adding below in application.properties resolve this issue for me.

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

Tuesday, March 1, 2022

Null Pointer Exception in Java

Here we will discuss about what is nullpointerexception and how to fix it?

In java if a variable or object reference do not have any value to assign to them , then we will have possibility of having null pointer exception. More clearly if a reference variable or object is assigned to nothing. For example,

public class NullPointerException {
public static void main(String[] args) {
Employee employee = null;
employee.getName();
}
}

Lets run this program, we are getting exception says below.,

Exception in thread "main" java.lang.NullPointerException
at com.example.monitoring.exception.NullPointerException.main(NullPointerException.java:8)
Here we are trying to call getName() of employee object, but we did not create a object for it.  Which mean employee is referred to nothing . 

How to fix this issue, we need to create a new employee object using new Employee().After changing null to this we will not get exception. We are not assigned any value to employee name variable, even we don't get any exception, because we have not call any further from getName(). Let me modified something from above example,

public class NullPointerException {
public static void main(String[] args) {
Employee employee = new Employee();
employee.getName().length();
}
}

While running the main method we will get below exception
Exception in thread "main" java.lang.NullPointerException
at com.example.monitoring.exception.NullPointerException.main(NullPointerException.java:8).

How to fix this issue, before we fix it, let we check other possible ways of having null pointer exception.

public class NullPointerException {
public static void main(String[] args) {
List<Employee> employeeList = null;
for(Employee employee1 : employeeList){
System.out.println(employee1);
}
}
}
Here we will get nullpointerexception on for loop, because we are trying to iterate from nothing.

List<Employee> employeeList = null;
Employee employee = new Employee();
employeeList.add(employee);
for(Employee employee1 : employeeList){
if(employee1.getName().equals("Boomiraj")){
System.out.println("Hello Boomiraj");
}
}

We will get exception on if condition to check equals(), because we do not set name to the employee object, so employee1 will have null on name variable. 

public static void main(String[] args) {
Employee employee = new Employee();
getEmployeeNameLength(employee);
}

public static int getEmployeeNameLength(Employee employee){
return employee.getName().length();
}

Here we will get exception on return statement of getEmployeeNameLength , here the exception trace will be like this and more details on it, 


Exception in thread "main" java.lang.NullPointerException
at com.example.monitoring.exception.NullPointerException.getEmployeeNameLength(NullPointerException.java:15)
at com.example.monitoring.exception.NullPointerException.main(NullPointerException.java:11)

We have seen all the possible ways of having nullpointerexception. Let see how to fix them.

Never assign object reference to null, just initialize them new Employee();. We may have some scenarios to have dynamic object, there we cannot initialize object. we can handle them with condition check using null. let see above code we are trying to get length of the name from employee object. 

We need to check the getName is null or not before we call .length(). Before call getName() we need to check employee object itself null or not.

public static int getEmployeeNameLength(Employee employee){
if(employee != null &&
employee.getName() != null)
{
return employee.getName().length();
}
return 0;
}
Above code might be looks like ugly code, we don't have any other option to check it.

On employee name equals check we need to pass static value first then we need to check equality.

if("Boomiraj".equals(employee.getName())){
System.out.println("Hello Boomiraj");
}

For loop fix we need initialize the list object.
List<Employee> employeeList = new ArrayList<>();

Now we have fixed all the possible ways of null exception. 

But this could not be happen to primitive type. Because we cannot declare a primitive type as null, primitive types always have their default value. Lets try with example.

Boolean isNull = null;
if(isNull){
System.out.println("Its null!");
}
 Lets try with example. Here I used Boolean wrapper class. So we can assign null to it, but if we use primitive boolean we cannot assign null to it. 

boolean isNull = null; 
Here I am getting compilation error says, required type boolean, provider null.
If you have possible way to declare primitive type, use them to rid out of nullpointerexception.

Thank you!.

Friday, January 28, 2022

Error creating bean with name 'conversionServicePostProcessor' defined in class path resource

Today I changed my .m2 repository from external repo to internal repo. After downloading all the necessary jars, I did mvn clean install and both got success. Then i tried to start my inbuild tomcat server for my spring boot application, after few seconds I got this error on console and server shutdown.


Error creating bean with name 'conversionServicePostProcessor' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.beans.factory.config.BeanFactoryPostProcessor]: Factory method 'conversionServicePostProcessor' threw exception; nested


The same code working other for my team, so I just googled the error and find some suggestion,   

spring.main.allow-bean-definition-overriding=true

But this same already available in my application.properties.


spring.main.allow-bean-definition-overriding=true 
So I have no clue to solve this issue, I tried many suggestion nothing works for me. Then I remember one, what if I try to  
Reimport All Maven Projects in my IDE, I am using IntelliJ. If you are using Eclipse just refresh the dependencies.


After all the jar loading done, I retried to start the server. Finally it works for me.
If you have some problem initializing spring boot bean after successful mvn install, just try reimport your jars on your IDE.
Because sometime your IDE need manual call to get refresh the dependencies.