Sunday, May 25, 2025

SpringBoot application properties

 What happens when you have default yaml or properties file along with the profile specific yml or properties files. eg: you have application.yml and application-dev.yml, application-test.yml, application-prod.yml


1. Default Behavior (No Active Profile)

  • Only application.yml is loaded

  • All other profile-specific files (-dev.yml, -test.yml, -prod.yml) are ignored

  • Useful for shared configurations (e.g., app name, default server port)


2. When a Profile is Activated

If you activate a profile (e.g., dev):

  1. application.yml is loaded first (base config)

  2. application-dev.yml is merged on top, overriding matching properties

  3. Other profile files (-test.yml, -prod.yml) are ignored

Example:

yaml
Copy
Download
# application.yml (shared)
server:
  port: 8080
logging:
  level:
    root: INFO

# application-dev.yml (dev-only)
logging:
  level:
    root: DEBUG
    org.hibernate.SQL: TRACE

Result (--spring.profiles.active=dev):

yaml
Copy
Download
server:
  port: 8080  # From base
logging:
  level:
    root: DEBUG       # Overridden by dev
    org.hibernate.SQL: TRACE  # Added by dev

3. Key Rules

RuleExplanation
Profile-specific files override baseapplication-dev.yml wins over application.yml
Last profile winsIf multiple profiles are active (dev,test), the rightmost profile's config takes precedence
Non-conflicting properties mergeUnique properties from all files are combined
spring.profiles.includeForce-include additional profiles (e.g., spring.profiles.include: db,security)

4. How to Activate Profiles

Option 1: Command Line

sh
Copy
Download
java -jar app.jar --spring.profiles.active=prod

Option 2: Environment Variable

sh
Copy
Download
export SPRING_PROFILES_ACTIVE=test  # Linux/macOS
set SPRING_PROFILES_ACTIVE=test     # Windows

Option 3: In application.yml

yaml
Copy
Download
spring:
  profiles:
    active: dev  # Default profile (not recommended for production)

5. Advanced: Multi-Profile Activation

You can activate multiple profiles (e.g., dev + db-mysql):

sh
Copy
Download
--spring.profiles.active=dev,db-mysql

Spring Boot merges them in order (rightmost profile wins conflicts).


6. Best Practices

  1. application.yml → Store default/shared configs

  2. application-{profile}.yml → Store environment-specific overrides

  3. Never commit secrets → Use application-{profile}.yml with Vault/Env vars for prod credentials

  4. Use spring.config.activate.on-profile (YAML only) to conditionally include sections:

    yaml
    Copy
    Download
    # In application.yml
    spring:
      config:
        activate:
          on-profile: "dev"
    logging:
      level:
        root: DEBUG

7. Debugging Configuration

Check which profiles are active and property sources:

sh
Copy
Download
# Enable debug mode
java -jar app.jar --debug

Look for:

Copy
Download
The following profiles are active: dev
Property Sources:
  - application.yml
  - application-dev.yml

Summary

  • Base + Profile-Specific: Configs merge, with profile files overriding defaults

  • Profile Activation: Controls which -{profile}.yml files are loaded

  • Order Matters: Last profile in a comma-separated list has highest priority

This system allows clean separation of environments while avoiding duplication.

Tuesday, September 10, 2024

Create Pdf with ITEXT

 ITEXT is one of the most common libraries used to create pdf files. you can get the library from the maven repository. below is the latest version as of now.

<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.4</version>
</dependency>

If you have fair knowledge in java, it is more than enough to create a use Itext and generate a PDF file.

you can create a java project, mostly a springboot project via https://start.spring.io/

Then you can add the maven dependency. Here i use maven, but you can use anything eg:gradle

In this example i have added

1. plain text

2. some Alignment with text

3. insert an image ( keep image in classpath)

package com.example.poc.pdf.itext.sample;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;

public class ExperienceLetter {

private static String FILE = "C:\\Project\\PoC\\docs\\Experience.pdf";

private static Font TO = new Font(Font.FontFamily.TIMES_ROMAN, 12,
Font.BOLD);
private static Font TO_DATA = new Font(Font.FontFamily.TIMES_ROMAN, 12);
private static Font TITLE = new Font(Font.FontFamily.TIMES_ROMAN, 12,
Font.BOLD | Font.UNDERLINE);

private static Font BODY = new Font(Font.FontFamily.TIMES_ROMAN, 11);

public static void main(String[] args) {
try {
//create Doc
Document document = new Document();
// pdf file
PdfWriter.getInstance(document, new FileOutputStream(FILE));
//open doc
document.open();
// add each section
// add metadata
addMetaData(document);
//
addParaTo(document);
addTitle(document);

addBody(document, "EMPLYEE NAME", "DESIGNATION", "2022-01-01", "2024-02-01", 2);

addSignature(document);
// close doc
document.close();
} catch (DocumentException e) {
throw new RuntimeException(e);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}

public static void addMetaData(Document document) {
document.addTitle("Sample Pdf");
document.addSubject("Using iText");
document.addKeywords("Java, PDF, iText");
document.addAuthor("Amal Prasad");
document.addCreator("Amal Prasad");
}

public static void addParaTo(Document document)
throws DocumentException {
Paragraph toPara = new Paragraph();
addEmptyLine(toPara, 1);
// Lets write a big header
toPara.add(new Paragraph("TO:", TO));

addEmptyLine(toPara, 1);
toPara.add(new Paragraph("Employee Name", TO_DATA));
toPara.add(new Paragraph("Employee ID:", TO_DATA));
toPara.add(new Paragraph("Address Line 1", TO_DATA));
toPara.add(new Paragraph("Address Line 2", TO_DATA));
toPara.add(new Paragraph("City", TO_DATA));
toPara.add(new Paragraph("Country", TO_DATA));

document.add(toPara);
}

public static void addTitle(Document document)
throws DocumentException {
// create Para
Paragraph title = new Paragraph();
title.setAlignment(Element.ALIGN_CENTER);
addEmptyLine(title, 2);
title.add(new Paragraph("TO WHOM IT MAY CONCERN", TITLE));
title.setAlignment(Element.ALIGN_CENTER);

//add para to doc
document.add(title);
}

public static void addBody(Document document, String employeeName, String designation, String workStartDate, String workEndDate, int yearsOfExperience)
throws DocumentException {
StringBuilder experience = new StringBuilder("This letter is to certify that ");
experience.append(employeeName);
experience.append(" has worked in our organisation as ");
experience.append(designation);
experience.append(".");

experience.append("He had started working here on dated ");
experience.append(workStartDate);
experience.append(" and worked till dated ");
experience.append(workEndDate);
experience.append(".");


experience.append("He had served the company for about ");
experience.append(yearsOfExperience);
experience.append(" years.");
// create Para
Paragraph body = new Paragraph();

addEmptyLine(body, 2);
body.add(new Paragraph(experience.toString(), BODY));

//add para to doc
document.add(body);

// create Para
Paragraph bodyPart2 = new Paragraph();
addEmptyLine(bodyPart2, 1);
StringBuilder expereincePart2 = new StringBuilder("Until the day he joined, he had been quite responsible.");
expereincePart2.append("To date, he has accumulated a diverse set of talents and job experiences");
expereincePart2.append("His mind blowing abilities include: Team work,Management skills and Analytical skills");
expereincePart2.append("");

bodyPart2.add(new Paragraph(expereincePart2.toString(), BODY));
document.add(bodyPart2);

Paragraph bodyPart3 = new Paragraph();
addEmptyLine(bodyPart3, 1);

StringBuilder expereincePart3 = new StringBuilder("We wish him all the best for his future endeavours.");

bodyPart3.add(new Paragraph(expereincePart3.toString(), BODY));

addEmptyLine(bodyPart3, 1);
document.add(bodyPart3);
}

public static void addEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i < number; i++) {
paragraph.add(new Paragraph(" "));
}
}

public static void addSignature(Document document) throws URISyntaxException, DocumentException, IOException {
String imagePath = "signature.jpg";
Path path = Paths.get(ClassLoader.getSystemResource(imagePath).toURI());
// System.out.println(path.toAbsolutePath());
// String classpath = System.getProperty("java.class.path");
// String[] classpathEntries = classpath.split(File.pathSeparator);
// System.out.println(Arrays.toString(classpathEntries));
Image signImage = Image.getInstance(path.toAbsolutePath().toString());
// signImage.setAlignment(Image.LEFT | Image.TEXTWRAP);
signImage.setAlignment(Image.ALIGN_CENTER);
// signImage.setBorder(Image.BOX);
// signImage.setBorderWidth(15);
signImage.scaleToFit(100, 100);

document.add(signImage);

//////
// create Para
Paragraph afterSignature = new Paragraph();
// addEmptyLine(afterSignature, 3);
afterSignature.add(new Paragraph("Authorized Signatory", BODY));
document.add(afterSignature);
}


}


Explaining the main functionalities

1. Create a Document

//create Doc
Document document = new Document();

2. Create PDF writer instance to write input to generating pdf.

// pdf file
PdfWriter.getInstance(document, new FileOutputStream(FILE));

3. As we have added writer, Now let's open doc.

//open doc
document.open();

4. Do the functionalities/ or operations you need.

eg: add Meta data for the pdf. This also not need. BUt you can add , if you need.

public static void addMetaData(Document document) {
document.addTitle("Sample Pdf");
document.addSubject("Using iText");
document.addKeywords("Java, PDF, iText");
document.addAuthor("Alex Crow");
document.addCreator("Alex Crow");
}

you can add Text as Paragraph. Below example will help. Here we create a Paragraph. add content as Paragraphs.  After that add the Paragraph to the document, you already opened.

public static void addParaTo(Document document)
throws DocumentException {
Paragraph toPara = new Paragraph();
addEmptyLine(toPara, 1);
// Lets write a big header
toPara.add(new Paragraph("TO:", TO));

addEmptyLine(toPara, 1);
toPara.add(new Paragraph("Employee Name", TO_DATA));
toPara.add(new Paragraph("Employee ID:", TO_DATA));
toPara.add(new Paragraph("Address Line 1", TO_DATA));
toPara.add(new Paragraph("Address Line 2", TO_DATA));
toPara.add(new Paragraph("City", TO_DATA));
toPara.add(new Paragraph("Country", TO_DATA));

document.add(toPara);
}

you can use below functionality to add some empty lines

public static void addEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i < number; i++) {
paragraph.add(new Paragraph(" "));
}
}

Add Image

    public static void addSignature(Document document) throws URISyntaxException, DocumentException, IOException {
String imagePath = "signature.jpg";
Path path = Paths.get(ClassLoader.getSystemResource(imagePath).toURI());
Image signImage = Image.getInstance(path.toAbsolutePath().toString());
signImage.setAlignment(Image.ALIGN_CENTER);
signImage.scaleToFit(100, 100);

document.add(signImage);
}

Here we have added an image of an signature.

5. Finally Close the doc.

// close doc
document.close();