How to configure Daily Log File Rolling in Java using Log4j - DailyRollingFileAppender Example

Hello guys, today, I am going to share one small but the useful tip about logging in to your Java application. If your Java application is a weekly restart, I mean it starts on Sunday and not again on the weekday, then you really want to have separate log files for each day. This helps during troubleshooting and debugging. But If you are facing a problem where your log files are not rolling daily and becoming bigger and bigger after each passing day, making it challenging to search anything in case of any production issue, then it might be that you have not configured your Log4j properly to roll your logs daily.

How to solve Arithmetic overflow error converting IDENTITY to data type tinyint, smallint or int in Microsoft SQL Server database

Last year we had a production issue where one of our backup jobs was failing while inserting Orders aggregated from other systems into our SQL Server database. The reason was dreaded "Arithmetic overflow error converting IDENTITY to data type int" because the table was using IDENTITY feature of SQL Server to generate OrderId, and Identity has breached it a maximum value, which is around 2.1 billion, precisely 2,147,483,647. The error "Arithmetic overflow error converting IDENTITY to data type int" comes when the IDENTITY value is inserted into a column of data type int, but the value is out-of-range. For example, if the current value of Identity becomes more than 2,147,483,647, then you cannot store that into an int column because it's more than the maximum value of int in SQL Server.

How to Fix java.lang.OutOfMemoryError: Metaspace in Java? [Solution]

Hello guys, An OutOfMemoryError related to Metaspace indicates that your Java application has exhausted the memory allocated for the Metaspace area, which is used for class metadata and method information. This error typically occurs when an application dynamically generates and loads a large number of classes or when the Metaspace size is not properly configured to handle the application's requirements.  Java class metadata (the virtual machine's internal presentation of Java class) is allocated in native memory (referred to here as metaspace). If metaspace for class metadata is exhausted, a java.lang.OutOfMemoryError exception with a detail MetaSpace is thrown. 

How to Handle REST exception in Spring Boot Application? Example Tutorial

Hello everyone, in this article we are going to take a look at how to handle REST API exceptions in Spring Boot. It is crucial to handle errors correctly in APIs by displaying meaningful messages as it helps API clients to address problems easily. What happens if we don’t handle the errors manually? By default, the spring application throws a stack trace, which is difficult to understand. Stack traces are mainly for developers hence it is useless for API clients. That's why its very important to use proper HTTP code and error messages to convey errors and exception to client and also logging so that support team can better handle them. Ideally you should tell what went wrong and how to fix it? For example, if the error is due to duplicate data then clearly say, already existed, try with a new one. Similarly, if authentication fail then clearly say authentication failed instead of throwing some other exception. 

What is try with resource in Java? Example tutorial

In Java we normally use resources like file, network connection, socket connection, database connection etc ,dealing with resources is not a difficult task but what if after using the resources programmers forget to close the resources. As we know in Java everything is Object so if we forget to close or shut down the resource its responsibility of GC that will recollect it when its no longer used but we can reduce resource exhaustion by explicitly closing the resources as soon we done with our job with the resources. Some resources like database connection are very precious and would surely run out of resources if waited for finalization. Many database servers only accept a certain number of connections so if forget to close properly will create problem.

How to Fix SQLServerException: The index is out of range? JDBC Example

I was executing a stored procedure against SQL SERVER 2008 database from Java program using CallableStatement, but unfortunately, I was getting the following error "SQLServerException: The index 58 is out of range". Since I am passing a lot of parameters I thought that something is wrong with a number of parameters I was passing to the stored proc. My stored procedure had 58 INPUT parameters, as soon as I removed the 58th INPUT parameter the error goes away, which confirmed my belief that SQL Server supports a maximum of 57 INPUT parameters in stored procedure via JDBC

How to fix cannot determine embedded database driver class for database type NONE

Hello and welcome to the blog post. Today we are going to take a look at a frequently encountered problem in Spring Boot Application. If you are reading this, I'm going to assume that you saw the problem "Cannot determine embedded database driver class for database type NONE" while executing a Spring Boot application. We will understand, when this error appears. For this we will create a simple Spring Boot project as shown below. It demonstrates how I encountered the problem "Cannot determine embedded database driver class for database type NONE".  

Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean

Hello and welcome to the blog post. In this post, we are about to take a look at how to fix the ‘unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean’ in the spring boot application. Let’s understand how to fix this error. But before we dig deep into this issue. Let’s first have a look at when this error appears. 


Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean

The error appears with the following stack trace.

Exception in thread “main” org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.

at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:140)

at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:476)

at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:124)

at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:658)

at org.springframework.boot.SpringApplication.run(SpringApplication.java:355)

at org.springframework.boot.SpringApplication.run(SpringApplication.java:920)

at org.springframework.boot.SpringApplication.run(SpringApplication.java:909)

at Application.main(Application.java:17)

Caused by: org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.

at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getEmbeddedServletContainerFactory(EmbeddedWebApplicationContext.java:190)

at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:163)

at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:137)

… 7 more 


Now, let's see some code to understand when this error comes and how to fix it:


SpringBootPracticeApplication.java


package com.practice.springboot;



import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootConfiguration;



@SpringBootConfiguration

public class SpringBootPracticeApplication {



   public static void main(String[] args) {

      SpringApplication.run(SpringBootPracticeApplication.class, args);

   }



}



pom.xml


<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>

   <parent>

      <groupId>org.springframework.boot</groupId>

      <artifactId>spring-boot-starter-parent</artifactId>

      <version>3.0.4</version>

      <relativePath/> <!-- lookup parent from repository -->

   </parent>

   <groupId>com.practice</groupId>

   <artifactId>spring-boot</artifactId>

   <version>0.0.1-SNAPSHOT</version>

   <name>Spring Boot Practice</name>

   <description>Spring Boot Practice Project</description>

   <properties>

      <java.version>17</java.version>

   </properties>

   <dependencies>

      <dependency>

         <groupId>org.springframework.boot</groupId>

         <artifactId>spring-boot-starter-web</artifactId>

      </dependency>



	 <dependency>

       <groupId>org.springframework.boot</groupId>

         <artifactId>spring-boot-starter-test</artifactId>

         <scope>test</scope>

	</dependency>

   </dependencies>

</project>


As you can see from the above program, we have a very simple spring boot project that fails to run as intended. There are a couple of possible solutions to this program. These approaches are discussed below.


How to fix this error?

First of all you need to ensure that your main class has the @SpringBootApplication annotation.

The @SpringBootApplication annotation is comparable to the @EnableAutoConfiguration, @ComponentScan, and @Configuration annotations with their default properties, i.e., allow adding new beans to the context or importing more configuration classes.


SpringBootPracticeApplication.java -- updated

package com.practice.springboot;



import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;



@SpringBootApplication

public class SpringBootPracticeApplication {



   public static void main(String[] args) {

      SpringApplication.run(SpringBootPracticeApplication.class, args);

   }



}


If you have followed the above step or your starter file already contains @SpringBootApplication, you need to make sure your pom.xml file also includes the spring-boot-starter-web or spring-boot-starter-tomcat dependencies, as demonstrated in the example below.
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>

   <parent>

      <groupId>org.springframework.boot</groupId>

      <artifactId>spring-boot-starter-parent</artifactId>

      <version>3.0.4</version>

      <relativePath/> <!-- lookup parent from repository -->

   </parent>

   <groupId>com.practice</groupId>

   <artifactId>spring-boot</artifactId>

   <version>0.0.1-SNAPSHOT</version>

   <name>Spring Boot Practice</name>

   <description>Spring Boot Practice Project</description>

   <properties>

      <java.version>17</java.version>

   </properties>

   <dependencies>

      <dependency>

         <groupId>org.springframework.boot</groupId>

         <artifactId>spring-boot-starter-web</artifactId>

      </dependency>



	 <dependency>

       <groupId>org.springframework.boot</groupId>

         <artifactId>spring-boot-starter-test</artifactId>

         <scope>test</scope>

	</dependency>



<!-- Add spring-boot-starter-web or spring-boot-starter-tomcat -->



<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-tomcat</artifactId>

</dependency>



<!-- Add spring-boot-starter-web or spring-boot-starter-tomcat -->



   </dependencies>

</project>


After following the above two approaches, the error finally disappeared and the spring application start successfully as shown from the console.

 .   ____          _            __ _ _

 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \

( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \

 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )

  '  |____| .__|_| |_|_| |_\__, | / / / /

 =========|_|==============|___/=/_/_/_/

 :: Spring Boot ::                (v3.0.4)


2023-03-09T09:46:05.540+05:00  INFO 40009 --- [           main] c.p.s.SpringBootPracticeApplication      : Starting SpringBootPracticeApplication using Java 19.0.1 with PID 40009 (/home/muhammad/IdeaProjects/spring-boot/target/classes started by muhammad in /home/muhammad/IdeaProjects/spring-boot)

2023-03-09T09:46:05.545+05:00  INFO 40009 --- [           main] c.p.s.SpringBootPracticeApplication      : No active profile set, falling back to 1 default profile: "default"

2023-03-09T09:46:06.501+05:00  INFO 40009 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)

2023-03-09T09:46:06.509+05:00  INFO 40009 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]

2023-03-09T09:46:06.510+05:00  INFO 40009 --- [           main] o.apache.catalina.core.StandardEngine    : Starting Servlet engine: [Apache Tomcat/10.1.5]

2023-03-09T09:46:06.585+05:00  INFO 40009 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext

2023-03-09T09:46:06.585+05:00  INFO 40009 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 972 ms

2023-03-09T09:46:06.964+05:00  INFO 40009 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''

2023-03-09T09:46:06.972+05:00  INFO 40009 --- [           main] c.p.s.SpringBootPracticeApplication      : Started SpringBootPracticeApplication in 1.927 seconds (process running for 2.661)


Conclusion

That's all about how to fix "Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean" error in Spring Boot. . The main subject of this post is the Spring Boot problem Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean. 

We have explored two methods to address this issue. The first step is to choose the appropriate Spring annotation, and the second is to add the missing dependency to your build.gradle or pom.xml file. I hope the information in this post has helped you to correct the issue. For more such helpful articles keep following us.

How to fix "not a managed type exception" in JPA? [Solution]

Hello folks, JPA (Java Persistence API) is a widely used technology in Java applications for object-relational mapping (ORM) and working with databases. However, when using JPA, you may encounter the "not a managed type" exception, which is a common error that occurs when JPA fails to recognize an entity class as a managed type. This exception can occur due to various reasons, such as incorrect package or class names, missing annotations, or misconfiguration of JPA settings. Fixing this error requires identifying the root cause and taking appropriate steps to resolve it. In this article, we will explore different strategies and solutions to fix the "not a managed type" exception in JPA, helping you overcome this hurdle and successfully work with JPA in your Java applications.

'javac' is not recognized as an internal or external command [Solution]

'javac' is not recognized as an internal or external command, operable program, or batch file error comes when you try to compile a Java source file using the javac command like javac Helloworld.java but your PATH is not set properly. It means that the javac.exe executable file, which exists in the bin directory of the JDK installation folder is not added to the PATH environment variable. You need to add the JAVA_HOME/bin folder in your machine's PATH to solve this error. You cannot compile and run a Java program until your add Java into your system's PATH variable

How to Fix java.lang.OufOfMemoryError: Direct Buffer Memory

Java allows an application to access non-heap memory by using a direct byte buffer. Many high-performance applications use a direct byte buffer, along with a memory-mapped file for high-speed IO. And, while the ByteBuffer object is small itself, it can hold a large chunk of non-heap memory, which is outside of the Garbage collection scope.  This means the garbage collectors can not reclaim this memory. It is often used to store large data like order or static data cache. Since generally, your program allocates the large buffer e.g. size of 1GB or 2GB, you get "Exception in thread "main" java.lang.OutOfMemoryError: Direct buffer memory" error, when you try to allocate memory by running the following code

How to Fix with java.net.SocketException: Connection reset Exception in Java? Examples

Hello guys, for the past few months, I have been writing about different socket-related errors on Java applications, and today I am going to talk about another common socket-related exception in Java -  java.net.SocketException: Connection reset Exception. There is no difference between exceptions thrown by the client and server. This is also very similar to the java.net.SocketException: Failed to read from SocketChannel: Connection reset by a peer but there is some subtle difference. The difference between connection reset and connection reset by peer is that the first means that your side reset the connection, the second means the peer did it. Nothing to do with clients and servers whatsoever