Thursday, April 20, 2023

How to resolve the error 'Failed to load driver class com.mysql.cj.jdbc.Driver in either of HikariConfig class loader or Thread context classloader'

How to resolve the error 'Failed to load driver class com.mysql.cj.jdbc.Driver in either of HikariConfig class loader or Thread context classloader'

The error message "Failed to load driver class com.mysql.cj.jdbc.Driver in either of HikariConfig class loader or Thread context classloader" typically occurs when a Java application using the HikariCP connection pool is unable to load the MySQL JDBC driver class.

This error can have several causes, including:

  • The MySQL JDBC driver is not included in the project dependencies.
  • The MySQL JDBC driver JAR file is not in the classpath.
  • The driver class name is misspelled or not specified correctly in the configuration.
  • The MySQL JDBC driver version is not compatible with the current version of the application or the JVM.
screenshot of postman with the json in the body section

Solution :

Just add a specific version to the pom file

<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<version>8.0.25</version>
</dependency>
    

In conclusion, the "Failed to load driver class com.mysql.cj.jdbc.Driver in either of HikariConfig class loader or Thread context classloader" error can be frustrating and time-consuming to resolve. However, by following the step-by-step solution outlined in this blog, you can quickly identify and fix the root cause of the error.

Remember to ensure that the MySQL JDBC driver is included in the project dependencies and classpath, double-check the spelling and version compatibility of the driver class name, and make any necessary updates to your configuration file.

By resolving this error, you can get back to developing your Java applications with the confidence that your connection pool is working correctly.

How to resolve the error "docker: Error response from daemon: Conflict. The container name '/mysql' is already in use by container '421345f4e65f4e564f5e6fa5ef65we6f4af4af56a46fe4a'. You have to remove (or rename) that container to be able to reuse that name"

How to resolve the error "docker: Error response from daemon: Conflict. The container name '/mysql' is already in use by container '421345f4e65f4e564f5e6fa5ef65we6f4af4af56a46fe4a'. You have to remove (or rename) that container to be able to reuse that name"

The error "docker: Error response from daemon: Conflict. The container name '/mysql' is already in use by container '421345f4e65f4e564f5e6fa5ef65we6f4af4af56a46fe4a'. You have to remove (or rename) that container to be able to reuse that name" is caused by attempting to create a new container with a name that is already in use by an existing container. Docker does not allow multiple containers to have the same name, so this conflict must be resolved before the new container can be created.

screenshot of postman with the json in the body section

Solution :

To resolve this error, you need to remove or rename the existing container before you can create a new container with the same name. You can remove the existing container using the following command:

    	docker rm 421345f4e65f4e564f5e6fa5ef65we6f4af4af56a46fe4a
    

This command will remove the container with the specified container ID. Alternatively, you can remove all stopped containers using the following command:

    	docker container prune
    

After you have removed the existing container, you should be able to create a new container with the same name.

Sunday, April 16, 2023

How to resolve the error 'Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.7.1, expected version is 1.1.15' in IntelliJ IDEA

How to resolve the error 'Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.7.1, expected version is 1.1.15'

This error occurs when there is a mismatch between the version of Kotlin used to compile a module and the version expected by the Kotlin runtime environment. Specifically, the binary version of metadata generated during compilation is not compatible with the expected version, which leads to the error message. This can happen if you are using an outdated version of Kotlin or if you have multiple versions installed and the wrong version is being used. It can also occur if you are using a library or module that was compiled with a different version of Kotlin than the one used in your project.

screenshot of postman with the json in the body section

Solution :

in IntelliJIdea goto Settings -> Plugins -> search for Kotlin in the installed plugins

screenshot of postman with the json in the body section

simply disable the kotlin plugin, and you will get rid of this error.

Friday, April 14, 2023

How to convert JSON to PDF using iText library

How to convert JSON to PDF using iText library

In today's world, the exchange of data and information is an essential part of everyday life. With so much information being shared in different formats, it's important to know how to convert data from one format to another. In this blog post, we will be discussing how to convert JSON data to a PDF file using the iText library.

iText is a popular Java library for creating and manipulating PDF files. It provides a set of APIs for working with PDF documents, including text extraction, merging, and splitting PDF files, and creating PDF forms. It also supports the conversion of JSON data to PDF.

Prerequisites:
Before we dive into the process of converting JSON to PDF using the iText library, make sure that you have the following prerequisites in place:

  • Java Development Kit (JDK) version 1.8 or later
  • iText library version 5 or later
  • A JSON file / or JSON String that you want to convert to PDF
  • A basic understanding of Java programming

Steps to Convert JSON to PDF using iText: Now that we have the prerequisites in place, let's take a look at the steps involved in converting JSON data to a PDF file using the iText library.

Step 1: add maven dependencies

      <dependency>
         <groupId>com.itextpdf</groupId>
         <artifactId>itextpdf</artifactId>
         <version>5.5.13.3</version>
      </dependency>

      <dependency>
         <groupId>com.google.code.gson</groupId>
         <artifactId>gson</artifactId>
         <version>3.10</version>
      </dependency>
    

Step 2: convert json string to JsonObject

Step 3: create iText pdf document with desired page size and path of output file location

Step 4: create PdfPtable

Step 5: populate data in to the table

Step 6: add the table to document

Step 7: close the document

      package com.itext.jsontopdf;

      import com.google.gson.*;
      import com.itextpdf.text.*;
      import com.itextpdf.text.pdf.PdfPCell;
      import com.itextpdf.text.pdf.PdfPTable;
      import com.itextpdf.text.pdf.PdfWriter;
      import org.springframework.web.bind.annotation.*;

      import java.io.FileOutputStream;
      import java.util.Iterator;
      import java.util.Map;

      @RestController
      public class PDFController {

          @ResponseBody
          @PostMapping("/convertToPdf")
          public String convertJsonToPdf(@RequestBody String jsonData) {
              String msg = "";
              try {
                  //2. converting json string to jsonObject
                  Gson gson = new Gson();
                  JsonParser parser = new JsonParser();
                  JsonArray array = parser.parse(jsonData).getAsJsonArray();
                  JsonObject object = new JsonObject();
                  object.add("item", array);
                  JsonObject jsonObject = gson.fromJson(object, JsonObject.class);

                  //3. create iText pdf document
                  Document document = new Document(PageSize.A4);
                  PdfWriter.getInstance(document, new FileOutputStream("/home/viveksoni/Documents" + "/jsontopdf.pdf"));
                  document.open();

                  /**
                   * we are taking the numOfColumn so we can use this ahead while declaring pdf table
                   */
                  int numColumns = getNumOfColumns(jsonObject);

                  //4.
                  PdfPTable table = new PdfPTable(numColumns);

                  Paragraph heading = new Paragraph("Student Data");
                  heading.setAlignment(Element.ALIGN_CENTER);
                  document.add(heading);
                  document.add(new Paragraph("\n"));

                  //5. populate data in to the table
                  // filling the header
                  for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
                      for (JsonElement element : entry.getValue().getAsJsonArray()) {
                          Iterator<Map.Entry<String, JsonElement>> iterator = ((JsonObject) element).entrySet().iterator();
                          while (iterator.hasNext()) {
                              Font boldFont = new Font(Font.FontFamily.COURIER, 10, Font.BOLD);
                              table.addCell(new PdfPCell(new Phrase(iterator.next().getKey(), boldFont)));
                          }
                          break;
                      }
                  }

                  // filling the data
                  for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
                      for (JsonElement element : entry.getValue().getAsJsonArray()) {
                          Iterator<Map.Entry<String, JsonElement>> iterator = ((JsonObject) element).entrySet().iterator();
                          while (iterator.hasNext()) {
                              Font normalFont = new Font(Font.FontFamily.COURIER, 9, Font.NORMAL);
                              JsonElement jsonElement = iterator.next().getValue();
                              String value = "";
                              if (jsonElement != null && !jsonElement.isJsonNull()) {
                                  value = jsonElement.getAsString();
                              }
                              Phrase phrase = new Phrase(value + " ", normalFont);
                              PdfPCell cell = new PdfPCell(phrase);
                              table.addCell(cell);
                          }
                      }
                  }

                  //6. add the table to the document
                  document.add(table);
                  //7. close the document
                  document.close();

                  msg = "PDF conversion is successful";
              } catch (Exception e) {
                  e.printStackTrace();
                  msg = "PDF conversion failed due to : " + e.getMessage();
              }
              return msg;
          }

          private int getNumOfColumns(JsonObject jsonObject) {
              int numColumns = 0;
              for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
                  for (JsonElement element : entry.getValue().getAsJsonArray()) {
                      numColumns = ((JsonObject) element).entrySet().size();
                      break;
                  }
              }
              return numColumns;
          }
      }
    

Step 8: test the application using postman

make a post request with the following url - http://localhost:8080/convertToPdf

screenshot of postman with the url to be hit

write your json in the body section of the postman hit send

screenshot of postman with the json in the body section

you will receive a 200 response and a file created on the provided path

screenshot of postman with the json in the body section screenshot of postman with the json in the body section

source code on github